/* eslint-disable no-else-return */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable indent */
/* eslint-disable camelcase */
/* eslint-disable no-unused-expressions */
import React, { useContext, useEffect, useRef, useState } from 'react';
import { Context } from './maintenance';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import {
  Drawer,
  Form,
  Input,
  notification,
  Row,
  Col,
  Select,
  Button,
  Dropdown,
  Tooltip,
  Menu,
  Space,
  Radio,
  Switch,
  TreeSelect,
  message,
  AutoComplete,
  InputNumber,
  Popconfirm,
  Table,
  Modal,
  Spin,
  Empty,
} from 'antd';
import {
  PlusOutlined,
  InfoCircleOutlined,
  MinusCircleOutlined,
  EditOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import styles from './maintenance.less';
import RuleConfig from '@/components/RuleConfig';
import { FormRender } from 'panda-xform';
import {
  CM_XWBPlan_AccountTable,
  NewCM_XWBPlan_feedbackTable,
  NewCM_XWBPlan_DataEditORAdd,
  NewCM_XWBPlan_DataList,
  QueryDevicesList,
  newGetParentDeviceTemplate,
  GetFeedbackTableFields,
  GetAccountConfigInfo,
  newGetAccountConfigInfo,
  NewGetFeedbackTableFields
} from '@/services/maintenance/api';
import BaseTimeConfig from './components/BaseTimeConfig';

import { GetTaskSyncField } from '@/services/PatrolFeedback/api';
import { reloadTableFields } from '@/services/tablemanager/tablemanager';

import {
  GetCM_Event_LoadEventTable,
  CM_Event_LoadDepartmentAndRoles,
} from '@/services/standingBook/api';
import RMSComponents from '@/components/RolePmSite/index';

import ChangeAdd from './ChangeAdd';

import logo from '@/assets/images/icons/值映射.png';

const { Option } = Select;

const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [formFeed] = Form.useForm();
  return (
    <Form form={formFeed} component={false}>
      <EditableContext.Provider value={formFeed}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  index,
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const formBack = useContext(EditableContext);
  const { state, dispatch } = useContext(Context);
  useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    formBack.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await formBack.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请选择反馈名称`,
          },
        ]}
      >
        <Select ref={inputRef} showSearch onPressEnter={save} onBlur={save} onSelect={save}>
          {state.selectList
            ? state.selectList.map((item, index) => (
              <Option key={index} value={item}>
                {item}
              </Option>
            ))
            : ''}
        </Select>
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

const AddModal = props => {
  const { callBackSubmit = () => { }, visible, type, formObj, keepTableData } = props;
  const { state, dispatch } = useContext(Context);
  const [Type1, setType1] = useState('');
  const [Type2, setType2] = useState('');
  const [selectValue, setSelectValue] = useState('');
  const [selectValue1, setSelectValue1] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [isVisible, setIsVisible] = useState(false);
  const [filed, setFiled] = useState([]); // 传给子组件列表数据
  const [keepFeed, setKeepFeed] = useState([]);
  const [filed1, setFiled1] = useState({}); // 传给子组件列表数据
  const [types, setTypes] = useState(''); // 弹窗类型
  const [pickItem, setPickItem] = useState(''); // 复选框数据填入项
  const [checkedList1, setCheckedList1] = useState([]); // 最新选择数据
  const [characterValue, setCharacterValue] = useState(''); // 打开弹框之前数据
  const [ff, setFf] = useState([]);
  const [chee, setChee] = useState('');
  const [isVisibleRoles, setIsVisibleRoles] = useState(false);
  const [groupName, setGroupName] = useState('角色');
  const [chooseGroupName, setChooseGroupName] = useState(['角色']);
  const [keepFiled, setKeepFiled] = useState([]);
  const [visibleChecked, setVisibleChecked] = useState(false);
  const [visibleChecked1, setVisibleChecked1] = useState(false);
  const [eventData, setEventData] = useState([]);
  const [autoFlag, setAutoFlag] = useState(false); // 禁用自动派发
  const [keepData, setKeepData] = useState('');
  const [parentList, setParentList] = useState([]);
  const [keep, setKeep] = useState([]); // 保存初始完整任务同步事件字段
  const [keepAllData, setKeepAllData] = useState([]); // 保存所有关联事件类型数据
  const [keepTree, setKeepTree] = useState([]);
  const [keepAll, setKeepAll] = useState([]); // 保存所选关联事件下完整的字段值
  const [showRule, setShowRule] = useState(false);
  const [fieldList, setFieldList] = useState([]);
  const [record, setRecord] = useState();
  const [loading, setLoading] = useState(false);
  const timeData = useRef(null);
  const [keepTimeData, setKeepTimeData] = useState('');

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

  const [formJson, setFormJson] = useState(null);
  const [visibleLook, setVisibleLook] = useState(false);

  const [dataSource, setDataSource] = useState([]);
  const [count, setCount] = useState(0);

  const SortableItem = SortableElement(props => <tr {...props} />);
  const SortableBody = SortableContainer(props => <tbody {...props} />);

  const [stateType, setStateType] = useState('edit');

  const handleDelete = key => {
    const newData = dataSource.filter(item => item.key !== key);
    setDataSource(newData);
  };

  const DragHandle = SortableHandle(() => (
    <MenuOutlined
      style={{
        cursor: 'grab',
        color: '#999',
      }}
    />
  ));

  const columnsDrag = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 30,
      className: 'drag-visible',
      render: r => {
        return (
          <div
            style={{
              width: '100%',
              height: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
            onMouseEnter={() => {
              setStateType('drag');
            }}
          >
            <DragHandle />
          </div>
        );
      },
    },
    {
      title: <span style={{ marginLeft: '12px' }}>反馈名称</span>,
      dataIndex: 'name',
      width: '60%',
      className: 'drag-visible',
      editable: true,
      render: r => {
        return (
          <div
            style={{
              width: '100%',
              height: '100%',
              display: 'flex',
              alignItems: 'center',
              paddingLeft: stateType === 'drag' ? '12px' : '0px',
            }}
            onMouseEnter={() => {
              setStateType('edit');
            }}
          >
            {r}
          </div>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      className: 'drag-visible',
      align: 'center',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <div style={{ display: 'flex', justifyContent: 'space-around' }}>
            {record.name ? (
              <span
                onClick={() => handleLook(record.name)}
                style={{ color: '#0e8ef7', cursor: 'pointer' }}
              >
                预览
              </span>
            ) : (
              <span style={{ color: '#b3b3b3', cursor: 'not-allowed' }}>预览</span>
            )}

            <span
              onClick={() => handleDelete(record.key)}
              style={{ color: '#fb8686', cursor: 'pointer' }}
            >
              移除
            </span>
          </div>
        ) : null,
    },
  ];

  const onSortEnd = ({ oldIndex, newIndex }) => {
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(el => !!el);
      console.log('Sorted items: ', newData);
      setDataSource(newData);
    }
  };
  const DraggableContainer = props => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );
  const DraggableBodyRow = ({ className, style, ...restProps }) => {
    const index = dataSource.findIndex(x => x.key === restProps['data-row-key']);
    return <SortableItem style={{ zIndex: 999999, height: '50px' }} index={index} {...restProps} />;
  };

  const handleAdd = () => {
    setStateType('edit');
    const newData = {
      key: count,
      name: ``,
    };
    setDataSource([...dataSource, newData]);
    setCount(count + 1);
  };
  const handleSave = row => {
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  useEffect(() => {
    let list = [];
    keepFeed.forEach(i => {
      let index = dataSource.find(val => val.name === i);
      if (!index) {
        list.push(i);
      }
    });
    setFiled(list);
    dispatch({ type: 'SET_SELECT_LIST', data: list });
    let arr = [];
    dataSource.map(i => {
      arr.push(i.name);
    });
    onChangeFeed(arr.toString(), 1);
  }, [dataSource]);

  const columns = columnsDrag.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  useEffect(() => {
    if (!visibleLook) {
      setFormJson(null);
    }
  }, [visibleLook]);

  useEffect(() => {
    getEventData();
    if (visible) {
      getRole();
      if (type === 'add') {
        setChee('否');
        form.setFieldsValue({ isSubmit: '否', feedbackRule: '' });
        getGetTaskSyncField();
        setType1('');
        setType2('');
        setFiled1({});
        setCount(0);
      } else if (type === 'edit') {
        getParentList();

        NewCM_XWBPlan_DataList({ id: formObj.id }).then(res => {
          if (res.data[0].docycle.indexOf('{') === -1) {
            setKeepTimeData(null);
          } else {
            let list = JSON.parse(res.data[0].docycle);
            setKeepTimeData(list);
            form.setFieldsValue({
              time: list?.time,
            });
          }

          let data = res.data[0];
          let mappingFields = JSON.parse(data.mappingFields);
          onChangeEvent(data.relationEvent, mappingFields); // 改变关联事件类型
          onChangeFeed(
            formObj.feedbackName,
            '',
            formObj.mappingFields && JSON.parse(formObj.mappingFields),
          );
          if (data.isSubmit === '是') {
            setAutoFlag(true);
          } else {
            setAutoFlag(false);
          }
          let str = data.feedbackName?.split(',');
          let arr = [];
          str?.forEach((i, index) => {
            arr.push({ key: index, name: i });
          });
          setCount(arr.length);
          setDataSource(arr);
          setVisibleChecked(data.isSubmit === '是');
          setVisibleChecked1(data.autoAssign === '是');
          data && form.setFieldsValue({ ...data });
          if (data.parentBusinessName) {
            form.setFieldsValue({
              parentId: data.parentId,
              inOrder: data.inOrder === 1 ? true : false,
            });
          } else {
            form.setFieldsValue({ parentId: '', inOrder: data.inOrder === 1 ? true : false });
          }
          form.setFieldsValue({ isDynamicCycle: data.isDynamicCycle === 1 ? true : false });
          setType1(data.businessType);
          setType2(data.accountName);
        });
      }
    } else {
      setKeepTimeData('');
      setFormJson(null);
      setDataSource([]);
      setAutoFlag(false);
      setVisibleChecked(false);
      setVisibleChecked1(false);
      setChee('');
      form.resetFields();
      formAdd.resetFields();
      setKeepAll([]);
      setKeepTree([]);
      setKeepData([]);
      setKeep([]);
      setCount(0);
      setFieldList([]);
    }
  }, [visible]);

  useEffect(() => {
    getRole();
    getList();
    getFeedbackTable();
  }, []);

  useEffect(() => { }, [keepData]);

  const getParentList = e => {
    let value = e ? e : formObj.accountName;
    newGetParentDeviceTemplate({ accountName: value }).then(res => {
      if (res.code === 0) {
        setParentList(res.data);
      }
    });
  };

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

  const getList = () => {
    QueryDevicesList().then(res => {
      if (res.code === 0) {
        setTreeData(res.data);
      }
    });
  };

  const onSubmit = () => {
    formAdd.validateFields().then(validate1 => {
      if (validate1) {
        form.validateFields().then(validate => {
          if (validate) {
            let obj = form.getFieldsValue();
            let mappingFields = formAdd.getFieldValue('parmars');
            mappingFields &&
              mappingFields.forEach(i => {
                let data = i.fromField.split('%');
                i.fromField = data[0];
                i.fromTable = data[1];
              });
            obj.isSubmit = visibleChecked === true ? '是' : '否';
            obj.autoAssign = visibleChecked1 === true ? '是' : '否';

            let StartExecLen = 0;
            let EndExecLen = 0;
            let data = timeData.current.getdata;
            let startLen = data.startLen;
            if (data.Unit == 'week') {
              StartExecLen = getNum(data.cities, data);
              EndExecLen = getNum(data.secondCity, data);
            }
            if (data.Unit == 'month') {
              let obg = {
                1: 0,
                2: 1,
                3: 2,
                6: 5,
                12: 11,
              };
              StartExecLen = obg[data.MonthType1] * 31 + data.MonthDayType1 * 1 - startLen;
              EndExecLen = obg[data.MonthType2] * 31 + data.MonthDayType2 * 1 - startLen;
            }
            let UnitObj = {
              hour: '小时',
              day: '日',
              week: '周',
              month: '月',
            };
            let lastData = {
              CycleLen: data.CycleLen * 1,
              Unit: UnitObj[data.Unit],
              StartLen: Number(startLen),
              StartExecLen: StartExecLen,
              EndExecLen: EndExecLen,
            };
            obj.inOrder = obj.inOrder ? 1 : 0;
            obj.isDynamicCycle = obj.isDynamicCycle ? 1 : 0;
            if (!obj.time) {
              lastData.time = false;
              if (data.Unit === 'month') {
                lastData.StartExecLen = 0;
                lastData.EndExecLen = 31 - lastData.StartLen;
              } else if (data.Unit === 'week') {
                lastData.StartExecLen = 1;
                lastData.EndExecLen = 7;
              }
            } else {
              lastData.time = true;
            }
            obj.docycle = JSON.stringify(lastData);
            let arr = [];
            dataSource.forEach(i => {
              arr.push(i.name);
            });
            let newArr = arr.filter(i => i !== '');
            if (newArr.length === 0) {
              message.warning('请选择填报内容');
            } else {
              obj.feedbackName = newArr.toString();
              if (type === 'add') {
                NewCM_XWBPlan_DataEditORAdd({
                  ...obj,
                  mappingFields: mappingFields && JSON.stringify(mappingFields),
                }).then(res => {
                  if (res.msg === '') {
                    form.resetFields();
                    callBackSubmit();
                    notification.success({
                      message: '提示',
                      duration: 3,
                      description: '添加成功',
                    });
                  } else {
                    notification.error({
                      message: '提示',
                      duration: 3,
                      description: res.msg,
                    });
                  }
                });
              }
              if (type === 'edit') {
                obj.isSubmit = visibleChecked === true ? '是' : '否';
                obj.autoAssign = visibleChecked1 === true ? '是' : '否';
                NewCM_XWBPlan_DataEditORAdd({
                  ...obj,
                  id: formObj.id,
                  mappingFields: mappingFields && JSON.stringify(mappingFields),
                }).then(res => {
                  if (res.msg === '') {
                    form.resetFields();
                    callBackSubmit();
                    notification.success({
                      message: '提示',
                      duration: 3,
                      description: '编辑成功',
                    });
                  } else {
                    notification.error({
                      message: '提示',
                      duration: 3,
                      description: res.msg,
                    });
                  }
                });
              }
            }
          }
        });
      }
    });
  };

  const getNum = (a, datas) => {
    return datas.provinceData.indexOf(a) + 1;
  };

  const inputType1 = e => {
    setType1(e.target.value);
    form.setFieldsValue({ businessType: e.target.value });
  };
  const inputType2 = e => {
    setType2(e.target.value);
    form.setFieldsValue({ accountName: e.target.value });
  };

  const pickFiled = fileds => {
    if (form.getFieldValue(fileds)) {
      setTypes('add');
      setCharacterValue(form.getFieldValue(fileds));
      setCheckedList1(form.getFieldValue(fileds).split(','));
      setPickItem(fileds);
      setIsVisible(true);
    } else {
      setTypes('add');
      setCharacterValue(form.getFieldValue(fileds));
      setCheckedList1([]);
      setPickItem(fileds);
      setIsVisible(true);
    }
  };
  const pickFiled1 = fileds => {
    if (form.getFieldValue(fileds)) {
      setTypes('app');
      setCheckedList1(form.getFieldValue(fileds).split(','));
      setPickItem(fileds);
      setIsVisibleRoles(true);
    } else {
      setTypes('app');
      setCheckedList1([]);
      setPickItem(fileds);
      setIsVisibleRoles(true);
    }
  };
  const getRole = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.msg === 'Ok') {
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        setKeepFiled(groupArr(res.data, 'groupType'));
        setFf(filed1['角色']);
      }
    });
  };

  const groupArr = (initialArr, name) => {
    let list = {};
    initialArr.data.forEach(i => {
      let ar = [];
      i.root.forEach(j => {
        let ss = {};
        ss.label = j.Name;
        ss.value = j.ID.toString();
        ar.push(ss);
        // console.log(ss);
      });
      list[i.groupType] = ar;
    });
    return list;
  };
  const getFeedbackTable = () => {
    NewCM_XWBPlan_feedbackTable().then(res => {
      if (res.code === 0) {
        let arr = [];
        res.data.forEach((item, index) => {
          arr.push(item.accountName);
        });
        setFiled(arr);
        dispatch({ type: 'SET_SELECT_LIST', data: arr });
        setKeepFeed(arr);
      }
    });
  };
  const formateArrDataA1 = (initialArr, name) => {
    let aa = [];
    let a1 = [];
    let a2;
    let a3 = [];
    initialArr.data.forEach(i => {
      a2 = i.groupType;
      a1 = i.root;
      a1.forEach(j => {
        j.group = a2;
      });
      aa.push(i.root);
    });
    aa.forEach(p => {
      p.forEach(o => {
        a3.push(o);
      });
    });
    // 判定传参是否符合规则
    if (!(a3 instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    a3.forEach(i => {
      if (nameArr.indexOf(i.group) === -1) {
        nameArr.push(i.group);
      }
    });
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in a3) {
        if (a3[j].group == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(a3[j]);
        }
      }
    }
    for (let key in tempObj) {
      let arr = [];
      tempObj[key].map(item => {
        tempObj[key] = arr;
        arr.push(item.Name);
      });
    }
    return tempObj;
  };

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

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

  const inputType = value => {
    if (value) {
      form.setFieldsValue({ businessType: value });
    }
  };

  const change = e => {
    if (e === true) {
      setVisibleChecked1(false);
    }
    setVisibleChecked(e);
    setAutoFlag(e);
  };

  const change1 = e => {
    setVisibleChecked1(e);
  };

  const mapTreeSelect = org => {
    if (org.children) {
      return (
        <TreeNode value={org.name} title={org.name} disabled>
          {org.children.map(item => mapTreeSelect(item))}
        </TreeNode>
      );
    }
    if (org.name) {
      return <TreeNode value={org.name} title={org.name} />;
    }
    return <TreeNode value={org} title={org} key={org} />;
  };

  const mapTree = org => {
    if (org.Value) {
      return (
        <TreeNode value={org.key} title={org.key} disabled>
          {org.Value.map(item => mapTree(item))}
        </TreeNode>
      );
    }
    return <TreeNode value={org} title={org} key={org} />;
  };

  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.FieldName}%${parent}`} title={org.FieldName} key={org.FieldName} />
    );
  };

  // 获取字段名数据
  const getGetTaskSyncField = (e, newKeep) => {
    // 编辑时初始处理数据为下拉框过滤调已选数据
    let dataList = newKeep ? newKeep : keep;
    if (e) {
      // 编辑时
      let datalist = [...e];
      let aa = e;
      let from = [];
      aa.forEach(i => {
        if (i && i.fromField) {
          from.push(`${i.fromField}%${i.fromTable}`);
        }
      });
      let lastFrom = [];
      dataList.forEach(j => {
        if (from.indexOf(j) === -1) {
          lastFrom.push(j);
        }
      });
      // let bb = detailData(dataList, from);
      // setKeepData(lastFrom);
      // setKeep(lastFrom);
      let arr = [];
      datalist.forEach(i => {
        if (i.fromTable) {
          arr.push({ fromField: `${i.fromField}%${i.fromTable}`, toField: i.toField });
        } else {
          arr.push({ fromField: i.fromField, toField: i.toField });
        }
      });
      setTimeout(() => {
        formAdd.setFieldsValue({ parmars: arr }); // 处理数据让下拉框回显title值
      }, 0);
    } else {
      setKeepData(dataList);
    }
  };

  const changeValue = () => {
    let aa = formAdd.getFieldsValue().parmars;
    if (aa) {
      let from = [];
      let to = [];
      aa.forEach(i => {
        if (i && i.fromField) {
          from.push(i.fromField);
        }
        if (i && i.toField) {
          to.push(i.toField);
        }
      });
      let lastTo = [];
      let lastFrom = [];
      keep.forEach(j => {
        if (from.indexOf(j) === -1) {
          lastFrom.push(j);
        }
      });
      // let bb = detailData(keep, from);
      // setKeepData(lastFrom);
      keepAll.forEach(j => {
        if (to.indexOf(j.name) === -1) {
          lastTo.push(j);
        }
      });
      setKeepTree(lastTo);
    }
  };

  const detailData = (val, from) => {
    let newKeep = {};
    val.forEach(i => {
      i.TableFields.forEach(j => {
        let data = `${j.FieldName}%${i.TableName}`;
        // if (from.indexOf(data) === -1) {
        //   if (!newKeep[i.TableName]) {
        //     newKeep[i.TableName] = [j];
        //   } else {
        //     newKeep[i.TableName].push(j);
        //   }
        // }

        if (from.indexOf(data) === -1) {
          j.show = true;
        } else {
          j.show = false;
        }
      });
    });
    let arr = [];
    let keys = Object.keys(newKeep);
    keys.forEach(item => {
      arr.push({ TableName: item, TableFields: newKeep[item] });
    });
    return val;
  };

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

  const getReloadTableField = (e, i) => {
    reloadTableFields({
      tableName: e,
    }).then(res => {
      if (res.msg === 'Ok') {
        setKeepAll(res.data.root);
        // 编辑时过滤下l拉框初始数据
        if (i) {
          let aa = i;
          let to = [];
          aa.forEach(j => {
            if (j && j.toField) {
              to.push(j.toField);
            }
          });
          let lastTo = [];
          res.data.root.forEach(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.forEach(item => {
          arrList.push(item.name);
        });
        data.TableFieldNames = arrList;
        data.TableName = e;
        listArr.push(data);
        let arr = formateArrDataA(res.data.root, 'group');
        let newArr = [];
        Object.keys(arr).forEach((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);
        });
        // setKeepTree(aa);
        // setKeepAll(aa);
        // all.current = aa;
      }
    });
  };
  const formateArrDataA = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    let arr = {};
    initialArr.forEach((item, index) => {
      let data = item.group;
      if (!arr[data]) {
        arr[data] = [item];
      } else {
        arr[data].push(item);
      }
    });
    return arr;
  };

  const onChangeFeed = (val, flag, str) => {
    NewGetFeedbackTableFields({ feedbackName: val }).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);
        setKeep(newData);
        if (str) {
          // 编辑初次回显处理过滤下拉款数据
          getGetTaskSyncField(str, newData);
        }
      }
    });
    newGetAccountConfigInfo({ accountName: val }).then(res => {
      if (res.code === 0) {
        let arr = [];
        res.data?.map(resData => {
          let list = resData.editFieldGroup.split(',');
          let newList = list.filter(i => i && i.trim());
          let data = { TableName: resData.tableName, TableFieldNames: newList };
          arr.push(data);
        });
        setFieldList(arr);
      }
    });
    if (flag) {
      formAdd.setFieldsValue({ parmars: [] });
    }
  };

  const handleLook = val => {
    setVisibleLook(true);
    setLoading(true);
    setRecord(val);
    GetAccountConfigInfo({ accountName: val }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        let obj = res.data.formJson && JSON.parse(res.data.formJson).properties;

        if (Object.keys(obj).length !== 0) {
          setFormJson({ formJson: res.data.formJson });
        } else {
          setFormJson(null);
        }
      }
    });
  };

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

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

  const options = [
    {
      value: '巡检',
    },
    {
      value: '保养',
    },
    {
      value: '水箱清洗',
    },
    {
      value: '扫码巡检',
    },
  ];

  return (
    <Drawer
      title="模板配置"
      visible={visible}
      destroyOnClose
      width="600px"
      {...props}
      footer={
        <Space>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        labelCol={{ span: 7 }}
        style={{ overflowY: 'scroll' }}
        className={styles.dragTable}
      >
        <Row>
          <Col span={24}>
            <div className={styles.titleIcon}>
              <div className={styles.icon} />
              <div className={styles.font}>模板基础信息</div>
            </div>
          </Col>
          <Col span={24}>
            <Item
              label="业务名称"
              name="businessName"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().businessName;
                    if (type === 'add' && keepTableData.indexOf(aa) != -1) {
                      return Promise.reject('业务名称已存在');
                    }
                    if (
                      type === 'edit' &&
                      keepTableData.indexOf(aa) != -1 &&
                      aa != formObj.businessName
                    ) {
                      return Promise.reject('业务名称已存在');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="业务名称不可重复" />
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="业务类型"
              name="businessType"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
                {
                  validator: (rule, value) => {
                    if (form.getFieldsValue().businessType == '') {
                      return Promise.reject('业务类型必填');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <AutoComplete placeholder="选择业务类型" options={options} allowClear />
            </Item>
          </Col>
          <Col span={24}>
            <div className={styles.titleIcon}>
              <div className={styles.icon} />
              <div className={styles.font}>模板应用范围</div>
            </div>
          </Col>
          <Col span={24}>
            <Item
              label="维保设备"
              name="accountName"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请选择维保设备',
                },
              ]}
            >
              <TreeSelect
                showSearch
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择维保设备"
                allowClear
                treeDefaultExpandAll
                showCheckedStrategy
                onChange={e => {
                  getParentList(e);
                }}
              >
                {treeData.map(i => mapTree(i))}
              </TreeSelect>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label={
                <div className={styles.labelItem}>
                  <Tooltip title="请使用SQL条件进行配置">
                    <InfoCircleOutlined
                      style={{
                        color: 'rgb(24, 144, 255)',
                        marginLeft: '5px',
                        marginRight: '3px',
                      }}
                    />
                  </Tooltip>
                  设备条件
                </div>
              }
              name="filterCondition"
              labelCol={{ span: 5 }}
              rules={[
                {
                  validator: (rule, value) => {
                    let filterValue = form.getFieldsValue().filterCondition;
                    if (filterValue) {
                      if (
                        filterValue.substring(0, 3) !== 'and' &&
                        filterValue.substring(0, 3) !== 'AND'
                      ) {
                        return Promise.reject('请以and开头');
                      }
                      return Promise.resolve();
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="例如：and 泵房品牌='熊猫'（SQL表达式）" />
            </Item>
          </Col>
          {form.getFieldsValue().accountName ? (
            <Col span={24}>
              <Item
                label={
                  <div className={styles.labelItem}>
                    <Tooltip title="针对组合设备的反馈模板方式，可独立配置模板并挂接父子关系，批量反馈">
                      <InfoCircleOutlined
                        style={{
                          color: 'rgb(24, 144, 255)',
                          marginLeft: '5px',
                          marginRight: '3px',
                        }}
                      />
                    </Tooltip>
                    父业务模板
                  </div>
                }
                name="parentId"
                labelCol={{ span: 5 }}
              >
                <Select placeholder="选择父业务模板" showSearch allowClear>
                  {parentList
                    ? parentList.map((item, index) => (
                      <Option key={index.ID} value={item.ID}>
                        {item.TemplateName}
                      </Option>
                    ))
                    : ''}
                </Select>
              </Item>
            </Col>
          ) : (
            <Col span={24}>
              <Item
                label={
                  <div className={styles.labelItem}>
                    <Tooltip title="针对组合设备的反馈模板方式，可独立配置模板并挂接父子关系，批量反馈">
                      <InfoCircleOutlined
                        style={{
                          color: 'rgb(24, 144, 255)',
                          marginLeft: '5px',
                          marginRight: '3px',
                        }}
                      />
                    </Tooltip>
                    父业务模板
                  </div>
                }
                name="parentId"
                labelCol={{ span: 5 }}
              >
                <Select placeholder="选择父业务模板" disabled>
                  {parentList
                    ? parentList.map((item, index) => (
                      <Option key={index.ID} value={item.ID}>
                        {item.TemplateName}
                      </Option>
                    ))
                    : ''}
                </Select>
              </Item>
            </Col>
          )}
          <Col span={24}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div
                    style={{
                      color: '#fb0000',
                      marginRight: '4px',
                      marginTop: '3px',
                      fontSize: '15px',
                    }}
                  >
                    *
                  </div>
                  <span>填报内容</span>
                </div>
              }
              name="feedbackName"
              labelCol={{ span: 5 }}
              style={{ marginBottom: '10px' }}
            >
              {/* <Select
                placeholder="请选择填报内容"
                showSearch
                allowClear
                onChange={e => onChangeFeed(e, 1)}
              >
                {filed
                  ? filed.map((item, index) => (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    ))
                  : ''}
              </Select> */}
              <div
                style={{
                  fontSize: '12px',
                  color: '#bfbcbc',
                  marginTop: '6px',
                  marginBottom: '5px',
                }}
              >
                请选择此设备巡检后的反馈表单，来源与类型为【设备反馈】的台账
              </div>
              {stateType === 'drag'
                ? dataSource.length > 0 && (
                  <Table
                    pagination={false}
                    dataSource={dataSource}
                    columns={columns}
                    rowKey={record => record.key}
                    components={{
                      body: {
                        wrapper: DraggableContainer,
                        row: DraggableBodyRow,
                      },
                    }}
                  />
                )
                : dataSource.length > 0 && (
                  <Table
                    pagination={false}
                    dataSource={dataSource}
                    columns={columns}
                    rowKey={record => record.key}
                    rowClassName={() => 'editable-row'}
                    components={{
                      body: {
                        row: EditableRow,
                        cell: EditableCell,
                      },
                    }}
                  />
                )}
            </Item>
          </Col>
          <Col span={12}>
            <Button
              onClick={handleAdd}
              icon={<EditOutlined />}
              style={{
                marginBottom: 16,
                marginLeft: 114,
                borderRadius: '5px',
              }}
            >
              添加设备反馈
            </Button>
          </Col>
          <Col span={12}>
            <Item valuePropName="checked" label="顺序验证" name="inOrder">
              <Switch checkedChildren="开启" unCheckedChildren="关闭" />
            </Item>
          </Col>
          <BaseTimeConfig
            keepTimeData={keepTimeData}
            ref={timeData}
            visible={visible}
            type={type}
          />
          {/* <Col span={24}>
            <Item labelCol={{ span: 5 }} valuePropName="checked" label="动态周期" name="isDynamicCycle">
              <Switch checkedChildren="开启" unCheckedChildren="关闭" />
            </Item>
          </Col> */}
          <Col span={24}>
            <div className={styles.titleIcon}>
              <div className={styles.icon} />
              <div className={styles.font}>任务执行角色</div>
            </div>
          </Col>
          <Col span={24}>
            <Item
              label="执行角色"
              name="doRole"
              labelCol={{ span: 5 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (form.getFieldValue().doRole === '') {
                      return Promise.reject('执行角色必填');
                    }
                    return Promise.resolve();
                  },
                },
                {
                  required: true,
                  message: '请选择执行角色',
                },
              ]}
            >
              <div style={{ display: 'flex' }}>
                <Item name="doRole" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择执行角色" allowClear />
                </Item>
                <Button
                  type="dashed"
                  onClick={() => pickFiled1('doRole')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          {/* <Col span={12}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Tooltip title="任务提前生成天数，仅适用于接口定时执行">
                    <InfoCircleOutlined
                      style={{
                        color: '#1890ff',
                        marginRight: '2px',
                      }}
                    />
                  </Tooltip>

                  <span>预生成天数</span>
                </div>
              }
              labelCol={{ span: 10 }}
              name="produceDays"
              rules={[
                {
                  required: true,
                  message: '请输入预生成天数',
                },
              ]}
            >
              <Input placeholder="请输入预生成天数" />
            </Item>
          </Col>
          <Col span={12}>
            <Item
              label="在线任务量"
              name="onLines"
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请输入在线任务量',
                },
              ]}
            >
              <Input placeholder="请输入在线任务量" />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="自动派发" name="autoAssign" labelCol={{ span: 10 }}>
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                checked={visibleChecked1}
                onChange={change1}
                disabled={autoFlag}
              />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="是否送审" name="isSubmit" labelCol={{ span: 10 }}>
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                checked={visibleChecked}
                onChange={change}
              />
            </Item>
          </Col>
           */}
          <Col span={24}>
            <div className={styles.titleIcon}>
              <div className={styles.icon} />
              <div className={styles.font}>异常事件联动</div>
            </div>
          </Col>
          <Col span={24}>
            <Item label="联动条件" name="feedbackRule" labelCol={{ span: 5 }}>
              <div
                style={{
                  border: '2px solid #6A98FA',
                  minHeight: '34px',
                  lineHeight: '34px',
                  textAlign: 'center',
                }}
                onClick={() => {
                  if (dataSource && dataSource.length === 0) {
                    message.warning('请先选择填报内容！');
                  } else {
                    editRule();
                  }
                }}
              >
                <span>{form.getFieldsValue().feedbackRule}</span>
              </div>
            </Item>
          </Col>
          {form.getFieldsValue().feedbackRule !== '' ? (
            <Col span={24}>
              <Item
                label="关联事件"
                name="relationEvent"
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: '请选择关联事件类型' }]}
              >
                <Select
                  placeholder="选择关联事件类型"
                  showSearch
                  onChange={e => onChangeEvent(e)}
                  allowClear
                >
                  {eventData
                    ? eventData.map((item, index) => (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    ))
                    : ''}
                </Select>
              </Item>
            </Col>
          ) : (
            <Col span={24}>
              <Item label="关联事件" name="relationEvent" labelCol={{ span: 5 }}>
                <Select
                  placeholder="选择关联事件类型"
                  showSearch
                  onChange={e => onChangeEvent(e)}
                  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: '114px' }}>
              当配置了关联事件后，可配置字段映射规则
            </span>
            <br />
            <span style={{ fontSize: '12px', color: '#bfbcbc', marginLeft: '114px' }}>
              配置后，设备维保发起的工单，可以传递该维保任务信息
            </span>
          </Col>
          <Col span={4} />
          <Col span={19}>
            <Item style={{ marginTop: '20px', marginLeft: '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();
                                },
                              },
                            ]}
                          >
                            <TreeSelect
                              showSearch
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择字段名"
                              treeDefaultExpandAll
                              style={{ width: '159px' }}
                              showCheckedStrategy
                              onFocus={() => {
                                if (dataSource && dataSource.length === 0) {
                                  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: '7px', width: '423px' }}
                        // disabled={keepData && !(keepData.length > 0)}
                        >
                          添加映射
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </Form>
            </Item>
          </Col>
        </Row>
      </Form>
      <ChangeAdd
        visible={isVisible}
        onCancel={() => setIsVisible(false)}
        callBackSubmit={onOK1}
        newCheckedList={checkedList1}
        isType={types}
        filed={filed}
        type={type}
        filed1={filed1}
        ff={ff}
        pickItem={pickItem}
        characterValue={characterValue}
      />
      <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}
      />
      <Modal
        title={record}
        visible={visibleLook}
        onCancel={() => setVisibleLook(false)}
        width="1536px"
        bodyStyle={{ height: '700px', overflow: 'scroll' }}
        footer={null}
      >
        <Spin spinning={loading}>
          {formJson ? (
            <FormRender schemaValues={formJson} />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ marginTop: '300px' }} />
          )}
        </Spin>
      </Modal>
    </Drawer>
  );
};
export default AddModal;
