/* eslint-disable prefer-destructuring */
/* eslint-disable no-else-return */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable indent */
/* eslint-disable camelcase */
/* eslint-disable no-unused-expressions */
import React, { useState, useEffect, useRef } from 'react';
import {
  Drawer,
  Form,
  Input,
  notification,
  Row,
  Col,
  Select,
  Button,
  Space,
  TreeSelect,
  Empty,
  message,
} from 'antd';
import { PlusOutlined, SwapOutlined, MinusCircleOutlined } from '@ant-design/icons';
import styles from './patrolFeedback.less';
import {
  CM_Feedback_LoadFeedbackTables,
  CM_Feedback_LoadFeedbackEvent,
  CM_Feedback_OperatePatrolFeedback,
  CM_Feedback_LoadFields,
  CM_Feedback_QueryPatrolFeedback,
  GetTaskSyncField,
  GetGisPatrolObject,
  GetGisFeedbackTableFields,
} from '@/services/PatrolFeedback/api';
import {
  GetCM_Event_LoadEventTable,
  CM_Event_LoadDepartmentAndRoles,
} from '@/services/standingBook/api';
import RMSComponents from '@/components/RolePmSite/index';

import ChangeRoles from './ChangeRoles';
import ChangeFields from './ChangeFields';

import logo from '@/assets/images/icons/值映射.png';
import lodash from 'lodash';
import { reloadTableFields } from '@/services/tablemanager/tablemanager';
import RuleConfig from '@/components/RuleConfig';

