import { PlusOutlined,ArrowLeftOutlined } from '@ant-design/icons';
import { Button, message, Input, Form, Popconfirm,Radio,InputNumber,Card,Tag  } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import EditableProTable from '@ant-design/pro-table';

import { history } from 'umi';
import ProDescriptions from '@ant-design/pro-descriptions';
import {
  getpage,
  add,
  update,
  del,
  getbygoodsidattribute
} from './service';



const goodsattribute = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [editableKeys, setEditableRowKeys] = useState([]);
  /** 分布更新窗口的弹窗 */
  const [arttuename,setarttuename]=useState("");
  const [checkvalue, setCheckvalue] = useState([]);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [price, setprice] = useState(0);
  const [goodsAttriburteData, setGoodsAttriburteData] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  /** 国际化修改 */
  useEffect(() => {
    
    intDicData();
  }, []);
  function intDicData() {
    getbygoodsidattribute(props.location.query.values.id).then((r)=>{
      if(r.data && r.data.length>0){
        
          setGoodsAttriburteData(r.data);
        
      }
      
      
    })
  }

  /**
   * 批量删除
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    await del(selectedRows.map((row) => row.id)).then((r) => {
      if (r.succeeded) {
        message.success('删除成功');
        actionRef.current.reload();
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '属性',
      dataIndex: 'goodsattributeValue',
      valueType: 'textarea',
      ellipsis: true,
      readonly: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="config"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          更新
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            await del([record.id]).then((r) => {
              if (r.succeeded) {
                message.success('删除成功');
                actionRef.current.reload();
              } else {
                message.error(r.errors);
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];
const onChangevalue =(data)=>{
  const { name, value } = data.target;  
  let names="";
  let updatedValues = [...checkvalue]; 
  for (let index = 0; index <goodsAttriburteData.length; index++) {
   if (name === 'radiogroup'+index) {  
     // 将第一组的值累加到数组中  
     updatedValues[index] = value;  
    
   } 
  }

  goodsAttriburteData.forEach(item=>{
   for (let index = 0; index < updatedValues.length; index++) {
     var bs=item.goodsAttributeValueList.find(x=>x.goodsAttributeValuId==updatedValues[index])?.attributeValue
     if(bs){
       names=names+bs;
       if(index< updatedValues.length-1){
         names=names+"-"
       }
     }
    }
    item.goodsAttributeValueList.forEach(x=>{
      if(value==x.goodsAttributeValuId){
        x.check=true;
        item.defalutvalue=value
      }
    })
  })
  setarttuename(names)
  setCheckvalue(updatedValues)
}
const onpriceChange=(value)=>{
  setprice(value)
}
const onsubmit=()=>{
  var check=true;
  if(checkvalue.length==0){
    check=false;
    message.error("请选择属性");
  }
  else if(price<=0){
    check=false;
    message.error("价格不能小于0");
  }
  if(check){
    var parm={goodsId:props.location.query.values.id,goodsattributeValueId:checkvalue.join(','),Price:price,goodsattributeValue:arttuename}
    add(parm).then((r)=>{
      if (r.succeeded) {
        message.success('保存成功');
        actionRef.current.reload();
        setCheckvalue([]);
        setarttuename("");
        setprice(0)
        var gg=goodsAttriburteData.map(x => {
          x.goodsAttributeValueList.forEach(t=>{
              t.check=false;
              x.defalutvalue=""
          })
          return x
        })
        setGoodsAttriburteData(gg)
      } else {
        message.error(r.errors);
      }
    })
  }
  
}
const onresetsubmit=()=>{
  setCheckvalue([]);
        setarttuename("");
        setprice(0)
        var gg=goodsAttriburteData.map(x => {
          x.goodsAttributeValueList.forEach(t=>{
              t.check=false;
              x.defalutvalue=""
          })
          return x
        })
        setGoodsAttriburteData(gg)
}
  return (
    <>
    <PageContainer host header={{
      title: [<a  key="back"
      onClick={() => {
        history.push({
          pathname: '/database/goods/newgoods',
        });
      }}><ArrowLeftOutlined />返回</a>],
      breadcrumb: {},
    }}>
      <Card>
         <span><span style={{color:'red',marginRight: 3}}>*</span>商品属性</span>
    {
          goodsAttriburteData==undefined || goodsAttriburteData.length ==0 ? (   <div style={{fontSize: '12px',marginLeft:10}}>当前商品分类还未配置属性点击跳转  <a
            key="primary"
            type="primary"
            onClick={() => {
              history.push({
                pathname: '/database/goods/goodstypemanage',
                
              });
              // handleModalVisible(true);
              // setCurrentRow(record);
            }}
          >
            添加属性
          </a></div>) :(
              goodsAttriburteData.map((item, index) => {
                return (
                  <div style={{marginLeft: 80,marginBottom:10}}>
                     <div>
                          <span style={{marginRight: 10}}> <Tag color="blue">{item.attributeName}</Tag>：</span>
                          <span>
                          <Radio.Group name={"radiogroup"+index}  buttonStyle="solid" size="small" value={item.defalutvalue} onChange={onChangevalue}>
                              {
                                  item.goodsAttributeValueList.map((item, index)=>{
                                      return (
                                          <Radio.Button name={index} defaultChecked={item.check} checked={item.check} value={item.goodsAttributeValuId} style={{marginRight: 22, marginTop: 16}}>{item.attributeValue}</Radio.Button>
                                      )
                                  })
                              }
                          </Radio.Group>
                          </span>
                     </div>
                  </div>
                );
              })
          )
      }
   <div style={{marginTop:10}}>
   <span style={{marginRight:'3%'}}><span style={{color:'red',marginRight: 3}}>*</span>价格:</span><InputNumber value={price} style={{width:'20%'}} onChange={onpriceChange} placeholder="请输入价格"/>
   </div>
      
     <div style={{float:'right',position: 'absolute', top: '70%',left: '88%',width: '200px'}}>
      
    <Button  htmlType="submit" style={{marginRight:'2%'}}  onClick={onresetsubmit}> 重置</Button>
          <Button type="primary" htmlType="submit"  onClick={onsubmit}>
            保存
          </Button>
     </div>
   
  
    </Card>
      <EditableProTable
        headerTitle="属性价格列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={false}
        // toolBarRender={false}
        recordCreatorProps={false}
        request={async (params) => {
          var data = [];
          params.goodsId=props.location.query.values.id
          var total = 0;
          await getpage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
          onSave: async (rowKey, data, row) => {
            console.log(rowKey, data, row);
            update(data).then((res)=>{
              if (res.succeeded) {
                message.success('保存成功');
                actionRef.current.reload();
              } else {
                message.error(r.errors);
              }
            })
            //onsubmit()
          },
       
          onChange: setEditableRowKeys,
        }}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
    </PageContainer>
    </>
  );
};

export default goodsattribute;
