/* eslint-disable object-shorthand */
import React, { useEffect, useState, useRef } from 'react';
import classnames from 'classnames';
import {
  // Tree,
  Table,
  Space,
  Input,
  Button,
  Select,
  Popconfirm,
  notification,
  Spin,
  Tooltip,
  Badge,
  Spac,
  Card,
  Dropdown,
  Menu,
  Modal,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  FontColorsOutlined,
  PlusSquareOutlined,
  SortDescendingOutlined,
  PlusOutlined,
  BorderInnerOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
  MenuOutlined,
  DatabaseOutlined,
  FunnelPlotOutlined,
  BranchesOutlined,
  ToolOutlined,
} from '@ant-design/icons';

import PageContainer from '@/components/BasePageContainer';
import {
  CM_Table_LoadTable,
  removeTable,
  loadUnattachedTables,
  checkTableType,
  regroupTableType,
} from '@/services/tablemanager/tablemanager';
import { useHistory } from 'react-router-dom';
import styles from './index.less';
import Editor from './components/Field/editor';
// import AddTablelList from './components/Field/addTable';
import AddTablelList from './components/TableView';
import AffiliateAdd from './components/Field/affiliateAdd';
import LoadGroup from './components/Field/loadGroup';
import LoadGroupNew from './components/Field/loadGroupNew';
import { defaultFields } from './components/defaultFields';
import { Ellipse } from 'bizcharts/lib/g-components';
const { Search } = Input;
const { Option } = Select;
const placeholder = '请输入表名';

