/* eslint-disable no-unused-expressions */
import React, { useState, useEffect } from 'react';
import {
  Form,
  Card,
  Space,
  Table,
  Popconfirm,
  Spin,
  Tooltip,
  notification,
  Input,
  Button,
  Modal,
  Upload,
  message,
} from 'antd';

import {
  DoubleLeftOutlined,
  DoubleRightOutlined,
  PlusSquareFilled,
  RightOutlined,
  EditTwoTone,
  DeleteOutlined,
  SyncOutlined,
  ExportOutlined,
  ImportOutlined,
} from '@ant-design/icons';
import classnames from 'classnames';
import PageContainer from '@/components/BasePageContainer';
import {
  GetCM_Ledger_LoadLedgers,
  CM_Ledger_RmoveLedger,
  ExportLedgerConfig,
  CheckImportLedgerConfig,
  ImportLedgerConfig,
} from '@/services/standingBook/api';
import AddModal from './BookConfig';
import AddModalNew from './BookConfigNew';
import styles from './standingBook.less';
// import Search from 'antd/lib/transfer/search';
const StandingBook = props => {
  const [allData, setAllData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [maxLength, setMaxLength] = useState(0);
  const [treeVisible, setTreeVisible] = useState(true); // 左边列表是否可见
  const [formObj, setFormObj] = useState('');
  const [flag, setFlag] = useState(0); // 弹窗类型
  const [isVisible, setIsVisible] = useState(false); // 弹窗
  const [isType, setIsType] = useState(''); // 弹窗类型
  const [pickItem, setPickItem] = useState('');
  const [hoverItemIndex, setHoverItemIndex] = useState(0); // hover流程索引
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [searchData, setSearchData] = useState([]);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [keepTableData, setKeepTableData] = useState([]);
  const [searchFlag, setSearchFlag] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(20);
  const [data, setData] = useState([]);
  const { Item } = Form;
  const { Search } = Input;

  const editor = record => {
    setFormObj(record);
    setIsType('edit');
    setIsVisible(true);
  };
  const Submit = prop => {
    setIsVisible(false);
    setFlag(flag + 1);
  };

  const columns = [
    {
      title: '台账类型',
      dataIndex: 'AccountType',
      key: 'AccountType',
      width: 100,
    },
    {
      title: '台账名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 200,
      render: item => searchStyle(item),
    },

    {
      title: '台账表名',
      dataIndex: 'tableName',
      key: 'tableName',
      align: 'center',
      width: 200,
      ellipsis: true,
    },
    {
      title: '台账字段',
      dataIndex: 'fields',
      key: 'fields',
      align: 'center',
    },
    {
      title: '检索字段',
      dataIndex: 'searchFields',
      key: 'searchFields',
      align: 'center',
    },
    {
      title: '添加字段',
      dataIndex: 'addFields',
      key: 'addFields',
      align: 'center',
    },

    {
      title: '编辑字段',
      dataIndex: 'editFields',
      key: 'editFields',
      align: 'center',
    },
    {
      title: '前端字段',
      dataIndex: 'webFields',
      key: 'webFields',
      align: 'center',
    },
    {
      title: '手持字段',
      dataIndex: 'mobileFields',
      key: 'mobileFields',
      align: 'center',
      width: 100,
    },
    {
      title: '外部字段',
      dataIndex: 'outFields',
      key: 'outFields',
      align: 'center',
      width: 100,
      render: text => (
        <span
          style={{
            display: 'inline-block',
            width: '80px',
            color: Number(text) > 0 ? 'red' : '',
            backgroundColor: Number(text) > 0 ? 'yellow' : '',
          }}
        >
          {text}
        </span>
      ),
    },
    {
      title: '操作',
      ellipsis: true,
      align: 'center',
      render: (text, record) => (
        <Space>
          <Tooltip title="编辑此表">
            <EditTwoTone onClick={() => editor(record)} style={{ fontSize: '16px' }} />
          </Tooltip>
          <Tooltip title="导出台账">
            <ExportOutlined
              onClick={() => hadelExport(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip>

          <Tooltip title="删除此表">
            <Popconfirm
              placement="bottomRight"
              title={<p>是否删除此表</p>}
              // title={`确认删除用户${currentUser}`}
              okText="确认"
              cancelText="取消"
              onConfirm={() => deleteChart(record)}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];
  // 导出
  const hadelExport = record => {
    window.location.href = ExportLedgerConfig({
      ledgerId: record.ID,
    });
  };

  // 导入
  const beforeUpload = val => {
    // setFile(val);
    const formData = new FormData();
    formData.append('_files', val);
    CheckImportLedgerConfig(formData).then(res => {
      if (res.code === 0) {
        Modal.confirm({
          title: '提示',
          icon: '',
          content: <div style={{ whiteSpace: 'pre-wrap' }}>{res.data}</div>,
          onOk() {
            console.log('OK');
            ImportLedgerConfig(formData).then(response => {
              if (response.code === 0) {
                setFlag(flag + 1);
                message.success('导入成功');
              } else {
                message.error(response.msg);
              }
            });
          },
          okText: '确认导入',
          cancelText: '我再想想',
        });
      } else {
        message.error(res.msg);
      }
    });
    return false;
  };

  useEffect(() => {
    setTreeLoading(true);
    GetCM_Ledger_LoadLedgers().then(res => {
      setTreeLoading(false);
      if (res.msg === 'Ok' && res.data.root) {
        console.log(res.data.root);
        setKeepTableData(res.data.root);
        const maxOrder = res.data.root.reduce((pre, cur) =>
          pre.order > cur.order ? pre.order : cur.order,
        );
        setMaxLength(maxOrder + 1);
        // setMaxLength(res.data.root.length + 1);
        let arr = formateArrDataA(res.data.root, 'type');
        let newArr = [];
        let dataList = [];
        newArr.push('全部');
        Object.keys(arr).map((item, index) => {
          newArr.push(item);
          dataList.push(item);
        });
        console.log(arr);
        arr.全部 = res.data.root;
        setAllData(arr);
        setShowSearchStyle(false);
        // 第一次进入展示第一页 不是第一次进入根据当前选择的来进行展示
        console.log(flag);
        console.log(pickItem);
        flag === 0 ? setPickItem(newArr[0]) : setPickItem(pickItem);
        // setPickItem(newArr[0]);
        console.log(newArr, 'newArr');
        // newArr.push('全部');
        setTableData(newArr);
        setData(dataList);
        if (searchFlag === 1) {
          onSearch();
        }
      }
    });
  }, [flag]);
  const formateArrDataA = (initialArr, name) => {
    console.log(initialArr);
    console.log(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 deleteChart = record => {
    CM_Ledger_RmoveLedger({ ledgerId: record.ID }).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 showPopup = () => {
    setIsVisible(true);
    setIsType('add');
  };
  const onSubmit = () => {
    setIsVisible(false);
    setFlag(flag + 1);
  };

  const onSearch = () => {
    setSearchFlag(1);
    setTableLoading(true);
    setCurrentPage(1);
    setCurrentPageSize(20);
    GetCM_Ledger_LoadLedgers({ accountName: searchWord }).then(res => {
      setTableLoading(false);
      if (res.msg === 'Ok' && res.data.root) {
        let aa = res.data.root;
        if (pickItem == '全部') {
          if (aa.length > 0) {
            aa.map(i => {
              i.type = '全部';
            });
          }
        }
        console.log(aa);
        // const maxOrder = aa.reduce((pre, cur) => (pre.order > cur.order ? pre.order : cur.order));
        // setMaxLength(maxOrder + 1);
        let arr = formateArrDataA(aa, 'type');
        console.log(arr);
        setShowSearchStyle(true);
        // setAllData(arr);
        setSearchData(arr);
        // setPickItem('');
        // 第一次进入展示第一页 不是第一次进入根据当前选择的来进行展示
        // flag === 0 ? setPickItem(newArr[0]) : setPickItem(pickItem);
        // setTableData(newArr);
      }
    });
  };

  const handleSearch = e => {
    console.log(e.target.value);
    setSearchWord(e.target.value);
    setSearchFlag(0);
    // if (e.target.value == '') {
    //   setTableLoading(true);
    //   GetCM_Ledger_LoadLedgers().then(res => {
    //     setTableLoading(false);
    //     if (res.msg === 'Ok' && res.data.root) {
    //       console.log(res.data.root);
    //       setMaxLength(res.data.root.length + 1);
    //       let arr = formateArrDataA(res.data.root, 'type');
    //       let newArr = [];
    //       Object.keys(arr).map((item, index) => {
    //         newArr.push(item);
    //       });
    //       console.log(arr);
    //       setAllData(arr);
    //       setShowSearchStyle(false);
    //       // 第一次进入展示第一页 不是第一次进入根据当前选择的来进行展示
    //       flag === 0 ? setPickItem(newArr[0]) : setPickItem(pickItem);
    //       setPickItem(newArr[0]);
    //       console.log(newArr, 'newArr');
    //       setTableData(newArr);
    //     }
    //   });
    // }
  };

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(searchWord, 'g'), `<span style='color:red'>${searchWord}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };
  const handleReset = () => {
    setFlag(flag + 1);
  };

  const pageChage = (page, pageSize) => {
    console.log(page);
    console.log(pageSize);
    setCurrentPage(page);
    setCurrentPageSize(pageSize);
  };
  return (
    <PageContainer className={styles.userManageContainer}>
      <div className={styles.contentContainers}>
        <Spin spinning={treeLoading} tip="loading...">
          <Card
            className={classnames({
              [styles.orgContainer]: true,
              [styles.orgContainerHide]: !treeVisible,
            })}
          >
            {treeVisible ? (
              <>
                <div style={{ width: '214px', height: '100%' }}>
                  <span
                    style={{
                      fontSize: '15px ',
                      fontWeight: 'bold',
                      color: '#333E51',
                    }}
                  >
                    台账列表
                  </span>
                  <Tooltip title="添加台账表">
                    <PlusSquareFilled
                      style={{
                        color: '#1890FF',
                        fontSize: '25px',
                        float: 'right',
                        paddingRight: '5px',
                        marginTop: '2px',
                      }}
                      onClick={e => showPopup()}
                    />
                  </Tooltip>
                  <hr style={{ width: '97%', color: '#eeecec', marginLeft: '0px' }} />
                  <div
                    style={{
                      height: 'calc(100% - 35px)',
                      overflowY: 'scroll',
                    }}
                  >
                    {tableData.length > 0 &&
                      tableData.map((item, index) => (
                        <div
                          title={`${item}(${allData[item] ? allData[item].length : 0})`}
                          className={classnames({
                            [styles.listItem]: true,
                            [styles.pickItem]: item === pickItem,
                            [styles.listHover]: item !== pickItem && item === hoverItemIndex,
                          })}
                          onClick={() => {
                            setPickItem(item);
                            setSearchWord('');
                            setSearchFlag(0);
                            setCurrentPage(1);
                            setCurrentPageSize(20);
                          }}
                          onMouseEnter={() => {
                            setHoverItemIndex(item);
                          }}
                          onMouseLeave={() => {
                            setHoverItemIndex('');
                          }}
                          key={index}
                        >
                          {item}({allData[item] ? allData[item].length : 0})
                        </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={classnames({
            [styles.userContainer]: true,
            [styles.userContainerHide]: !treeVisible,
          })}
        >
          <div
            style={{
              marginTop: '10px',
              marginLeft: '10px',
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <Search
              style={{ width: 260 }}
              placeholder="台账名称"
              enterButton
              onSearch={onSearch}
              onChange={e => handleSearch(e)}
              value={searchWord}
              allowClear
            />
            {/* <Button icon={<SyncOutlined />} onClick={handleReset}>
              重置
            </Button> */}
            <Upload showUploadList={false} accept=".json" beforeUpload={beforeUpload}>
              <Button style={{ marginLeft: '10px' }} type="primary" ghost>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <ImportOutlined style={{ marginRight: '5px' }} />
                  <div>导入</div>
                </div>
              </Button>
            </Upload>
          </div>
          <div style={{ marginTop: '10px', height: 'calc(100% - 94px)' }}>
            <Table
              size="small"
              rowKey="ID"
              bordered
              onRow={record => ({
                onDoubleClick: event => {
                  event.stopPropagation();
                  editor(record);
                }, // 双击
              })}
              columns={columns}
              loading={tableLoading}
              dataSource={searchFlag === 0 ? allData[pickItem] : searchData[pickItem]}
              // loading={tableLoading}
              scroll={{ x: 'max-content', y: 'calc(100% - 40px)' }}
              // scroll={{ x: 'max-content' }}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
                current: currentPage,
                pageSize: currentPageSize,
                onChange: (page, pageSize) => pageChage(page, pageSize),
              }}
            />
          </div>
        </div>
        {/* <AddModal
          visible={isVisible}
          type={isType}
          data={data}
          pickItem1={pickItem}
          formObj={formObj}
          maxLength={maxLength}
          callBackSubmit={onSubmit}
          onCancel={() => setIsVisible(false)}
          tableData={tableData}
          keepTableData={keepTableData}
        /> */}
        <AddModalNew
          visible={isVisible}
          type={isType}
          data={data}
          pickItem1={pickItem}
          formObj={formObj}
          maxLength={maxLength}
          callBackSubmit={onSubmit}
          onCancel={() => setIsVisible(false)}
          tableData={tableData}
          keepTableData={keepTableData}
        />
      </div>
    </PageContainer>
  );
};
export default StandingBook;