import React, { useEffect, useState } from 'react';
import { Modal, Form, Button, Input, Space, Select, Switch, Radio } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

import { LoadLedgers } from '@/services/tablemanager/tablemanager';

const ParmarModal = props => {
  const { pageUrl, visible, handleCancel, parmarCallBack } = props;
  const [form] = Form.useForm();
  const [keepStandingBook, setKeepStandingBook] = useState([]);
  const [visibleChecked, setVisibleChecked] = useState(true);
  const [mappingData, setMappingData] = useState(['事件编号', '工单编号']);
  const { Option } = Select;
  useEffect(() => {
    if (visible) {
      LoadLedgers().then(res => {
        if (res.code === 0) {
          let data = [];
          res.data.root.map(i => {
            data.push(i.name);
          });
          setKeepStandingBook(res.data.root);
        }
      });
      // 给url通过字符串分割成表单需要的数据形式
      console.log(pageUrl);
      if (pageUrl) {
        if (pageUrl.indexOf('[') !== -1) {
          let data = JSON.parse(pageUrl);
          let list = [];
          if (data.mapping.length > 0) {
            data.mapping.map(i => {
              list.push(i.fromField);
            });
          }
          form.setFieldsValue({
            accountName: data.accountName,
            editable: data.editable,
            mapping: list,
          });
        }
      }
    } else {
      // 关闭弹窗清除表单数据
      form.resetFields();
    }
  }, [visible]);
  // 保存
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();
        // let parma = obj.parmars;
        let data = {};
        data.accountName = obj.accountName;
        data.editable = visibleChecked;
        data.mapping = [];
        if (obj.mapping) {
          obj.mapping.map(i => {
            data.mapping.push({ fromField: i, toField: i });
          });
        }
        // data.mapping = [{ fromField: obj.mapping, toField: obj.mapping }];
        // data.mapping = parma;
        parmarCallBack(JSON.stringify(data));
      }
    });
  };

  const change = e => {
    setVisibleChecked(e);
  };

  return (
    <div>
      <Modal
        title="参数配置"
        visible={visible}
        onOk={onFinish}
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
      >
        <div style={{ maxHeight: '400px', overflowY: 'scroll', marginBottom: '10px' }}>
          <Form name="form" form={form} labelCol={{ span: 4 }}>
            <Form.Item
              label="台账名"
              name="accountName"
              rules={[{ required: true, message: '请选择台账名' }]}
            >
              <Select placeholder="请选择台账名" showSearch>
                {keepStandingBook
                  ? keepStandingBook.map((item, index) => (
                    <Option key={index} value={item.name}>
                      {item.name}
                    </Option>
                  ))
                  : ''}
              </Select>
            </Form.Item>
            <Form.Item label="可编辑" name="editable">
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                checked={visibleChecked}
                onChange={change}
              />
            </Form.Item>
            <Form.Item label="映射字段" name="mapping">
              <Select placeholder="请选择映射字段" showSearch mode="multiple">
                {mappingData.map((item, index) => (
                  <Option key={index} value={item}>
                    {item}
                  </Option>
                ))}
              </Select>
              {/* <Form.List name="parmars">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, fieldKey, ...restField }) => (
                      <Space
                        key={key}
                        style={{ display: 'flex', marginBottom: '5px', justifyContent: 'center' }}
                        align="baseline"
                      >
                        <Form.Item
                          {...restField}
                          style={{ marginBottom: '5px' }}
                          name={[name, 'fromField']}
                          fieldKey={[fieldKey, 'key']}
                          validateTrigger={['onChange', 'onBlur']}
                          rules={[
                            { required: true, message: '请选择字段名' },
                            {
                              validator: () => {
                                // 验证参数名不能重复
                                const allKey = form
                                  .getFieldsValue()
                                  .parmars.map(item => (item ? item.fromField : ''));
                                const repeatKey = new Set(allKey);
                                if (repeatKey.size !== allKey.length) {
                                  return Promise.reject(new Error('参数名重复'));
                                }
                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <Input placeholder="请选择字段名" />
                        </Form.Item>
                        <Form.Item
                          {...restField}
                          style={{ marginBottom: '5px' }}
                          name={[name, 'toField']}
                          fieldKey={[fieldKey, 'value']}
                          rules={[{ required: true, message: '请选择映射字段名' }]}
                        >
                          <Input placeholder="请选择映射字段名" />
                        </Form.Item>

                        <MinusCircleOutlined
                          onClick={() => remove(name)}
                          style={{ marginLeft: '10px', fontSize: '20px' }}
                        />
                      </Space>
                    ))}

                    <Form.Item>
                      <Button
                        style={{ width: '372px' }}
                        type="dashed"
                        onClick={() => add()}
                        block
                        icon={<PlusOutlined />}
                      >
                        添加参数
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List> */}
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </div>
  );
};

export default ParmarModal;
