import React, { useEffect, useState } from 'react';
import classnames from 'classnames';
import {
  // Tree,
  Table,
  Space,
  Input,
  Button,
  Select,
  Popconfirm,
  notification,
  Spin,
  Tooltip,
  Badge,
  Spac,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  FontColorsOutlined,
  PlusSquareOutlined,
  SortDescendingOutlined,
  PlusOutlined,
  BorderInnerOutlined,
} from '@ant-design/icons';
import PageContainer from '@/components/BasePageContainer';
import {
  CM_Table_LoadTable,
  removeTable,
  loadUnattachedTables,
} 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 AffiliateAdd from './components/Field/affiliateAdd';
import LoadGroup from './components/Field/loadGroup';
import LoadGroupNew from './components/Field/loadGroupNew';
import { ChangedEvent } from 'gojs';
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 [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]);
  useEffect(
    record => {
      loadTable(searchValue);
      getField();
      //   if (props.history.location.query && selectTableName !== {}) {
      //     let { template } = props.history.location.query;
      //     setSelectTableName(template);
      //   }
    },
    [flag],
  );
  // 重字段配置返回后需要返回到原来的位置
  useEffect(() => {
    let arr = Object.keys(allData);
    console.log(selectTableName, 'selectTableName');
    console.log(arr, 'arr');
    console.log(props.history.location.query, 'props.history.location.query');
    if (arr.length > 0 && props.history.location.query && selectTableName == '') {
      console.log(234534256342);
      let { tableScroll, template, keepValue } = props.history.location.query;
      setSelectTableName(template);
      setTimeout(() => {
        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);
    console.log(keepValue);
    history.push({
      pathname: `/bsmanger/base/filedConfig/${record.tableName}`,
      state: {
        template: record,
        tableScroll: document.querySelector('.ant-table-body').scrollTop,
        keepValue: keepValue,
      },
    });
    // 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);
    setSearchValue(text);
    setShowSearchStyle(true);
  };
  const getField = () => {
    loadUnattachedTables().then(res => {
      if (res.data.root && res.data.root.length) {
        setTableList(res.data.root);
      }
    });
  };
  // 加载表
  const loadTable = keyword => {
    console.log(222);
    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 = [];
          Object.keys(groupData).map((item, index) => {
            newArr.push({ type: item, key: index });
          });
          console.log(newArr);
          setAllData(groupData);
          setGroupArr(newArr);
          setSelect(newArr);
        }
      })
      .catch(e => {
        setTreeLoading(true);
      });
  };
  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 expandedRowRender = item => {
    const columns1 = [
      {
        title: '名称',
        dataIndex: 'tableName',
        key: 'tableName',
        width: 300,
        render: (text, record) => (
          <div onClick={e => fieldsConfig(record, e)}>{searchStyle(text)}</div>
        ),
      },
      {
        title: '别名',
        dataIndex: 'tableAlias',
        key: 'tableAlias',
        align: 'center',
      },
      {
        title: '表格样式',
        dataIndex: 'tableStyle',
        key: 'tableStyle',
        align: 'center',
      },
      {
        title: '附加字段',
        dataIndex: 'fieldCount',
        key: 'fieldCount',
        align: 'center',
      },
      {
        title: '缺少字段',
        dataIndex: 'missingFieldCount',
        key: 'missingFieldCount',
        align: 'center',
        render: text => (
          <div
            className={classnames({
              [styles.lack]: text !== '(无)',
            })}
          >
            {text}
          </div>
        ),
      },
      {
        title: '未附加',
        dataIndex: 'extraFieldCount',
        key: 'extraFieldCount',
        align: 'center',
      },
      {
        title: '分组数量',
        dataIndex: 'groupCount',
        key: 'groupCount',
        align: 'center',
      },
      {
        title: '操作',
        ellipsis: true,
        key: 'tableID',
        align: 'center',
        render: (text, record) => (
          <Space>
            <Tooltip title="修改">
              <EditOutlined
                onClick={() => changeDesc(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 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 }} />;
    };

    return (
      <Table
        columns={columns1}
        bordered
        size="small"
        onRow={record => ({
          onDoubleClick: event => {
            console.log(keepValue);
            event.stopPropagation();
            history.push({
              pathname: `/bsmanger/base/filedConfig/${record.tableName}`,
              state: {
                template: record,
                tableScroll: document.querySelector('.ant-table-body').scrollTop,
                keepValue: keepValue,
              },
            });
          },
          onClick: event => {
            event.stopPropagation();
            setSelectTableName(record);
          }, // 点击行
        })}
        rowClassName={setRowClassName}
        showHeader={false}
        dataSource={allData[item.type]}
        pagination={false}
      />
    );
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'type',
      key: 'type',
      render: text => (
        <a style={{ fontWeight: 'bold' }}>
          {text}({allData && allData[text] ? allData[text].length : 0}个)
        </a>
      ),
      width: 260,
    },
    {
      title: '别名',
      dataIndex: 'tableAlias',
      key: 'tableAlias',
      align: 'center',
    },
    {
      title: '表格样式',
      dataIndex: 'tableStyle',
      key: 'tableStyle',
      align: 'center',
    },
    {
      title: '附加字段',
      dataIndex: 'fieldCount',
      key: 'fieldCount',
      align: 'center',
    },
    {
      title: '缺少字段',
      dataIndex: 'missingFieldCount',
      key: 'missingFieldCount',
      align: 'center',
      render: text => <div>{text}</div>,
    },
    {
      title: '未附加',
      dataIndex: 'extraFieldCount',
      key: 'extraFieldCount',
      align: 'center',
    },
    {
      title: '分组数量',
      dataIndex: 'groupCount',
      key: 'groupCount',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
    },
  ];
  const onUnfold = (expanded, record) => {
    const data = [...select];
    let index = data.indexOf(record);
    if (expanded) {
      data.push(record);
    } else {
      data.splice(index, 1);
    }
    setSelect(data);
    let arr = [];
    arr.push(record.key);
    if (expanded === true) {
      setChooseLine(arr);
      console.log(arr);
      setKeepValue(arr);
    } else {
      setChooseLine([]);
      setKeepValue([]);
    }
  };

  return (
    <Spin tip="loading..." spinning={treeLoading}>
      <PageContainer>
        <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>

            <Button
              type="primary"
              style={{ marginLeft: '10px' }}
              icon={<BorderInnerOutlined />}
              onClick={AddTable}
            >
              建表
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={AffiliateAddTable}
            >
              附加表
            </Button>
          </div>
          <div
            style={{
              width: '100vm',
              height: 'calc(100vh - 150px) ',
              background: '#ffffff',
            }}
          >
            {/* <Table
                            columns={columns}
                            dataSource={tableData}
                            //pagination={{ pageSize: 10 }}
                            scroll={{ x: 'max-content', y: 'calc(100vh - 228px)' }}
                            size="small"
                            style={{height:'8rem'}}
                            rowKey={(record, index) => `complete${record.tableID}${index}`}
                            pagination={{
                                showTotal: (total, range) =>
                                    `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                                pageSizeOptions: [10, 20, 50, 100],
                                defaultPageSize: 20,
                                showQuickJumper: true,
                                showSizeChanger: true,
                            }}
                        /> */}
            <Table
              className="components-table-demo-nested"
              columns={columns}
              expandable={{ expandedRowRender }}
              defaultExpandedRowKeys={[0]}
              expandRowByClick
              expandedRowKeys={chooseLine}
              dataSource={groupArr}
              scroll={{ y: 'calc(100vh - 190px)' }}
              size="small"
              pagination={false}
              onExpand={onUnfold}
              style={{ height: '8rem' }}
            />
          </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} />
        )}
        {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}
          />
        )}
      </PageContainer>
    </Spin>
  );
};
export default TableManager;