const { Option } = Select;
const AddModal = props => {
  const {
    callBackSubmit = () => {},
    visible,
    type,
    formObj,
    keepTableData,
    onClose,
    pipeArr,
  } = props;

  const [filed, setFiled] = useState({}); // 传给子组件列表数据
  const [filed1, setFiled1] = useState({}); // 传给子组件列表数据
  const [pickItem, setPickItem] = useState(''); // 复选框数据填入项
  const [checkedList1, setCheckedList1] = useState([]); // 最新选择数据

  const [feedbackTable, setFeedbackTable] = useState([]);
  const [feedbackEvent, setFeedbackEvent] = useState([]);
  const [isVisibleFields, setIsVisibleFields] = useState(false);
  const [isVisibleRoles, setIsVisibleRoles] = useState(false);
  const [nu, setNu] = useState([]);
  const [nu1, setNu1] = useState([]);
  const [groupName, setGroupName] = useState('角色');
  const [chooseGroupName, setChooseGroupName] = useState(['角色', '部门', '站点']);
  const [keepFiled, setKeepFiled] = useState([]);
  const [eventData, setEventData] = useState([]);
  const [keepData, setKeepData] = useState('');
  const keep = useRef([]); // 保存初始完整任务同步事件字段
  const [keepAllData, setKeepAllData] = useState([]); // 保存所有关联事件类型数据
  const [keepTree, setKeepTree] = useState([]);
  const [keepAll, setKeepAll] = useState([]); // 保存所选关联事件下完整的字段值
  const [treeSelectValue, setTreeSelectValue] = useState([]);
  const [menuWebList, setMenuWebList] = useState([]);
  const [showRule, setShowRule] = useState(false);
  const [fieldList, setFieldList] = useState([]);
  const [layerList, setLayerList] = useState([]);
  const [newPipeArr, setNewPipeArr] = useState([]);

  const [form] = Form.useForm();
  const [formAdd] = Form.useForm();
  const { Item } = Form;
  const { TreeNode } = TreeSelect;

  useEffect(() => {
    getEventData(); // 获取所有关联事件数据
    if (visible) {
      setNewPipeArr(pipeArr);
      if (type === 'edit') {
        CM_Feedback_QueryPatrolFeedback({ id: formObj.id }).then(res => {
          form.setFieldsValue({ ...res.data });
          console.log(res.data);
          if (!res.data.businessGroup) {
            form.setFieldsValue({
              businessGroup: '区域巡检',
              // gisLayer: res.data.gisServerName
              //   ? `${res.data.gisServerName}&${res.data.gisLayer}`
              //   : res.data.gisLayer,
            });
          } else {
            form.setFieldsValue({
              businessGroup: res.data.businessGroup.split(','),
              // gisLayer: res.data.gisServerName
              //   ? `${res.data.gisServerName}&${res.data.gisLayer}`
              //   : res.data.gisLayer,
            });
          }
          getGisPatrolObject(res.data.gisServerName);

          onChangeEvent(res.data.relationEvent, aa); // 改变关联事件类型
          getFeedbackTable();
          getRoles();
          getFields(res.data.tableName);
          let aa = JSON.parse(res.data.mappingFields);
          onChangeTableName(formObj.tableName, aa);
        });
      } else {
        form.setFieldsValue({ businessGroup: '区域巡检', feedbackRule: '' });
        getGetTaskSyncField();
        getFeedbackTable();
        getRoles();
      }
    } else {
      setLayerList([]);
      setNewPipeArr([]);
      formAdd.resetFields();
      form.resetFields();
      setKeepTree([]);
      setKeepData('');
      keep.current = [];
      setKeepAll([]);
    }
  }, [visible]);

  // 获取字段名数据
  const getGetTaskSyncField = (e, newKeep) => {
    if (e) {
      // 编辑时
      let datalist = [...e];
      let str = newKeep && newKeep[0].TableName;
      let arr = [];
      datalist.forEach(i => {
        if (i.fromTable) {
          arr.push({ fromField: `${i.fromField}%${i.fromTable}`, toField: i.toField });
        } else {
          arr.push({
            fromField: `${i.fromField}%${str ? str : ''}`,
            toField: i.toField,
          });
        }
      });
      setTimeout(() => {
        formAdd.setFieldsValue({ parmars: arr }); // 处理数据让下拉框回显title值
      }, 0);
    } else {
      setKeepData([]);
    }
  };

  const getGisPatrolObject = val => {
    GetGisPatrolObject({ serverName: val }).then(res => {
      if (res.code === '0') {
        setLayerList(res.data[0]?.items);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
      console.log(res);
    });
  };

  const getReloadTableField = (e, i) => {
    reloadTableFields({
      tableName: e,
    }).then(res => {
      if (res.msg === 'Ok') {
        console.log(res.data.root);
        console.log(i);
        setKeepAll(res.data.root);
        // 编辑时过滤下l拉框初始数据
        if (i) {
          let aa = i;
          let to = [];
          aa.map(j => {
            if (j && j.toField) {
              to.push(j.toField);
            }
          });
          let lastTo = [];
          res.data.root.map(b => {
            if (to.indexOf(b.name) == -1) {
              lastTo.push(b);
            }
          });
          setKeepTree(lastTo);
        } else {
          setKeepTree(res.data.root);
        }

        let arrlist = [];
        let data = {};
        let listArr = [];
        res.data.root.map(i => {
          arrlist.push(i.name);
        });
        data.TableFieldNames = arrlist;
        data.TableName = e;
        listArr.push(data);
        let arr = formateArrDataA2(res.data.root, 'group');
        let newArr = [];
        Object.keys(arr).map((item, index) => {
          newArr.push({ type: item, key: index, id: index });
        });
        let aa = [];
        let bb = [];
        Object.keys(arr).forEach((item, index) => {
          aa.push({ name: item, key: index, ID: index, children: arr[item] });
          bb.push(item);
        });
        console.log(aa, 'aaaaaaaaaaaaa');
        // setKeepTree(aa);
        // setKeepAll(aa);
        // all.current = aa;
      }
    });
  };

  const formateArrDataA2 = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    // eslint-disable-next-line no-restricted-syntax
    for (let i in initialArr) {
      if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
        nameArr.push(initialArr[i][`${name}`]);
      }
    }
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in initialArr) {
        if (initialArr[j][`${name}`] == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(initialArr[j]);
        }
      }
    }
    for (let keys in tempObj) {
      let arr = [];
      tempObj[keys].map((item, index) => {
        tempObj[keys] = arr;
        item.key = index;
        arr.push(item);
      });
    }
    return tempObj;
  };

  // 获取关联事件数据
  const getEventData = () => {
    GetCM_Event_LoadEventTable().then(res => {
      if (res.code === 0) {
        let aa = [];
        let bb = [];
        res.data.map(i => {
          i.root.map(j => {
            aa.push(j.name);
            bb.push(j);
          });
        });
        setKeepAllData(bb);
        setEventData(aa);
      }
    });
  };

  const getFeedbackTable = () => {
    CM_Feedback_LoadFeedbackTables().then(res => {
      if (res.code === 0) {
        setFeedbackTable(res.data);
      }
    });
    CM_Feedback_LoadFeedbackEvent().then(res => {
      if (res.code === 0) {
        setFeedbackEvent(res.data);
        if (type == 'add') {
          form.setFieldsValue({ eventName: res.data[0].Name });
        }
      }
    });
  };

  const getFields = e => {
    CM_Feedback_LoadFields(e).then(res => {
      if (res.code === 0) {
        setNu(res.data);
        let data = [];
        res.data.forEach(i => {
          data.push(i.fieldName);
        });
        let list = [{ TableName: e, TableFieldNames: data }];
        setFieldList(list);
        setFiled(formateArrDataA(res.data, 'groupName'));
      }
    });
  };

  const getRoles = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.code === 0) {
        setNu1(res.data);
        // setFiled1(formateArrDataA1(res.data, 'groupType'));
        setKeepFiled(groupArr(res.data, 'groupType'));
      }
    });
  };

  const groupArr = (initialArr, name) => {
    let list = {};
    initialArr.data.map(i => {
      let ar = [];
      i.root.map(j => {
        let ss = {};
        ss.label = j.Name;
        ss.value = j.ID.toString();
        ar.push(ss);
      });
      list[i.groupType] = ar;
    });
    return list;
  };

  const onSubmit = () => {
    formAdd.validateFields().then(validate1 => {
      if (validate1) {
        form.validateFields().then(validate => {
          if (validate) {
            let obj = lodash.cloneDeep(form.getFieldsValue());
            let mappingFields = lodash.cloneDeep(formAdd.getFieldValue('parmars'));
            mappingFields &&
              mappingFields.forEach(i => {
                let data = i.fromField.split('%');
                i.fromField = data[0];
                i.fromTable = data[1];
              });
            obj.businessGroup = obj.businessGroup.toString();
            let list = [];
            let groupNameSever = '';
            // if (obj.gisLayer && obj.gisLayer.indexOf('&') !== -1) {
            //   list = obj.gisLayer.split('&');
            //   obj.gisLayer = list[1];
            //   groupNameSever = list[0];
            // }
            if (type == 'add') {
              CM_Feedback_OperatePatrolFeedback({
                ...obj,
                // gisServerName: groupNameSever,
                mappingFields: mappingFields && JSON.stringify(mappingFields),
              }).then(res => {
                if (res.code === 0) {
                  onClose();
                  callBackSubmit();
                  notification.success({
                    message: '提示',
                    duration: 3,
                    description: type == 'add' ? '添加成功' : '编辑成功',
                  });
                } else {
                  notification.error({
                    message: '提示',
                    duration: 3,
                    description: res.msg,
                  });
                }
              });
            } else {
              CM_Feedback_OperatePatrolFeedback({
                ...obj,
                // gisServerName: groupNameSever,
                id: formObj.id,
                mappingFields: mappingFields && JSON.stringify(mappingFields),
              }).then(res => {
                if (res.code === 0) {
                  onClose();
                  callBackSubmit();
                  notification.success({
                    message: '提示',
                    duration: 3,
                    description: type == 'add' ? '添加成功' : '编辑成功',
                  });
                } else {
                  notification.error({
                    message: '提示',
                    duration: 3,
                    description: res.msg,
                  });
                }
              });
            }
          }
        });
      }
    });
  };

  const pickFiled = fileds => {
    if (form.getFieldsValue().tableName) {
      let pp = formateArrDataA(nu, 'groupName');
      if (form.getFieldValue(fileds)) {
        let ab = form.getFieldValue(fileds).split(',');
        let arr = Object.keys(pp);
        let b = [];
        let a = [];
        arr.map((item, index) => {
          pp[item].map((i, j) => {
            b.push(i);
          });
        });
        ab.map((item, index) => {
          if (b.includes(item) == false) {
            if (item == '') {
              a = [];
            } else {
              a.push(item);
            }
          }
        });
        if (a.length > 0) {
          pp.外部字段 = a;
          arr.push('外部字段');
        }
        setFiled(pp);
        setCheckedList1(form.getFieldValue(fileds).split(','));
        setPickItem(fileds);
        setIsVisibleFields(true);
      } else {
        setFiled(pp);
        setCheckedList1([]);
        setPickItem(fileds);
        setIsVisibleFields(true);
      }
    } else {
      notification.warning({
        message: '提示',
        duration: 3,
        description: '请先选择反馈表',
      });
    }
  };
  const pickFiled1 = fileds => {
    if (form.getFieldValue(fileds)) {
      setCheckedList1(form.getFieldValue(fileds).split(','));
      setPickItem(fileds);
      setIsVisibleRoles(true);
    } else {
      setCheckedList1([]);
      setPickItem(fileds);
      setIsVisibleRoles(true);
    }
  };

  const onChangeTableName = (e, flag) => {
    getFields(e);
    GetGisFeedbackTableFields({ feedbackTableName: e }).then(res => {
      if (res.code === 0) {
        let newData = [res.data.DeviceData];
        res.data.FeedbackData.length > 0 &&
          res.data.FeedbackData.forEach(i => {
            newData.push(i);
          });
        setKeepData(newData);
        keep.current = newData;
        if (flag) {
          getGetTaskSyncField(flag, newData); // 获取字段名数据
        }
      }
    });
  };

  const formateArrDataA = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    for (let i in initialArr) {
      if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
        nameArr.push(initialArr[i][`${name}`]);
      }
    }
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in initialArr) {
        if (initialArr[j][`${name}`] == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(initialArr[j]);
        }
      }
    }
    for (let keys in tempObj) {
      let arr = [];
      tempObj[keys].map((item, index) => {
        tempObj[keys] = arr;
        item.key = index;
        arr.push(item);
      });
    }
    Object.keys(tempObj).map((i, j) => {
      tempObj[i].map((k, y) => {
        tempObj[i][y] = k.fieldName;
      });
    });
    return tempObj;
  };

  const onOK = prop => {
    setIsVisibleRoles(false);
    let inputText = {};
    inputText[prop.pickItem] = prop.str;
    setCheckedList1(prop.stt);
    form.setFieldsValue(inputText);
  };

  const onOK1 = prop => {
    setIsVisibleFields(false);
    let inputText = {};
    inputText[prop.pickItem] = prop.str;
    setCheckedList1(prop.stt);
    form.setFieldsValue(inputText);
  };

  // 改变关联事件类型
  const onChangeEvent = (e, i) => {
    if (!i || !e) {
      setKeepData(keep.current);
      formAdd.resetFields();
    }
    let aa = keepAllData.find(i => i.name === e);
    if (aa) {
      getReloadTableField(aa.tableName, i); // 找到关联事件对应事件表获取对应表的所有字段
    }
  };

  const mapTree = (org, server) => {
    const haveChildren = Array.isArray(org.items) && org.items.length > 0;
    return haveChildren ? (
      <TreeNode value={org.serverName} title={org.serverName} disabled>
        {org.items.map(item => mapTree(item, org.serverName))}
      </TreeNode>
    ) : (
      <TreeNode value={`${server}&${org.name}`} title={org.name} />
    );
  };

  const changeValue = () => {
    let aa = formAdd.getFieldsValue().parmars;
    if (aa) {
      let from = [];
      let to = [];
      aa.map(i => {
        if (i && i.fromField) {
          from.push(i.fromField);
        }
        if (i && i.toField) {
          to.push(i.toField);
        }
      });

      let lastFrom = [];
      let lastTo = [];
      keep.current.map(j => {
        if (from.indexOf(j.key) == -1) {
          lastFrom.push(j);
        }
      });
      setKeepData(lastFrom);

      keepAll.map(j => {
        if (to.indexOf(j.name) == -1) {
          lastTo.push(j);
        }
      });
      setKeepTree(lastTo);
    }

    // let data = keepAll;
    // data.map(k => {
    //   console.log(k);
    //   k.children.map((j, h) => {
    //     console.log(j);
    //     if (to.indexOf(j.name) != -1) {
    //       console.log(j);
    //       k.children.splice(h, 1);
    //     }
    //   });
    // });
    // console.log(data);
    // setKeepTree(data);
  };

  const treeSelectOnchange = e => {
    form.setFieldsValue({ gisLayer: '' });
    getGisPatrolObject(e);
    // setTreeSelectValue(e);
  };

  const saveRule = e => {
    form.setFieldsValue({ feedbackRule: e });
    setShowRule(false);
  };

  const editRule = () => {
    setShowRule(true);
  };

  const mapTreeFiled = (org, parent) => {
    if (org.TableFields) {
      return (
        <TreeNode value={org.TableName} title={org.TableName} disabled>
          {org.TableFields.map(item => mapTreeFiled(item, org.TableName))}
        </TreeNode>
      );
    }
    return (
      <TreeNode value={`${org.FieldValue}%${parent}`} title={org.FieldName} key={org.FieldName} />
    );
  };

  return (
    <Drawer
      title="反馈配置"
      visible={visible}
      destroyOnClose
      width="550px"
      {...props}
      footer={
        <Space>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} labelCol={{ span: 7 }} style={{ overflowY: 'scroll' }}>
        <Row>
          <Col span={23}>
            <Item
              label="巡检对象"
              name="layerName"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请输入巡检对象名称',
                },
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().layerName;
                    if (type === 'add' && keepTableData.indexOf(aa) != -1) {
                      return Promise.reject('巡检对象已存在');
                    } else if (
                      type === 'edit' &&
                      keepTableData.indexOf(aa) != -1 &&
                      aa != formObj.layerName
                    ) {
                      return Promise.reject('巡检对象已存在');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="巡检对象名称不可重复" />
            </Item>
          </Col>
          <Col span={23}>
            <Item
              label="业务划分"
              name="businessGroup"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请选择业务划分',
                },
              ]}
            >
              <Select placeholder="请选择业务划分" showSearch mode="multiple" allowClear>
                <Option key="区域巡检" value="区域巡检">
                  区域巡检
                </Option>
                <Option key="DMA巡检" value="DMA巡检">
                  DMA巡检
                </Option>
              </Select>
            </Item>
          </Col>
          <Col span={23}>
            <Item label="分组" name="groupType" labelCol={{ span: 4 }}>
              <Input placeholder="请输入分组名称" />
            </Item>
          </Col>
          <Col span={11}>
            <Item
              label="GIS服务"
              name="gisServerName"
              labelCol={{ span: 8 }}
              rules={[
                {
                  required: true,
                  message: '请选择GIS服务',
                },
              ]}
            >
              <Select placeholder="选择GIS服务" onChange={treeSelectOnchange} showSearch>
                {newPipeArr
                  ? newPipeArr.map((item, index) => (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          </Col>
          <Col span={12}>
            <Item
              label="GIS图层"
              name="gisLayer"
              labelCol={{ span: 8 }}
              rules={[
                {
                  required: true,
                  message: '请选择GIS图层',
                },
              ]}
            >
              <Select placeholder="选择GIS图层" showSearch>
                {layerList
                  ? layerList.map((item, index) => (
                      <Option key={item.id} value={item.name}>
                        {item.name}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          </Col>
          {/* <Col span={23}>
            <Item
              label="GIS图层"
              name="gisLayer"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请选择GIS图层',
                },
              ]}
            >
              <TreeSelect
                showSearch
                value={treeSelectValue}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择GIS图层"
                allowClear
                treeDefaultExpandAll
                showCheckedStrategy
                onChange={treeSelectOnchange}
              >
                {menuWebList ? (
                  menuWebList.map(i => mapTree(i))
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
              </TreeSelect>
            </Item>
          </Col> */}
          <Col span={23}>
            <Item label="GIS条件" name="gisFilterValue" labelCol={{ span: 4 }}>
              <Input placeholder="示例：设备级别 = '小区阀门'  （设备级别来自图层表字段）" />
            </Item>
          </Col>
          <Col span={23}>
            <Item label="反馈表" name="tableName" labelCol={{ span: 4 }}>
              <Select placeholder="选择反馈表" onChange={onChangeTableName} showSearch>
                {feedbackTable
                  ? feedbackTable.map((item, index) => (
                      <Option key={index} value={item.text}>
                        {item.text}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          </Col>
          <Col span={23}>
            <Item label="字段集" name="fields" labelCol={{ span: 4 }}>
              <div style={{ display: 'flex' }}>
                <Item name="fields" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择字段集" allowClear />
                </Item>
                <Button
                  type="dashed"
                  onClick={() => pickFiled('fields')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          {/* <Col span={23}>
            <Item label="异常值" name="exceptionValue" labelCol={{ span: 4 }}>
              <Input placeholder="请输入异常值" />
            </Item>
          </Col> */}
          {/* <Col span={23}>
            <Item label="触发事件" name="eventName" labelCol={{ span: 4 }}>
              <Select placeholder="选择触发事件" showSearch>
                {feedbackEvent
                  ? feedbackEvent.map((item, index) => (
                      <Option key={index} value={item.Name}>
                        {item.Name}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          </Col> */}
          <Col span={23}>
            <Item
              label="权限"
              name="roles"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请选择权限',
                },
              ]}
            >
              <div style={{ display: 'flex' }}>
                <Item name="roles" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择字段集" allowClear />
                </Item>
                <Button
                  type="dashed"
                  onClick={() => pickFiled1('roles')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={23}>
            <Item label="反馈联动" name="feedbackRule" labelCol={{ span: 4 }}>
              <div
                style={{
                  border: '2px solid #6A98FA',
                  minHeight: '34px',
                  lineHeight: '34px',
                  textAlign: 'center',
                }}
                onClick={() => {
                  let obj = form.getFieldsValue().tableName;
                  if (!obj) {
                    message.warning('请先选择反馈表！');
                  } else {
                    editRule();
                  }
                }}
              >
                <span>{form.getFieldsValue().feedbackRule}</span>
              </div>
            </Item>
          </Col>
          {form.getFieldsValue().feedbackRule !== '' ? (
            <Col span={23}>
              <Item
                label="关联事件"
                name="relationEvent"
                labelCol={{ span: 4 }}
                rules={[{ required: true, message: '请选择关联事件类型' }]}
              >
                <Select
                  placeholder="选择关联事件类型"
                  onChange={e => onChangeEvent(e)}
                  showSearch
                  allowClear
                >
                  {eventData
                    ? eventData.map((item, index) => (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
            </Col>
          ) : (
            <Col span={23}>
              <Item label="关联事件" name="relationEvent" labelCol={{ span: 4 }}>
                <Select
                  placeholder="选择关联事件类型"
                  onChange={e => onChangeEvent(e)}
                  showSearch
                  allowClear
                >
                  {eventData
                    ? eventData.map((item, index) => (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      ))
                    : ''}
                </Select>
              </Item>
            </Col>
          )}

          <Col span={23}>
            <span style={{ fontSize: '12px', color: '#bfbcbc', marginLeft: '80px' }}>
              当配置了关联事件后，可配置字段映射规则
            </span>
            <br />
            <span style={{ fontSize: '12px', color: '#bfbcbc', marginLeft: '80px' }}>
              配置后，管网巡检发起的工单，可以传递该巡检任务信息
            </span>
          </Col>
          <Col span={4} />
          <Col span={19}>
            <Item style={{ marginTop: '20px' }}>
              <Form name="form" form={formAdd} onFieldsChange={changeValue}>
                <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: (rule, value) => {
                                  if (value) {
                                    let filterValue = formAdd.getFieldsValue().parmars;
                                    let num = filterValue.findIndex(i => i.fromField === value);
                                    let index = rule.field.split('.')[1];
                                    if (num !== undefined && num !== Number(index)) {
                                      return Promise.reject('字段重复');
                                    }
                                  }
                                  return Promise.resolve();
                                },
                              },
                            ]}
                          >
                            {/* <Select
                              placeholder="选择字段名"
                              // onSelect={changTable}
                              // optionLabelProp="key"
                              showSearch
                              style={{ width: '159px' }}
                            >
                              {keepData
                                ? keepData.map((item, index) => (
                                    <Option key={item.key} value={item.key}>
                                      {item.key}
                                    </Option>
                                  ))
                                : ''}
                            </Select> */}
                            <TreeSelect
                              showSearch
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择字段名"
                              treeDefaultExpandAll
                              style={{ width: '159px' }}
                              showCheckedStrategy
                              onFocus={() => {
                                let obj = form.getFieldsValue().tableName;
                                if (!obj) {
                                  message.warning('请先选择反馈表！');
                                }
                              }}
                            >
                              {keepData.length > 0 && keepData.map(i => mapTreeFiled(i))}
                            </TreeSelect>
                          </Form.Item>
                          <img src={logo} style={{ height: '24px' }} alt="" />
                          <Form.Item
                            {...restField}
                            style={{ marginBottom: '5px' }}
                            name={[name, 'toField']}
                            fieldKey={[fieldKey, 'key']}
                            rules={[{ required: true, message: '请填写映射字段名' }]}
                          >
                            <Select
                              placeholder="选择映射字段名"
                              showSearch
                              style={{ width: '159px' }}
                            >
                              {keepTree.length > 0
                                ? keepTree.map((item, index) => (
                                    <>
                                      <Option key={item.name} value={item.name}>
                                        {item.name}
                                      </Option>
                                    </>
                                  ))
                                : ''}
                            </Select>
                          </Form.Item>
                          <MinusCircleOutlined
                            onClick={() => remove(name)}
                            style={{ marginLeft: '10px', fontSize: '20px' }}
                          />
                        </Space>
                      ))}
                      <Form.Item>
                        <Button
                          type="dashed"
                          onClick={() => add()}
                          block
                          icon={<PlusOutlined />}
                          style={{ marginLeft: '-2px' }}
                        >
                          添加映射
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </Form>
            </Item>
          </Col>
          {/* <Col span={23}>
            <Item label="分组" name="groupType" labelCol={{ span: 4 }}>
              <Input placeholder="请输入分组" />
            </Item>
          </Col> */}
        </Row>
      </Form>
      <ChangeFields
        visible={isVisibleFields}
        callBackSubmit={onOK1}
        onCancel={() => setIsVisibleFields(false)}
        newCheckedList={checkedList1}
        filed={filed}
        pickItem={pickItem}
        formObj={formObj}
      />
      {/* <ChangeRoles
        visible={isVisibleRoles}
        onCancel={() => setIsVisibleRoles(false)}
        callBackSubmit={onOK}
        newCheckedList={checkedList1}
        filed11={filed1}
        pickItem={pickItem}
      /> */}
      <RMSComponents
        visible={isVisibleRoles}
        onCancel={() => setIsVisibleRoles(false)}
        callBackSubmit={onOK}
        newCheckedList={checkedList1} // 单选框中的值
        pickItem={pickItem}
        groupName={groupName} // 打开组件展示的分组名，用来首次获取数据
        chooseGroupName={chooseGroupName} // 可选分组名
        keepFiled={keepFiled}
        dataType="name"
      />
      <RuleConfig
        RuleContent={form.getFieldsValue().feedbackRule || ''}
        tableName={form.getFieldsValue().feedbackName}
        fieldList={fieldList}
        visible={showRule}
        handleCancel={() => setShowRule(false)}
        onSubumit={e => saveRule(e)}
        flag={2}
      />
    </Drawer>
  );
};
export default AddModal;
