import React, {useState,useEffect } from 'react';
import { Modal, Form, Input, Button, Select } from 'antd';
import {
  EditableProTable
} from '@ant-design/pro-table';
import { useFetchData } from '@ant-design/pro-utils';
const CreateForm = (props) => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState([]);
  const [options,setoptions]=useState([]);
  useEffect(() => {
    console.log("props.values",props.values)
    if(props.values.id){
      form.setFieldsValue({
        id: props.values.id,
        templateName:props.values.templateName,
        deviceId:props.values.deviceId,
      });
      var data=props.values.warehousePostion.map(x=>{
        return {id: x.id,code:x.code,batchingId:x.batchingId}
      })
      setEditableRowKeys(data.map((item) => item.id))
      setDataSource(data)
    }
    var optdata=props.devicedata?.map((item, index) => {
      return {value:item.id,label:item.name}
    })
    setoptions(optdata);
  },[props])
  const columns=[
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
        title: '仓位编码',
        dataIndex: 'code',
      },
    {
        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: '45%',
      },
      // {
      //   title: '用量',
      //   dataIndex: 'dosage',
      //   valueType:'digit',
      //   width: '15%',
      // },
      // {
      //   title: '操作',
      //   valueType: 'option',
      //   width: '15%',
      //   render: () => {
      //     return null;
      //   },
      // },
  ]
  const handleChange=(value)=>{
    var device=props.devicedata.find(x=>x.id==value);
    console.log("device",device)
    if(device){
      var ary=[]
      for (let index = 0; index < device.productNumber; index++) {
        ary.push({id: index,code:'LC000'+(index+1),batchingId:''})
      }
      console.log("ary",ary)
      setEditableRowKeys(ary.map((item) => item.id))
      setDataSource(ary);
    }
  }
  const headleOk=()=>{
    form
    .validateFields()
    .then((data) => {
      var check=true
      if(dataSource.length==0){
        check=false;
        message.error("请选择物料")
      }
      if(check){
        data.warehousePostionData=dataSource
        props.handleAdd(data)
      }
    })
  }
  return (
    <Modal
      title={props.values.id ? '编辑' : '新建'}
      width={640}
      visible={props.createModalVisible}
      bodyStyle={{ padding: '32px 40px 48px' }}
      okText="确认"
      cancelText="取消"
      onOk={headleOk}
      onCancel={() => {
        props.onCancel();
        setDataSource([])
        setEditableRowKeys([])
      }}
      maskClosable={false}
      destroyOnClose
    >
      <Form
        layout="vertical"
        preserve={false}
        form={form}>
        <Form.Item name="id" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item label={"模板名称"} name="templateName"  rules={[{ required: true,max:50}]} >
          <Input />
        </Form.Item>
        <Form.Item label={"选择设备"} name="deviceId"  rules={[{ required: true,max:50}]} >
            <Select style={{width: '100%'}} allowClear showSearch
            optionFilterProp="children"  filterOption={(input, option) => (option?.label ?? '').includes(input)}
            filterSort={(optionA, optionB) =>
              (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase()) 
            }
            onChange={handleChange} options={options}/>
            
          
        </Form.Item>
        
        {/* <Form.Item>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item> */}
      </Form>
      <EditableProTable
       headerTitle={ <span><span style={{color:'red',marginRight: 3}}>*</span>仓位详情</span>}
        columns={columns}
        rowKey="id"
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={false}
        // recordCreatorProps={{
        //   newRecordType: 'dataSource',
        //   record: () => ({
        //     id: Date.now(),
        //     code:'',
        //     batchingId:''
        //   }),
        // }}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [];
          },
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onDelete:async (key, row) =>{
            console.log(key)
            console.log(row)
            
          },
          onChange: setEditableRowKeys,
        }}/>
    </Modal>
  );
};

export default CreateForm;
