import React, { useState, useEffect } from 'react';
import moment from 'moment';
import {
  Modal,
  Form,
  Input,
  Button,
  Select,
  InputNumber,
  Col,
  Popover,
  Row,
  TreeSelect,
} from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { EditableProTable } from '@ant-design/pro-table';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import styles from './style.less';
import Productlist from '../../dialog/Productlist';
import { getEntryPage } from '../services';
const fieldLabels = {
  sheetId: '单据号',
  operDate: '单据日期',
  orgId: '收货机构',
  remark: '备注',
};
const defaultData = [];
const CreateForm = (props) => {
  const [error, setError] = useState([]);
  const [ShowModalVisible, handleModalVisible] = useState(false);
  const { createModalVisible, onCancel } = props;
  const getTableInfo = async () => {
    defaultData.length = 0;
  };
  useEffect(() => {
    getTableInfo();
  }, [createModalVisible]);
  const getErrorInfo = (errors) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }

    const scrollToField = (fieldKey) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);

      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };

    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }

      const key = err.name[0];
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode;
            }

            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };
  const onFinishFailed = (errorInfo) => {
    setError(errorInfo.errorFields);
  };

  const columns = [
    {
      title: '物料id',
      dataIndex: 'id',
      key: 'id',
      hideInTable: true,
      editable: false,
    },
    {
      title: '多条码id',
      dataIndex: 'codeId',
      key: 'codeId',
      hideInTable: true,
      editable: false,
    },
    {
      title: '条码',
      dataIndex: 'code',
      key: 'code',
      renderFormItem: () => (
        <Input.Search
          placeholder="请选择物料"
          onSearch={() => {
            handleModalVisible(true);
          }}
        />
      ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      editable: false,
    },
    {
      title: '库存单位',
      dataIndex: 'stockUint',
      valueType: 'select',
      fieldProps: {
        options: props.uintList,
      },
    },
    {
      title: '包装单位',
      dataIndex: 'packUnit',
      valueType: 'select',
      fieldProps: {
        options: props.uintList,
      },
    },
    {
      title: '换算比例',
      dataIndex: 'proportion',
    },
    {
      title: '入库数量',
      dataIndex: 'packQty',
      key: 'packQty',
      valueType: 'digit',
    },
    {
      title: '库存数量',
      dataIndex: 'stockQty',
      key: 'stockQty',
      valueType: 'digit',
      render: (_, row, index, action) => {
        if (typeof row.packQty == 'undefined') {
          return 0;
        }
        return row.packQty * row.proportion;
      },
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record, index, action) => {
        return [
          <a
            key="eidit"
            onClick={(res) => {
              action?.startEditable(record.id);
            }}
          >
            编辑
          </a>,
          <a
            key="delete"
            onClick={() => {
              action?.startEditable(record.id);
            }}
          >
            删除
          </a>,
        ];
      },
    },
  ];
  return (
    <Modal
      title={props.values.id ? '编辑' : '新建'}
      width={1000}
      visible={createModalVisible}
      onCancel={() => onCancel()}
      bodyStyle={{ padding: '32px 40px 48px' }}
      footer={null}
      destroyOnClose
      maskClosable={false}
    >
      <ProForm
        layout="horizontal"
        hideRequiredMark
        onFinish={props.onFinish}
        onFinishFailed={onFinishFailed}
        // initialValues={{
        //   billDate: Date.now(),
        // }}
        initialValues={props.values}
      >
        <Row gutter={16}>
          <Col lg={8} md={12} sm={24}>
            <ProForm.Item name="id" hidden={true}>
              <Input />
            </ProForm.Item>
            <ProForm.Item label={fieldLabels.sheetId} name="sheetId">
              <ProFormText disabled />
            </ProForm.Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <ProForm.Item name="orgId" label={fieldLabels.orgId}>
              <TreeSelect
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={props.OrgData}
                placeholder="请选择入库机构"
                treeDefaultExpandAll
              />
            </ProForm.Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <ProForm.Item>
              <ProFormDatePicker name="operDate" label={fieldLabels.operDate} />
            </ProForm.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col lg={16} md={12} sm={24}>
            <ProForm.Item label={fieldLabels.remark} name="remark">
              <ProFormText />
            </ProForm.Item>
          </Col>
        </Row>
        <ProForm.Item name="sub">
          <EditableProTable
            rowKey="id"
            recordCreatorProps={{
              record: () => {
                return {
                  id: `0${Date.now()}`,
                };
              },
            }}
            request={async () => {
              if (props.values.id != undefined) {
                const res = await getEntryPage({ id: props.values.id });
                const { data } = res;
                if (data && data.data && data.data.length) {
                  data.data.map((data) => {
                    defaultData.push(data);
                  });
                }
              }
              return {
                data: defaultData,
                total: 0,
                success: true,
              };
            }}
            columns={columns}
          />
        </ProForm.Item>
      </ProForm>
      <Productlist
        onSubmit={async (value) => {
          value.map((data) => {
            var aa = defaultData.filter((x) => x.code == data.code);
            console.log(aa.length);
            if (defaultData.filter((x) => x.code == data.code).length <= 0) {
              defaultData.push(data);
            }
          });
          handleModalVisible(false);
        }}
        onCancel={() => {
          handleModalVisible(false);
        }}
        IsVisible={ShowModalVisible}
      />
    </Modal>
  );
};

export default CreateForm;
