/* eslint-disable no-unused-expressions */
/* eslint-disable no-else-return */
/* eslint-disable prefer-destructuring */
import React, { useEffect, useState, useRef } from 'react';
import { GetMaplayerByTerminalType, GetLayerList, GetLayerFields } from '@/services/flow/flow';
import {
  Form,
  Modal,
  notification,
  Select,
  TreeSelect,
  Tag,
  Row,
  Col,
  Space,
  Tooltip,
  Button,
  Input,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './AddGIS.less';
import logo from '@/assets/images/icons/值映射.png';
const { Option } = Select;
const { TreeNode } = TreeSelect;

const AddModal = props => {
  const {
    onSubumit,
    handleCancel,
    visible,
    msg,
    modalType,
    tableField,
    addIndex,
    tableData,
  } = props;
  const [schemeValue, setSchemeValue] = useState([]);
  const [layerValue, setLayerValue] = useState([]);
  const [layerFields, setLayerFields] = useState([]);
  const layerData = useRef({});
  const [type, setType] = useState();
  const [flag, setFlag] = useState(0); // 刷新
  const [tableType, setTableType] = useState();
  const [tableName, setTableName] = useState();
  const [ruleList, setRuleList] = useState([]);
  const [tableShape, setTableShape] = useState();

  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      let arr = [];
      tableData.map(i => {
        arr.push(i.RuleName);
      });
      setRuleList(arr);
      getSchemeList();
      if (modalType === 'edit') {
        console.log(msg);
        form.setFieldsValue(msg);
        setTableShape(msg.tableShape);
        setTableType(msg.tableType);
        setTableName(msg.TableName);
      }
    } else {
      layerData.current = {};
      form.resetFields();
      setLayerFields([]);
      setLayerValue([]);
      setSchemeValue([]);
    }
  }, [visible]);

  const getSchemeList = () => {
    GetMaplayerByTerminalType({ terminalType: 'scheme', isBaseMap: false }).then(res => {
      if (res.code === '0') {
        setSchemeValue(res.data);
        if (modalType === 'edit') {
          getLayerList(msg.schemeName);
          let arr = [];
          tableField.map(item => {
            arr.push(...item.TableFields);
          });
          let data = arr.find(i => i.FieldName === msg.Fields);
          setType(data.FiledType);
          getLayerFields(msg[0].nodeName, '', res.data, data.FiledType);
          msg.users?.map((i, j) => {
            getLayerFields(i.nodeName, j, res.data, data.FiledType);
          });
        }
      }
    });
  };

  const getLayerList = val => {
    GetLayerList({ serviceName: val }).then(res => {
      if (res.success === true) {
        let data = res.root.filter(i => i.layerID < 1000);
        let last = data.filter(j => j.layerID !== null);
        last.map(item => {
          item.layerName = item.layerName.split(':')[1];
        });
        setLayerValue(last);
      }
    });
  };

  const getLayerFields = (val, key, value, typeFields) => {
    let obj = form.getFieldsValue();
    let newValue = value ? value : schemeValue;
    let data = newValue.find(i => i.servicename === obj.schemeName);
    GetLayerFields({
      mapServer: data.servicename,
      layerName: val,
      filedType: typeFields ? typeFields : type,
    }).then(res => {
      if (res.code === '0') {
        if (key !== undefined && key !== null && key !== '') {
          let list = layerData.current;
          list[key] = res.data;
          layerData.current = list;
        } else {
          setLayerFields(res.data);
        }
      }
    });
  };

  // 表单监听
  const onValuesChange = val => {
    if (Object.keys(val)[0] === 'schemeName') {
      form.setFieldsValue({ nodeName1: '', nodeValue1: '', users: [] });
      setLayerValue([]);
      setLayerFields([]);
      layerData.current = {};
      getLayerList(val[Object.keys(val)[0]]);
    } else if (Object.keys(val)[0] === 'nodeName1') {
      form.setFieldsValue({ nodeValue1: '' });
      getLayerFields(val[Object.keys(val)[0]]);
    } else if (Object.keys(val)[0] === 'Fields') {
      let arr = [];
      tableField.map(item => {
        arr.push(...item.TableFields);
      });
      let data = arr.find(i => i.FieldName === val[Object.keys(val)[0]]);
      setTableShape(data.FiledShape);
      setTableType(data.type);
      setType(data.FiledType);
      setTableName(data.table);
      form.setFieldsValue({ schemeName: '', nodeName1: '', nodeValue1: '', users: [] });
      setLayerValue([]);
      setLayerFields([]);
      layerData.current = {};
    }
  };

  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let nodeName1 = form.getFieldsValue();
        let nodeName = form.getFieldsValue().nodeName1;
        let nodeValue = form.getFieldsValue().nodeValue1;
        let arr = [];
        let result = nodeName1.users;
        if (result) {
          // eslint-disable-next-line array-callback-return
          result.map((item, index) => {
            if (item) {
              arr.push({
                nodeName: item.nodeName,
                nodeValue: item.nodeValue,
              });
            }
          });
        }
        arr.unshift({ nodeName, nodeValue });
        let obj = {};
        if (modalType === 'add') {
          obj = { ...validate, ID: addIndex, ...arr };
        } else {
          obj = { ...validate, key: msg.ID || msg.key, ...arr };
        }
        debugger
        onSubumit(obj, modalType, tableType, tableName, tableShape);
      }
    });
  };

  const mapTree = org => {
    if (org.TableFields) {
      return (
        <TreeNode
          value={org.TableName}
          title={
            <>
              <span style={{ marginRight: '10px' }}>{org.TableName}</span>
              {org.type === '关联表单' ? (
                <Tag color="green">{org.type}</Tag>
              ) : (
                <Tag color="blue">{org.type}</Tag>
              )}
            </>
          }
          disabled
        >
          {org.TableFields.map(item => mapTree(item))}
        </TreeNode>
      );
    }
    return <TreeNode value={org.FieldName} title={org.FieldName} key={org.FieldName} />;
  };

  return (
    <div className={styles.AddGIS}>
      <Modal
        title="GIS配置"
        visible={visible}
        onOk={onFinish}
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
        width={550}
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ remember: true }}
          onValuesChange={onValuesChange}
        >
          <Form.Item
            label="规则名称"
            name="RuleName"
            rules={[
              { required: true },
              {
                validator: (_, value) => {
                  if (modalType === 'add' && ruleList.indexOf(value) !== -1) {
                    return Promise.reject(new Error('规则名称已存在'));
                  } else if (
                    modalType === 'edit' &&
                    ruleList.indexOf(value) !== -1 &&
                    value !== msg.RuleName
                  ) {
                    return Promise.reject(new Error('规则名称已存在'));
                  }

                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input placeholder="请输入规则名称" />
          </Form.Item>
          <Form.Item label="源字段" name="Fields" rules={[{ required: true }]}>
            <TreeSelect
              showSearch
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择表单源字段"
              treeDefaultExpandAll
              showCheckedStrategy
            >
              {tableField && tableField.map(i => mapTree(i))}
            </TreeSelect>
          </Form.Item>
          <Form.Item label="方案名称" name="schemeName" rules={[{ required: true }]}>
            <Select placeholder="请选择GIS地图方案">
              {schemeValue.map(item => (
                <Option value={item.servicename} key={item.servicename}>
                  <span>{item.schemename}</span>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Row>
            <Col span={1}>
              <img src={logo} style={{ height: '24px' }} alt="" />
            </Col>
            <Col span={11}>
              <Form.Item
                name="nodeName1"
                label="图层名称"
                labelCol={{ span: 8 }}
                rules={[{ required: true, message: '不能为空' }]}
                style={{ width: '233px' }}
              >
                <Select placeholder="请选择图层">
                  {layerValue &&
                    layerValue.map(item => (
                      <Option value={item.layerName} key={item.layerName}>
                        <span>{item.layerName}</span>
                      </Option>
                    ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={11}>
              <Form.Item
                name="nodeValue1"
                label="目标字段"
                labelCol={{ span: 8 }}
                rules={[{ required: true, message: '不能为空' }]}
                style={{ width: '230px', marginLeft: '3px' }}
              >
                <Select placeholder="请选择字段">
                  {layerFields &&
                    layerFields.map(item => (
                      <Option value={item.field} key={item.field}>
                        <span>{item.fieldAlias}</span>
                      </Option>
                    ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={1} />
          </Row>
          <Form.List name="users">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, fieldKey, ...restField }) => (
                  <Space key={key} style={{ display: 'flex', marginBottom: 8 }}>
                    <Row>
                      <Col span={1}>
                        <img src={logo} style={{ height: '24px' }} alt="" />
                      </Col>
                      <Col span={11}>
                        <Form.Item
                          {...restField}
                          name={[name, 'nodeName']}
                          label="图层名称"
                          labelCol={{ span: 8 }}
                          fieldKey={[fieldKey, 'frist']}
                          rules={[{ required: true, message: '不能为空' }]}
                          style={{ width: '233px' }}
                        >
                          <Select
                            placeholder="请选择图层名称"
                            style={{ width: '100%' }}
                            onChange={e => {
                              getLayerFields(e, key);
                              let obj = form.getFieldsValue().users;
                              obj[key].nodeValue = '';
                              form.setFieldsValue({ users: obj });
                            }}
                          >
                            {layerValue &&
                              layerValue.map(item => (
                                <Option value={item.layerName} key={item.layerName}>
                                  <span>{item.layerName}</span>
                                </Option>
                              ))}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={11}>
                        <Form.Item
                          {...restField}
                          name={[name, 'nodeValue']}
                          label="目标字段"
                          fieldKey={[fieldKey, 'last']}
                          labelCol={{ span: 8 }}
                          rules={[{ required: true, message: '不能为空' }]}
                          style={{ width: '230px', marginLeft: '5px' }}
                        >
                          <Select
                            placeholder="请选择设备字段"
                            style={{ width: '100%' }}
                            onClick={() => setFlag(flag + 1)}
                          >
                            {layerData.current[key] &&
                              layerData.current[key].map(item => {
                                return (
                                  <Option value={item.field} key={item.field}>
                                    <span>{item.fieldAlias}</span>
                                  </Option>
                                );
                              })}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={1}>
                        <Tooltip title="移除项">
                          <MinusCircleOutlined
                            onClick={() => remove(name)}
                            style={{
                              fontSize: '20px',
                              marginTop: '6px',
                              marginLeft: '3px',
                              color: '#fa5151',
                            }}
                          />
                        </Tooltip>
                      </Col>
                    </Row>
                  </Space>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                    style={{ width: '394px', marginLeft: '99px' }}
                  >
                    新增项
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};
export default AddModal;
