import React, { useState,useRef,useEffect } from 'react';
import { PlusOutlined,CheckOutlined} from '@ant-design/icons';
import { Modal, Form, Input, Button, Select,Radio,message,Tag,Divider,Space } from 'antd';
import { AddBomType,getbyidbomlist } 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 [disaenumbled, setdisaenumbled] = useState('block');
  const [disnewd, setdisnewd] = useState('none');
  const [arttue,setarttue]=useState(1);
  const [arttuename,setarttuename]=useState("");
  const [arttuename11,setarttuename1]=useState("");
  const [checked,setchecked]=useState(false);
  const [bomNameRules,setbomNameRules]=useState([])
  const [bomTypeListRules,setbomTypeListRules]=useState([])
  const [bomcheckRules,setbomcheckRules]=useState([])
  const [recordCreatorProps,setrecordCreatorProps]=useState(false)
  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(() => {
    var ty=form.getFieldValue("type");
    console.log("props.Bomdata",form.getFieldValue("type"))
    console.log(props.goodsname)
    if(ty!=0){
      setdisaenumbled('block')
      setdisnewd("none");
      setbomcheckRules([{ required: true, message: '请选择配方' }])
      setbomNameRules( [{ required: false}])
      setbomTypeListRules([{ required: false}])
    }
    
    // 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("values",values)
      if(checkvalue.length==0){
        check=false;
        message.error("请选择商品属性")
      }else{
        data.shuxing=checkvalue;
      }
      if(disnewd=="block"){
        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();
        if(disaenumbled=="block"){
          data.Type="check"
        }else{
          data.Type="add"
        }
        data.goodsAttributeValue=arttuename
        data.bomType=1;
        data.bomName=values.bomName+"("+arttuename11+")"
        props.onFinish(data);
        setDataSource([])
        //setCheckvalue([])
        setarttuename("")
      }
      
    })
    .catch((info) => {
      message.error("请填写必填信息")
    });
  }
  const onChangevalue=(data)=>{
   const { name, value } = data.target;  
   let names="";
   let names1="";
   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;
        names1=names1+bs
        if(index< updatedValues.length-1){
          names=names+"-"
          names1=names1+"-"
        }
      }
     
     }
   })
   setarttuename1(names)
   setarttuename(names1)
  //  form.setFieldsValue({
  //   bomName: props.goodsname+"("+names+")"
  // });
   setCheckvalue(updatedValues)
  }
  const handleChange = (value) => {
    console.log(`selected ${value}`);
    form.setFieldsValue({
      bomId: value,
      //  bomType:1
    });
    getbyidbomlist(value).then((r)=>{
      let soredata=[];
      r.data?.bomEntry?.forEach((item,index)=>{
        var data={
          id:index,
          batchingId:item.batchingId,
          dosage:item.bomQty
        }
        soredata.push(data)
      })
      
      //setEditableRowKeys(soredata.map((item) => item.id))
      setDataSource(soredata);
    })
  };
  const onchagetype= (e) => {
    console.log(form)
    setarttue(e.target.value)
    //setCheckvalue([])
    setDataSource([])
    setchecked(false)
    if(e.target.value==1){//选择配方
      setrecordCreatorProps(false);
      setdisaenumbled("block")
      setdisnewd("none")
      setbomcheckRules([{ required: true, message: '请选择配方' }])
      setbomNameRules( [{ required: false}])
      setbomTypeListRules([{ required: false}])
    }else{
      setbomcheckRules([{ required: false }])
      setbomNameRules( [{ required: true, message: '请输入配方名称!' }])
      setbomTypeListRules([{ required: true, message: '配方分类' }])
      setrecordCreatorProps({ 
        newRecordType: 'dataSource',
        record: () => ({
          id: Date.now(),
        })})
      setdisaenumbled("none")
      setdisnewd("block")
    }
  }
  return (
    <Modal
      title={'关联配方'}
      width={1040}
      visible={props.handleCreateoodsBomModalVisible}
      bodyStyle={{ padding: '32px 40px 1px 48px' }}
      okText="确认"
        cancelText="取消"
        onOk={headleOk}
      onCancel={() => {
        props.onCancel();
      }}
      maskClosable={false}
      destroyOnClose
    >
        <span><span style={{color:'red',marginRight: 3}}>*</span>商品属性</span>
      {
            props.goodsAttriburteData == undefined ? '' :(
                props.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" 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>
                  );
                })
            )
        }
      <Form layout="horizontal" preserve={false}  form={form}>
      <Form.Item name="type" label="功能类型">
          <Radio.Group name="type" defaultValue={1} value={arttue} onChange={onchagetype}>
            <Radio.Button value={1}>选择配方</Radio.Button>
            <Radio.Button value={0}>新建配方</Radio.Button>
           
          </Radio.Group>
        </Form.Item>
       <Form.Item shouldUpdate style={{display:disaenumbled}} name="bomId" label="选择配方" rules={bomcheckRules}>
          <Select
            showSearch
            optionFilterProp="children"
            onChange={handleChange}
            placeholder="请选配方信息">
            
            {props.Bomdata?.map((item, index) => {
              return (
                <Option index={index} value={item.id} key={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
          
        </Form.Item>
      <Form.Item  style={{display:disnewd}} label="配方名称" name="bomName"  rules={bomNameRules}  >
        <Input   placeholder="请输入配方名称"/>
       
      </Form.Item>
      <Form.Item  style={{display:disnewd}} name="bomTypeList"   rules={bomTypeListRules} 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>
    
        <EditableProTable
        headerTitle={ <span><span style={{color:'red',marginRight: 3}}>*</span>配方详情</span>}
        columns={columns}
        rowKey="id"
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={recordCreatorProps}
   
        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;
