import React, { useState,useRef,useEffect } from 'react';
import { PlusOutlined} from '@ant-design/icons';
import { Modal, Form, Input, Button, Select,Radio,message,Tag,Divider,Space } from 'antd';
import { AddBomType,getproductpage } from '../service';
import {
  EditableProTable,
  ProTable
} from '@ant-design/pro-table';
const GoodsbomFrom = (props) => {
  const { Option, OptGroup } = Select;
  const [checkvalue, setCheckvalue] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState([]);
  const [form] = Form.useForm();
  const [typename, settypename] = useState('');
  const inputRef = useRef(null);
  const onNameChange=(event)=>{
    settypename(event.target.value);
  }
  const addItem=(e)=>{
    e.preventDefault();
   
    if(typename.length==0){
      message.error("请输入名称");
    }else{
      var parm={name:typename}
      AddBomType(parm).then((r)=>{
        if(r.succeeded){
          message.success('添加成功');
          props.initTypeList();
          settypename('');
        }else{
          message.error(r.errors);
        }
      })
    }
   
  }
  useEffect(() => {
    console.log("111111111")
    console.log(props.defaultmatedata)
    form.setFieldsValue({
      bomName: props.goodsname,
      //  bomType:1
    });
    if(props.defaultmatedata){
      let soredata=[];
      props.defaultmatedata.forEach((item,index)=>{
        var data={
          id:index,
          batchingId:item,
          dosage:0
        }
        
        soredata.push(data)
      })
      
      setEditableRowKeys(soredata.map((item) => item.id))
      setDataSource(soredata);
    }
  },[props])
  const columns=[
    {
        title: '物料名称',
        dataIndex: 'batchingId',
        formItemProps: (form, { rowIndex }) => {
          return {
            rules:
              rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
          };
        },
        valueType: 'select',
        fieldProps: {
          showSearch:true,
          options: props.matedata.map((item, index) => {return {label:item.name,value:item.id}})
        },
        width: '25%',
      },
      {
        title: '用量',
        dataIndex: 'dosage',
        valueType:'digit',
        width: '15%',
      },
      {
        title: '操作',
        valueType: 'option',
        width: '15%',
        render: () => {
          return null;
        },
      },
]
  const headleOk=()=>{
    form
    .validateFields()
    .then((values) => {
      var check=true;
      var data=values;
      console.log(dataSource)
      if(checkvalue.length==0){
        check=false;
        message.error("请选择商品属性")
      }else{
        data.shuxing=checkvalue;
      }
      if(dataSource.length==0){
        check=false;
        message.error("请选择物料")
      }else{
        data.mate=dataSource.map(x=>{return {batchingId:x.batchingId,dosage:x.dosage}});
      }
      if(check){
        form.resetFields();
        props.onFinish(data);
        setDataSource([])
      }
      
    })
    .catch((info) => {
      message.error("请填写必填信息")
    });
  }
  const onChangevalue=(data)=>{
   const { name, value } = data.target;  
   let names="";
   let updatedValues = [...checkvalue]; 
   for (let index = 0; index < props.goodsAttriburteData.length; index++) {
    if (name === 'radiogroup'+index) {  
      // 将第一组的值累加到数组中  
      updatedValues[index] = value;  
     
    } 
   }
   props.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+"-"
        }
      }
     
     }
   })
   
  
   form.setFieldsValue({
    bomName: props.goodsname+"("+names+")"
  });
   setCheckvalue(updatedValues)
  }
 
  return (
    <Modal
      title={'新建配方'}
      width={1040}
      visible={props.handleCreateoodsBomModalVisible}
      bodyStyle={{ padding: '32px 40px 1px 48px' }}
      okText="确认"
        cancelText="取消"
        onOk={headleOk}
      onCancel={() => {
        props.onCancel();
      }}
      maskClosable={false}
      destroyOnClose
    >
      <Form layout="horizontal" preserve={false}  form={form}
     >
      <Form.Item name="bomName" label="配方名称" rules={[{ required: true, message: '配方名称' }]}>
        <Input  placeholder="请输入配方名称"/>
      </Form.Item>
      <Form.Item name="bomTypeList" rules={[{ required: true, message: '配方分类' }]} label="配方分类" >
      <Select
              style={{width: '100%'}}
              mode="tags"
              placeholder="请选配方分类"
              options={props.bomTypeData}
              dropdownRender={(menu) => (
                <>
                {menu}
                <Divider style={{margin: '8px 0'}}/>
                <Space style={{padding: '0 8px 4px'}}>
                  <Input
                    placeholder="请输入配方分类"
                    ref={inputRef}
                    value={typename}
                    onChange={onNameChange}
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                  <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
                    新增
                  </Button>
                </Space>
                </>
              )}
            />
        </Form.Item>
        <Form.Item name="bomType" label="配方类型" initialValue='1' rules={[{ required: true, message: '配方类型' }]}>
          <Select
            placeholder="请选配方类型"
            onChange={(value) => {
              form.setFieldsValue({
                bomType:value
              });
            }}
          >
            <OptGroup>
              <Select.Option value="1">主料配方</Select.Option>
              <Select.Option value="0">辅料配方</Select.Option>
            </OptGroup>
          </Select>
        </Form.Item>
      </Form>

      
      <span><span style={{color:'red',marginRight: 3}}>*</span>商品属性</span>
      {
            props.goodsAttriburteData == undefined ? '' :(
                props.goodsAttriburteData.map((item, index) => {
                  return (
                    <div style={{marginLeft: 80}}>
                       <div>
                            <span style={{marginRight: 10}}> <Tag color="blue">{item.attributeName}</Tag>：</span>
                            <span>
                            <Radio.Group name={"radiogroup"+index}  buttonStyle="solid" size="small" onChange={onChangevalue}>
                                {
                                    item.goodsAttributeValueList.map((item, index)=>{
                                        return (
                                            <Radio.Button name={index} value={item.goodsAttributeValuId} style={{marginRight: 22, marginTop: 16}}>{item.attributeValue}</Radio.Button>
                                        )
                                    })
                                }
                            </Radio.Group>
                            </span>
                       </div>
                    </div>
                  );
                })
            )
        }
        <EditableProTable
        headerTitle={ <span><span style={{color:'red',marginRight: 3}}>*</span>配方详情</span>}
        columns={columns}
        rowKey="id"
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          record: () => ({
            id: Date.now(),
          }),
        }}
   
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete,defaultDoms.Button];
          },
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onDelete:async (key, row) =>{
            console.log(key)
            console.log(row)
            
          },
          onChange: setEditableRowKeys,
        }}/>
      {/* <ProTable
        headerTitle="选择物料"
        actionRef={actionRef}
        size="small"
        scroll={{x:200,y:200}}
        rowKey="id"
        search={false}
        request={async (params) => {
          let Data = [];
          var total = 0;
          await getproductpage(params).then((r) => {
            Data = r.data.data;
            total = r.data.total;
          });
          return {
            data: Data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}/> */}
    </Modal>
    //vessels
  );
};

export default GoodsbomFrom;