const TableManager = props => {
  const history = useHistory();
  const [visible, setVisible] = useState(false); // 弹窗
  const [type, setType] = useState(''); // 弹窗类型
  const [formObj, setFormObj] = useState({});
  const [flag, setFlag] = useState(0); // 弹窗类型
  // const [initNum, setIntNum] = useState(0);
  const [searchValue, setSearchValue] = useState('');
  const [treeLoading, setTreeLoading] = useState(true);
  const [tableList, setTableList] = useState([]);
  const [groupArr, setGroupArr] = useState([]);
  const [allData, setAllData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [select, setSelect] = useState();
  const [selectTableName, setSelectTableName] = useState('');
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [chooseLine, setChooseLine] = useState([0]);
  const [keepValue, setKeepValue] = useState([0]);
  const [keepTreeSelect, setKeepTreeSelect] = useState([]);
  const [keepTreeFirst, setKeepTreeFirst] = useState([]);
  const [treeVisible, setTreeVisible] = useState(true); // 是否显示左侧树
  const [hoverItemIndex, setHoverItemIndex] = useState(0); // hover流程索引
  const [pickIndex, setPickIndex] = useState(0);
  const [tableType, setTableType] = useState(defaultFields[0].value);
  const [groupPopVisible, setgGroupPopVisible] = useState(false);
  const [checkMsg, setCheckMsg] = useState();

  const initNum = useRef(0);
  useEffect(
    record => {
      if (props.history.location.query && initNum.current == 0) {
        loadTable(props.history.location.query.searchV);
        setSearchValue(props.history.location.query.searchV);
      } else {
        loadTable(searchValue);
      }

      getField();
      //   if (props.history.location.query && selectTableName !== {}) {
      //     let { template } = props.history.location.query;
      //     setSelectTableName(template);
      //   }
    },
    [flag],
  );
  // 重字段配置返回后需要返回到原来的位置
  useEffect(() => {
    let arr = Object.keys(allData);

    if (
      arr.length > 0 &&
      props.history.location.query &&
      selectTableName == '' &&
      initNum.current == 0
    ) {
      let {
        tableScroll,
        template,
        keepValue,
        group,
        backIndex,
        selectValue,
      } = props.history.location.query;
      setSelectTableName(template);
      const i = group.findIndex(item => {
        return item.type == selectValue;
      });
      setTimeout(() => {
        setSelect(selectValue);
        setPickIndex(i);
        setGroupArr(group);
        document.querySelector('.ant-table-body').scrollTop = tableScroll;
      }, 0);
      setChooseLine(keepValue);
      setKeepValue(keepValue);
    }
  }, [allData]);

  // 附加
  const add = record => {
    setFormObj(record);
    setType('affiliateAdd');
    setVisible(true);
  };
  // 修改表名
  const changeDesc = record => {
    setType('edit');
    setVisible(true);
    setFormObj(record);
  };
  // 删除表
  const deleteChart = record => {
    removeTable({ tableID: record.tableID, removeFields: true }).then(res => {
      if (res.msg === 'Ok' || res.msg === '') {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        setFlag(flag + 1);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const onSubmit = prop => {
    setVisible(false);
    setFlag(flag + 1);
  };
  // 建表
  const AddTable = () => {
    setType('add');
    setVisible(true);
  };
  // 附加表
  const AffiliateAddTable = () => {
    setType('affiliateAdd');
    setFormObj({});
    setVisible(true);
  };
  // 字段配置
  const fieldsConfig = (record, e) => {
    e.stopPropagation();
    setFormObj(record);
    history.push({
      pathname: `/biz/account/fieldConfig`,
      state: {
        id: record.tableName,
        template: record,
        tableScroll: document.querySelector('.ant-table-body').scrollTop,
        groupArr: groupArr,
        pickIndex: pickIndex,
        searchValue: searchValue,
        select: select,
        keepValue: keepValue,
        keepTreeSelect: keepTreeSelect,
        keepTreeFirst: keepTreeFirst,
      },
    });
    // setType('config');
    // setVisible(true);
  };
  // 分组与排序
  const sort = record => {
    setFormObj(record);
    setType('sort');
    setVisible(true);
  };
  // 搜索框改变时存储输入的值
  const handleChange = e => {
    setSearchValue(e.target.value);
  };
  // 搜索
  const handleSearch = text => {
    loadTable(text, 'search');
    setSearchValue(text);
    setSelectTableName('');
    setPickIndex(0);
    setSelect(groupArr[0].type);
    setShowSearchStyle(true);
  };
  const getField = () => {
    loadUnattachedTables().then(res => {
      if (res.data.root && res.data.root.length) {
        setTableList(res.data.root.reverse());
      }
    });
  };
  // 加载表
  const loadTable = (keyword, isSearch) => {
    setTreeLoading(true);
    CM_Table_LoadTable({
      _version: 9999,
      filter: keyword || '',
    })
      .then(res => {
        setTreeLoading(false);
        if (res.msg === 'Ok') {
          // setTableData(res.data.root);
          let groupData = formateArrDataA(res.data.root, 'groupName');
          let newArr = [];
          let aa = [];
          let bb = [];
          console.log(groupData, 'groupData');
          // 对分组进行排序
          const sortNameArr = ['事件表', '工单表', '台账表', '设备表', '反馈表', '其他表'];
          const sortList = [];
          sortNameArr.forEach(ele => {
            Object.keys(groupData).map((item, index) => {
              if (item === ele) {
                newArr.push({ type: item, key: index, page: 1, pageSize: 20 });
                aa.push({ name: item, key: index, ID: index, children: groupData[item] });
                bb.push(item);
              }
            });
          });
          console.log(sortList, 'sortList');

          setAllData(groupData);
          if (!props.history.location.query || initNum.current > 0) {
            if (newArr.length > 0 && (!select || isSearch)) {
              setSelect(newArr[0].type);
            }
            if (groupArr.length == 0 || isSearch) {
              setGroupArr(newArr);
            }
          }
          setKeepTreeFirst(bb);
          setKeepTreeSelect(aa);
          initNum.current += 1;
        }
      })
      .catch(e => {
        setTreeLoading(false);
      });
  };
  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);
      });
    }
    return tempObj;
  };
  const setRowClassName = record =>
    Object.entries(record).toString() === Object.entries(selectTableName).toString()
      ? styles.clickRowStyle
      : '';
  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(
        new RegExp(searchValue, 'g'),
        `<span style='color:red'>${searchValue}</span>`,
      );
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'tableName',
      key: 'tableName',
      width: 400,
      render: (text, record) => (
        <div onClick={e => fieldsConfig(record, e)}>{searchStyle(text)}</div>
      ),
    },
    {
      title: '别名',
      dataIndex: 'tableAlias',
      key: 'tableAlias',
      align: 'center',
      render: text => <div>{text || '(无)'}</div>,
    },
    {
      title: '表格样式',
      dataIndex: 'tableStyle',
      key: 'tableStyle',
      align: 'center',
      width: 80,
      render: text => <div>{text || '大'}</div>,
    },
    {
      title: '附加字段',
      dataIndex: 'fieldCount',
      key: 'fieldCount',
      align: 'center',
      width: 80,
    },
    {
      title: '缺少字段',
      dataIndex: 'missingFieldCount',
      key: 'missingFieldCount',
      align: 'center',
      width: 80,
      render: text => (
        <div
          className={classnames({
            [styles.lack]: text !== '(无)',
          })}
        >
          {text}
        </div>
      ),
    },
    {
      title: '未附加',
      dataIndex: 'extraFieldCount',
      key: 'extraFieldCount',
      align: 'center',
      width: 80,
    },
    {
      title: '分组数量',
      dataIndex: 'groupCount',
      key: 'groupCount',
      align: 'center',
      width: 80,
    },
    {
      title: '接口',
      dataIndex: 'interfaceText',
      key: 'interfaceText',
      align: 'center',
      width: 80,
      render: record => {
        if (record) {
          return (
            <Tooltip title={record}>
              <span style={{ color: '#50aefc', cursor: 'pointer' }}>有</span>
            </Tooltip>
          );
        }
        return <span>无</span>;
      },
    },
    {
      title: '操作',
      ellipsis: true,
      key: 'tableID',
      align: 'center',
      width: 100,
      render: (text, record) => (
        <Space>
          <Tooltip title="修改">
            <EditOutlined
              onClick={() => changeDesc(record)}
              style={{ fontSize: '20px', color: '#1890FF' }}
            />
          </Tooltip>
          <Tooltip title="表配置">
            <MenuOutlined
              onClick={() => {
                setType('tableEdit');
                setVisible(true);
                setFormObj(record);
              }}
              style={{ fontSize: '20px', color: '#1890FF' }}
            />
          </Tooltip>
          {/* <Tooltip title="字段配置">
            <FontColorsOutlined
              onClick={e => fieldsConfig(record, e)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip> */}
          {/* <Tooltip title="附加">
            <PlusSquareOutlined
              onClick={() => add(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip> */}
          {/* <Tooltip title="分组与排序">
            <SortDescendingOutlined
              onClick={() => sort(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip> */}
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除该表？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                deleteChart(record);
              }}
            >
              <Tooltip title="删除">
                <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
              </Tooltip>
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];
  const pageChage = (page, pageSize) => {
    const list = JSON.parse(JSON.stringify(groupArr));
    list[pickIndex].page = page;
    list[pickIndex].pageSize = pageSize;
    setGroupArr(list);
  };
  const onMenuClick = e => {
    console.log('click', e);
    setTableType(e.key);
    AddTable();
  };
  // 检查表类型重分组
  const checkGroup = () => {
    checkTableType().then(res => {
      console.log(res);
      if (res.data === '检查完成，一切正常！') {
        notification.success({ message: '提示', duration: 3, description: res.data });
      } else {
        setCheckMsg(res.data);
        setgGroupPopVisible(true);
      }
    });
  };
  const getNewGroup = () => {
    regroupTableType().then(res => {
      if (res.code === 0) {
        // setFlag(flag + 1);
        setgGroupPopVisible(false);
        loadTable(searchValue, 'search');
        setSelectTableName('');
        setPickIndex(0);
        setSelect(groupArr[0].type);
        notification.success({ message: '提示', duration: 3, description: '执行成功' });
      }
    });
  };
  const menu = (
    <Menu
      onClick={onMenuClick}
      items={defaultFields.map(item => ({ key: item.value, label: item.value }))}
    />
  );
  return (
    <Spin tip="loading..." spinning={treeLoading}>
      <PageContainer>
        <div className={styles.content}>
          {/* 左侧树 */}
          <Spin spinning={treeLoading} tip="loading...">
            <Card
              className={classnames({
                [styles.orgContainer]: true,
                [styles.orgContainerHide]: !treeVisible,
              })}
            >
              <div style={{ display: `${treeVisible ? 'block' : 'none'}` }}>
                <span className={styles.processTitle}>
                  表分组
                  <Tooltip title="表类型重新分组检查">
                    <ToolOutlined
                      onClick={() => checkGroup()}
                      style={{
                        fontSize: '20px',
                        color: '#1890FF',
                        cursor: 'pointer',
                        marginLeft: '130px',
                      }}
                    />
                  </Tooltip>
                </span>
                <hr className={styles.splitLine} />

                <div
                  style={{
                    overflowY: 'scroll',
                    height: 'calc(100vh - 150px)',
                    overflowX: 'hidden',
                  }}
                >
                  {groupArr.length > 0 &&
                    groupArr.map((item, index) => (
                      <div
                        key={index}
                        className={classnames({
                          [styles.listItem]: true,
                          [styles.pickItem]: item.type === select,
                          [styles.listHover]: item.type !== select && item.type === hoverItemIndex,
                        })}
                        onMouseEnter={() => {
                          setHoverItemIndex(item.type);
                        }}
                        onMouseLeave={() => {
                          setHoverItemIndex('');
                        }}
                        onClick={() => {
                          setPickIndex(index);
                          setSelect(item.type);
                          setTableData(item.root);
                        }}
                      >
                        {item.type}（{allData[item.type]?.length}）
                      </div>
                    ))}
                </div>
              </div>
              <div className={styles.switcher}>
                {treeVisible && (
                  <Tooltip title="隐藏分组列表">
                    <DoubleLeftOutlined onClick={() => setTreeVisible(false)} />
                  </Tooltip>
                )}
                {!treeVisible && (
                  <Tooltip title="显示分组列表">
                    <DoubleRightOutlined onClick={() => setTreeVisible(true)} />
                  </Tooltip>
                )}
              </div>
            </Card>
          </Spin>
          <div className={styles.tablemanager_container}>
            <div className={styles.operate_bar}>
              <div className={styles.fast_search}>
                <div className={styles.title}>快速检索</div>
                <Search
                  allowClear
                  placeholder={placeholder}
                  onSearch={handleSearch}
                  onChange={handleChange}
                  value={searchValue}
                  enterButton
                  style={{ width: '300px' }}
                />
              </div>
              <Dropdown overlay={menu} arrow>
                <Button
                  type="primary"
                  icon={<BorderInnerOutlined />}
                  style={{ marginLeft: '10px' }}
                >
                  建表
                </Button>
              </Dropdown>
              <Button
                type="primary"
                style={{ marginLeft: '10px' }}
                icon={<PlusOutlined />}
                onClick={AffiliateAddTable}
              >
                附加表
              </Button>
            </div>
            <div style={{ flex: 1, position: 'relative', width: '100%' }}>
              <Table
                rowKey={record => record.key}
                size="small"
                bordered
                style={{ position: 'absolute' }}
                columns={columns}
                dataSource={allData[select]}
                scroll={{ x: 'max-content', y: 'calc(100vh - 217px)' }}
                rowClassName={setRowClassName}
                onRow={record => ({
                  onDoubleClick: event => {
                    event.stopPropagation();
                    history.push({
                      pathname: `/biz/account/fieldConfig`,
                      state: {
                        id: record.tableName,
                        template: record,
                        tableScroll: document.querySelector('.ant-table-body').scrollTop,
                        groupArr: groupArr,
                        pickIndex: pickIndex,
                        searchValue: searchValue,
                        select: select,
                        keepValue: keepValue,
                        keepTreeSelect: keepTreeSelect,
                        keepTreeFirst: keepTreeFirst,
                      },
                    });
                  },
                  onClick: event => {
                    event.stopPropagation();
                    setSelectTableName(record);
                  }, // 点击行
                })}
                pagination={{
                  showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                  pageSizeOptions: [10, 20, 50, 100],
                  defaultPageSize: 20,
                  showQuickJumper: true,
                  showSizeChanger: true,
                  current: groupArr[pickIndex] ? groupArr[pickIndex].page : 1,
                  pageSize: groupArr[pickIndex] ? groupArr[pickIndex].pageSize : 20,
                  onChange: (page, pageSize) => pageChage(page, pageSize),
                }}
              />
            </div>
          </div>
        </div>
        {visible && type == 'edit' && (
          <Editor
            visible={visible}
            onCancel={() => setVisible(false)}
            callBackSubmit={onSubmit}
            type={type}
            formObj={formObj}
          />
        )}
        {/* {visible && type === 'add' && (
          <AddTablelList type={type} onCancel={() => setVisible(false)} callBackSubmit={onSubmit} />
        )} */}
        <AddTablelList
          visible={visible && (type === 'add' || type === 'tableEdit')}
          type={type}
          onCancel={() => setVisible(false)}
          formObj={formObj}
          callBackSubmit={onSubmit}
          tableType={tableType}
        />
        {visible && type === 'affiliateAdd' && (
          <AffiliateAdd
            visible={visible}
            tableList={tableList}
            type={type}
            onCancel={() => setVisible(false)}
            callBackSubmit={onSubmit}
            formObj={formObj}
          />
        )}

        {/* {visible && type === 'sort' && (
          <LoadGroup
            visible={visible}
            type={type}
            formObj={formObj}
            onCancel={() => setVisible(false)}
            callBackSubmit={onSubmit}
          />
        )} */}
        {visible && type === 'sort' && (
          <LoadGroupNew
            visible={visible}
            type={type}
            formObj={formObj}
            onCancel={() => setVisible(false)}
            callBackSubmit={onSubmit}
          />
        )}
        <Modal
          title="确定要进行表类型重新分组吗？"
          visible={groupPopVisible}
          onOk={getNewGroup}
          onCancel={() => setgGroupPopVisible(false)}
        >
          <div style={{ whiteSpace: 'pre-line', textAlign: 'justify' }}>{checkMsg}</div>
        </Modal>
      </PageContainer>
    </Spin>
  );
};
export default TableManager;
