/* eslint-disable no-shadow */
/* eslint-disable react/jsx-boolean-value */
import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Modal,
  Space,
  Table,
  Button,
  Popconfirm,
  Spin,
  notification,
  Tooltip,
  TreeSelect,
  Empty,
  Checkbox,
  Switch,
  Tag,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  SortDescendingOutlined,
  PlusSquareOutlined,
  RollbackOutlined,
  ConsoleSqlOutlined,
  EyeOutlined,
  ArrowLeftOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  reloadTableFields,
  removeFields,
  loadUnattachedTables,
  LoadLedgers,
} from '@/services/tablemanager/tablemanager';
import { FormDesigner } from 'panda-xform';
import { useHistory } from 'react-router-dom';
import FieldEditor from './fieldEditor';
import AffiliateAdd from '../components/Field/affiliateAdd';
import LoadGroup from '../components/Field/loadGroupNew';
import styles from './index.less';
import clearSvg from '@/assets/font/omsfont/clear.svg';
// import PerviewPrase from './PerviewPrase';
import { LayerSetting } from '@/services/gis/gis';
const AddModal = props => {
  const history = useHistory();
  const [allData, setAllData] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [keepTreeFirst, setKeepTreeFirst] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [formObj, setFormObj] = useState('');
  const [formName, setFormName] = useState('');
  const [flag, setFlag] = useState(0); // 弹窗类型
  const [isVisible, setIsVisible] = useState(false); // 弹窗
  const [isType, setIsType] = useState(''); // 弹窗类型
  const [itemData, setItemData] = useState({});
  const [select, setSelect] = useState([]);
  const [selectTableName, setSelectTableName] = useState({});
  const [pramFormObj, setPramFormObj] = useState({});
  const [visible, setVisible] = useState(false); // 弹窗
  const [type, setType] = useState(''); // 弹窗类型
  const [chooseLine, setChooseLine] = useState('');
  const { TreeNode } = TreeSelect;
  const [treeSelectValue, setTreeSelectValue] = useState(undefined);
  const [selectTreeData, setSelectTreeData] = useState([]);
  const [selectDataFirst, setSelectDataFirst] = useState([]);
  const [multiOperate, setMultiOperate] = useState(true); // 是否禁用用户批量操作
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 已选字段配置数,机构改变时重置
  const [deleteUserVisible, setDeleteUserVisible] = useState(false); // 批量删除
  const [checkStrictly, setCheckStrictly] = useState(false);
  const [selectGroup, setSelectGroup] = useState([]);
  const [keepStandingBook, setKeepStandingBook] = useState([]);
  const [keepTreeData, setKeepTreeData] = useState([]);
  const [keepTree, setKeepTree] = useState([]); // 保存树字段名称
  const [perviewPrase, setPerViewPrase] = useState(false);
  const [tablesSchema, setTablesSchema] = useState(null); // 存储parseForm组件需要的数据格式

  const formRef = useRef(null);

  const getField = () => {
    loadUnattachedTables().then(res => {
      if (res.data.root && res.data.root.length) {
        setTableList(res.data.root);
      }
    });
  };

  useEffect(() => {
    LoadLedgers().then(res => {
      if (res.code === 0) {
        let data = [];
        res.data.root.map(i => {
          data.push(i.name);
        });
        setKeepStandingBook(res.data.root);
      }
    });
    LayerSetting({ client: 'sandbox' }).then(res => {
      let dataArea = res.data.find(i => i.layerType == 'PipenetLayer');
      console.log(res.data[0]);
      let ss = {
        layers: [dataArea],
      };
      let depart = { OID: 1017, code: '1-1016-1017', name: '管理员' };
      let userInfo = { OID: 1, fullName: '总经理', loginName: 'admin', depart };
      window.globalConfig = {
        ...window.globalConfig,
        mapsettings: ss,
        userInfo,
      };
    });
  }, []);

  useEffect(() => {
    if (props.tableInfo.id) {
      setSelectTreeData(props.tableInfo.keepData);
      setSelectDataFirst(props.tableInfo.keepTreeFirst);
      if (treeSelectValue) {
        let ss = treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@'));
        setFormObj(treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@')));
        setFormName(treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@')));
        reloadTableFields({
          tableName: treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@')),
        }).then(res => {
          setTreeLoading(false);
          if (res.msg === 'Ok') {
            console.log(res.data.root);
            let arrlist = [];
            let data = {};
            let listArr = [];
            res.data.root.map(i => {
              arrlist.push(i.name);
            });
            console.log(arrlist);
            setKeepTree(arrlist);
            data.TableFieldNames = arrlist;
            data.TableName = treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@'));
            listArr.push(data);
            setKeepTreeData(listArr);
            let arr = formateArrDataA(res.data.root, 'group');
            let newArr = [];
            Object.keys(arr).map((item, index) => {
              newArr.push({ type: item, key: index, id: index });
            });
            setAllData(arr);
            let aa = [];
            let bb = [];

            let list = {};
            let arrdata = [];
            let flowNodeMeta = {};
            Object.keys(arr).forEach((item, index) => {
              console.log(arr[item]);
              arr[item].map(i => {
                i.fieldName = i.name;
                i.configInfo = i.config;
                i.presetValue = i.preset == '(无)' ? '' : i.preset;
                i.showCss = props.tableInfo.template.tableStyle;
                i.tableName = ss;
                i.uiGroup = item;
                i.readOnly = i.readOnly == '是' ? 1 : 0;
                i.type = '文本';
                i.visible = 1;
                i.colSpan = i.rowSpan;
              });
              aa.push({ name: item, key: index, ID: index, children: arr[item] });
              arrdata.push({ groupName: item, schema: arr[item], visible: 1 });
              bb.push(item);
            });
            flowNodeMeta.groups = arrdata;
            list.flowNodeMeta = flowNodeMeta;
            list.showCss = props.tableInfo.template.tableStyle;
            console.log(list);

            let tablesSchema = {
              child: {},
              groups: list.flowNodeMeta.groups,
              values: [],
              modules: [],
              relationForm: {},
            };
            setTablesSchema(tablesSchema);

            console.log(arr);
            console.log(newArr);
            setKeepTreeFirst(bb);
            setTreeData(aa);
            setSelectGroup(newArr);
            setTableData(newArr);
            setSelect(newArr);
          }
        });
      } else {
        let ss = props.tableInfo.id;
        setFormObj(props.tableInfo.id);
        setFormName(props.tableInfo.name);
        reloadTableFields({
          tableName: props.tableInfo.id,
        }).then(res => {
          setTreeLoading(false);
          if (res.msg === 'Ok') {
            console.log(res.data.root);
            let result = {};
            // result.
            let arrlist = [];
            let data = {};
            let listArr = [];
            res.data.root.map(i => {
              arrlist.push(i.name);
            });
            console.log(arrlist);
            setKeepTree(arrlist);
            data.TableFieldNames = arrlist;
            data.TableName = props.tableInfo.id;
            listArr.push(data);
            setKeepTreeData(listArr);
            let arr = formateArrDataA(res.data.root, 'group');
            let newArr = [];
            Object.keys(arr).map((item, index) => {
              newArr.push({ type: item, key: index, id: index });
            });
            setAllData(arr);
            let aa = [];
            let bb = [];
            let list = {};
            let arrdata = [];
            let flowNodeMeta = {};
            Object.keys(arr).forEach((item, index) => {
              console.log(arr[item]);
              arr[item].map(i => {
                i.fieldName = i.name;
                i.configInfo = i.config;
                i.presetValue = i.preset == '(无)' ? '' : i.preset;
                i.showCss = props.tableInfo.template.tableStyle;
                i.tableName = ss;
                i.uiGroup = item;
                i.readOnly = i.readOnly == '是' ? 1 : 0;
                i.type = '文本';
                i.visible = 1;
                i.colSpan = i.rowSpan;
              });
              aa.push({ name: item, key: index, ID: index, children: arr[item] });
              arrdata.push({ groupName: item, schema: arr[item], visible: 1 });
              bb.push(item);
            });
            flowNodeMeta.groups = arrdata;
            list.flowNodeMeta = flowNodeMeta;
            list.showCss = props.tableInfo.template.tableStyle;
            console.log(list);

            let tablesSchema = {
              child: {},
              groups: list.flowNodeMeta.groups,
              values: [],
              modules: [],
              relationForm: {},
            };
            setTablesSchema(tablesSchema);
            console.log(aa, 'aaaaaaaaaaaaa');
            console.log(arr);
            console.log(newArr);
            setSelectGroup(newArr);
            setKeepTreeFirst(bb);
            setTreeData(aa);
            setTableData(newArr);
            setSelect(newArr);
          }
        });
      }
      setTreeLoading(true);
      getField();
    }
  }, [flag, props.tableInfo]);

  const formateArrDataA = (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 back = () => {
    console.log(props.tableInfo);
    let {
      template,
      tableScroll,
      keepValue,
      pickIndex,
      groupArr,
      searchValue,
      select,
    } = props.tableInfo;
    console.log(keepValue);
    console.log(pickIndex, groupArr, 'back');
    history.push({
      pathname: '/biz/account/table',
      query: {
        template,
        tableScroll,
        backIndex: pickIndex,
        group: groupArr,
        keepValue,
        searchV: searchValue,
        selectValue: select,
      },
    });
  };

  const treeSelectOnchange = e => {
    console.log(e);
    if (e) {
      setTreeLoading(true);
      console.log('切换');
      setSelectedRowKeys([]);
      setMultiOperate(true);
      setTreeSelectValue(e);
      console.log(e.substring(0, e.lastIndexOf('@')));
      let ss = e.substring(0, e.lastIndexOf('@'));
      setFormObj(e.substring(0, e.lastIndexOf('@')));
      reloadTableFields({
        tableName: e.substring(0, e.lastIndexOf('@')),
      }).then(res => {
        setTreeLoading(false);
        if (res.msg === 'Ok') {
          let arrlist = [];
          let data = {};
          let listArr = [];
          res.data.root.map(i => {
            arrlist.push(i.name);
          });
          console.log(arrlist);
          setKeepTree(arrlist);
          data.TableFieldNames = arrlist;
          data.TableName = e.substring(0, e.lastIndexOf('@'));
          listArr.push(data);
          setKeepTreeData(listArr);
          console.log(res.data.root);
          let arr = formateArrDataA(res.data.root, 'group');
          let newArr = [];
          Object.keys(arr).map((item, index) => {
            newArr.push({ type: item, key: index, id: index });
          });
          setAllData(arr);
          setSelectGroup(newArr);
          setTableData(newArr);
          let aa = [];
          let bb = [];
          let list = {};
          let arrdata = [];
          let flowNodeMeta = {};
          Object.keys(arr).forEach((item, index) => {
            arr[item].map(i => {
              i.fieldName = i.name;
              i.configInfo = i.config;
              i.presetValue = i.preset == '(无)' ? '' : i.preset;
              i.showCss = props.tableInfo.template.tableStyle;
              i.tableName = ss;
              i.uiGroup = item;
              i.readOnly = i.readOnly == '是' ? 1 : 0;
              i.type = '文本';
              i.visible = 1;
              i.colSpan = i.rowSpan;
            });
            aa.push({ name: item, key: index, ID: index, children: arr[item] });
            arrdata.push({ groupName: item, schema: arr[item], visible: 1 });
            bb.push(item);
          });
          flowNodeMeta.groups = arrdata;
          list.flowNodeMeta = flowNodeMeta;
          list.showCss = props.tableInfo.template.tableStyle;
          console.log(list);

          let tablesSchema = {
            child: {},
            groups: list.flowNodeMeta.groups,
            values: [],
            modules: [],
            relationForm: {},
          };
          setTablesSchema(tablesSchema);
          setKeepTreeFirst(bb);
          setTreeData(aa);
          setSelect(newArr);
        }
      });
    } else {
      setTreeSelectValue('');
    }
  };
  const mapTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    return haveChildren ? (
      <TreeNode value={org.name} title={org.name} disabled>
        {org.children.map(item => mapTree(item))}
      </TreeNode>
    ) : (
      <TreeNode
        value={`${org.tableName}@${org.groupName}|${org.tableID}`}
        title={org.tableName}
        key={`${org.tableName}@${org.groupName}|${org.tableID}`}
      />
    );
  };

  // 附加
  const add = record => {
    if (treeSelectValue) {
      selectTreeData.map(i => {
        i.children.map(j => {
          if (j.tableName == treeSelectValue.substring(0, treeSelectValue.lastIndexOf('@'))) {
            setPramFormObj(j);
          }
        });
      });
    } else {
      setPramFormObj(props.tableInfo.template);
    }
    setType('affiliateAdd');
    setVisible(true);
  };

  const onSubmit = prop => {
    setVisible(false);
    setFlag(flag + 1);
  };
  return (
    <Modal
      title={
        <div className={styles.config}>
          {/* <ArrowLeftOutlined onClick={back} className={styles.goBack} /> */}
          <div className={styles.title}> 展示名称 【{formName}】</div>
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            {/* <div style={{ lineHeight: '32px', marginRight: '5px' }}>快速切换表:</div>
          <div style={{ width: '350px', marginRight: '10px' }}>
            <TreeSelect
              showSearch
              style={{ width: '100%' }}
              value={treeSelectValue}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择表名 "
              allowClear
              treeDefaultExpandAll
              showCheckedStrategy
              onChange={treeSelectOnchange}
            >
              {selectTreeData ? (
                selectTreeData.map(i => mapTree(i))
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </TreeSelect>
          </div> */}
            <div className={styles.btn}>
              <Button
                type="primary"
                // icon={<PlusSquareOutlined />}
                ghost
                onClick={() => formRef.current.clear()}
              >
                <img src={clearSvg} style={{ marginRight: '6px' }} alt="" />
                清空
              </Button>
              <Button
                type="primary"
                ghost
                icon={<EyeOutlined />}
                onClick={() => formRef.current.preview()}
                style={{ marginLeft: '10px' }}
              >
                预览
              </Button>
              <Button
                type="primary"
                icon={<UploadOutlined />}
                onClick={() => formRef.current.submit()}
                style={{ marginLeft: '10px' }}
              >
                提交
              </Button>
              {/* <Button type="primary" icon={<PlusSquareOutlined />} onClick={add}>
              附加
            </Button> */}
              {/* <Button
              type="primary"
              icon={<RollbackOutlined />}
              onClick={back}
              style={{ marginLeft: '30px' }}
            >
              返回
            </Button> */}
            </div>
          </div>
        </div>
      }
      visible={props.fieldConfigShow}
      // onOk={getNewGroup}
      onCancel={() => props.setFieldConfigShow(false)}
      footer={null}
      width="100vw"
      style={{
        maxWidth: '100vw',
        top: 0,
        paddingBottom: 0,
      }}
      bodyStyle={{
        height: 'calc(100vh - 55px)',
      }}
      getContainer={false}
    >
      {/* <Spin tip="loading..." spinning={treeLoading}> */}
      <div className={styles.containerBox}>
        <div style={{ width: '100%', height: 'calc(100% - 63px)', padding: '10px' }}>
          {formObj && <FormDesigner ref={formRef} tableName={formObj} />}
        </div>
      </div>
      {/* </Spin> */}
      {visible && type === 'affiliateAdd' && (
        <AffiliateAdd
          visible={visible}
          tableList={tableList}
          type={type}
          onCancel={() => setVisible(false)}
          callBackSubmit={onSubmit}
          formObj={pramFormObj}
        />
      )}
    </Modal>
  );
};
export default AddModal;
