import React, { useState, useEffect } from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Radio,
  Modal,
  Form,
  Input,
  Button,
  Select,
  InputNumber,
  DatePicker,
  Alert,
  TreeSelect,
  Space,
  message,
  Spin,
  
} from 'antd';
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { getEntry,getproductpage, getDeliveryEntry } from '../services';

const { Search } = Input;
const CreateForm = (props) => {
  const [form] = Form.useForm();
  const { Option, OptGroup } = Select;
  const [productList, setProductList] = useState([]);
  const [productListAll, setProductListAll] = useState([]);
  const [supplierList, setSupplierList] = useState([]);
  const [deliveryEntryList, setDeliveryEntryList] = useState([]);


  //初始化数据
  useEffect(() => {
    const initproductList = async (value) => {
      var data = (await getproductpage({ current: 1, pageSize: 10000000 })).data;
      if (data.data) {
        var list = [];
        data.data.forEach((element) => {
          list.push({
            key: element.code,
            name: element.name,
            id: element.id,
            packUnit: element.packUnit,
            stockUint: element.stockUint,
            proportion: element.proportion,
            code: element.code,
            productId: element.id

          });
        });
        setProductListAll(list);
        setProductList(list);
      }
    };
    initproductList();
  }, []);





  const formItemLayout = {
    labelCol: {
      //sm: { span: 8 },
    },
    wrapperCol: {},
  };
  const onTimeTypeChange = (value) => { };


  const onSearchDeliveryEntry = async (val) => {
    var list = [];
    const result = await getDeliveryEntry(val);
    if (result.data) {
      var newData = [];
      var list=result.data.deliveryEntryList;
     
      for (let index = 0; index < list.length; index++) {
        var data = productList.find(x => {
          if (x.key == list[index].barcode) {
            return x;
          }
        })
        newData[index] = {
          ...newData[index],
          code:list[index].barcode,
          stockUint: data?.stockUint,
          packUnit: data?.packUnit,
          proportion: data?.proportion,
          productId: data?.productId,
          packQty:  list[index].deliveryQty,
          stockQty:  list[index].qty,
        };
      }

      form.setFieldsValue({ sub: newData, });
    } else {
      message.error(val + '不在此采购单');
    }

  }

  function onSearch(val) {
    var list = [];
    // const result = productList.filter((item) => {
    //     console.log(item.name.indexOf(val) != -1);
    //   if (item.name.indexOf(val) != -1) {
    //     list.push(item);
    //   }
    // });
    // setProductList(list);
    // if ((val??'') !== '') {
    //   setProductList(productListAll);
    // }
  }
  return (
    <Modal
      title={props.values.id ? '编辑会员信息' : '新建会员信息'}
      width={1270}
      maskClosable={false}
      visible={props.createModalVisible}
      // bodyStyle={{ padding: '32px 40px 48px' }}
      footer={null} //底部内容
      //取消
      onCancel={() => {
        props.onCancel();
      }}
      //关闭时销毁 Modal 里的子元素
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 3 }}
        //layout='vertical'
        preserve={false}
        initialValues={props.values}
        onFinish={props.onFinish}
      >
        <Form.Item name="id" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item  name='deliveryShelfNo' label="收货单号">
          <Search placeholder="请输入收货单号" onSearch={onSearchDeliveryEntry} enterButton />
        </Form.Item>

        <Form.Item name="orgId" label="采购机构" rules={[{ required: true }]}>
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={props.OrgData}
            placeholder="收货机构"
            treeDefaultExpandAll
          />
        </Form.Item>


        <Form.Item name="remark" label="备注" rules={[{ max: 300 }]}>
          <Input placeholder="" />
        </Form.Item>

        <Form.Item name="sub" >
          <Form.List
            name="sub"    >
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, fieldKey, ...restField }) => (
                  <Space key={key} align="baseline">


                    <Form.Item
                      {...restField}
                      name={[name, 'productId']}
                      fieldKey={[fieldKey, 'productId']}
                      hidden={true}
                    >
                      <Input />
                    </Form.Item>

                    <Form.Item
                      style={{ width: '250px', }}
                      {...restField}
                      name={[name, 'code']}
                      fieldKey={[fieldKey, 'code']}
                      label="条码"
                      rules={[{ required: true }]}
                    >
                      <Select
                        showSearch
                        placeholder="请选择物料条码"
                        optionFilterProp="children"
                        onSearch={onSearch}
                        onPopupScroll={onSearch}
                        onChange={(value) => {
                          var data = productList.find(x => {
                            if (x.key == value) {
                              return x;
                            }
                          })
                          var newData = form.getFieldsValue().sub;
                          form.setFieldsValue({ sub: [], })
                          newData[key] = {
                            ...newData[key],
                            stockUint: data?.stockUint,
                            packUnit: data?.packUnit,
                            proportion: data?.proportion,
                            productId: data?.productId,
                            code: data?.code,
                          };
                          form.setFieldsValue({ sub: newData, });
                        }}
                      >
                        {productList.map((item, index) => {
                          return (
                            <Select.Option index={index} value={item.key} key={item.key}>
                              <span style={{ float: 'left' }}>{item.key}</span>
                              <span style={{ float: 'right', color: '#8492a6' }}>{item.name}</span>
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>


                    <Form.Item
                      {...restField}
                      name={[name, 'stockUint']}
                      fieldKey={[fieldKey, 'stockUint']}
                      label="库存单位"
                      style={{ width: '200px' }}
                      rules={[{ required: true }]}
                    >
                      <Select>
                        {props.uintList.map((item, index) => {
                          return (
                            <Select.Option index={index} value={item.value} key={item.value}>
                              {item.label}
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'packUnit']}
                      fieldKey={[fieldKey, 'packUnit']}
                      label="包装单位"
                      style={{ width: '200px' }}
                      rules={[{ required: true }]}
                    >
                      <Select>
                        {props.uintList.map((item, index) => {
                          return (
                            <Select.Option index={index} value={item.value} key={item.value}>
                              {item.label}
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'proportion']}
                      fieldKey={[fieldKey, 'proportion']}
                      style={{ width: '200px' }}
                      label="换算比例"
                      rules={[{ required: true }]}
                    >
                      <Input />
                    </Form.Item>

                    <Form.Item
                      {...restField}
                      name={[name, 'packQty']}
                      fieldKey={[fieldKey, 'packQty']}
                      style={{ width: '150px' }}
                      label="采购数量"
                    >
                      <InputNumber />
                    </Form.Item>

                    <Form.Item
                      {...restField}
                      name={[name, 'stockQty']}
                      style={{ width: '150px' }}
                      fieldKey={[fieldKey, 'stockQty']}
                      label="数量"
                    >
                      <InputNumber />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ float: 'right' }}>
            保存
          </Button>
        </Form.Item>
      </Form>
    </Modal >
  );
};

export default CreateForm;
