/* eslint-disable no-shadow */
/*
 * @Description:
 * @Author: leizhe
 * @Date: 2022-04-06 11:38:46
 * @LastEditTime: 2022-04-15 09:56:38
 * @LastEditors: leizhe
 */
import React, { useState, useEffect } from 'react';
import {
  Button,
  Descriptions,
  Input,
  Card,
  Spin,
  Divider,
  Tabs,
  Table,
  Space,
  Tooltip,
  Modal,
  Image,
  Form,
  notification,
  message,
  Pagination,
} from 'antd';
import {
  typeList,
  modelManageList,
  deleteByModel,
  DelModelType,
  DownLoadModelType,
  GetBasicInfo,
  DownLoadModelTypeSingle,
} from '@/services/drawBoardManage/api';
import {
  FormOutlined,
  DeleteOutlined,
  PlusOutlined,
  DownloadOutlined,
  UploadOutlined,
  SyncOutlined,
  PlusSquareFilled,
} from '@ant-design/icons';
import classnames from 'classnames';
import zhCN from 'antd/es/locale/zh_CN';
import styles from './DrawBoardManage.less';
import AddModal from './AddModal';
import EditModal from './EditModal';
import AddTemplate from './AddTemplate';
import ChildAddTemplate from './ChildAddTemplate';
import EditTemplate from './EditTemplate';
import ImportModal from './ImportModal';

const { TabPane } = Tabs;

const DrawBoardManage = () => {
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [tableLoading, setTableLoading] = useState(false);
  const [treeLoading, setTreeLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [selectColor, setSelectColor] = useState({}); // 当前选中颜色,操作时设置
  const [treeData, setTreeData] = useState([]);
  const [pickItem, setPickItem] = useState('');
  const [rember1, setRember1] = useState();
  const [hoverItemIndex, setHoverItemIndex] = useState(0); // hover流程索引
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectGroup, setSelectGroup] = useState([]);
  const [addTemplateVisible, setAddTemplateVisible] = useState(false);
  const [childAddTemplateVisible, setChildAddTemplateVisible] = useState(false);
  const [checkStrictly, setCheckStrictly] = useState(false);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 已选字段配置数,机构改变时重置
  const [deleteVisible, setDeleteVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [multDeleteVisible, setMultDeleteVisible] = useState(false);
  const [changeObj, setChangeObj] = useState('');
  const [obj, setObj] = useState('');
  const [importVisible, setImportVisible] = useState(false);
  const { Search } = Input;
  const [keepId, setKeepId] = useState('');
  const [total, setTotal] = useState('');
  const setRowClassName = record => (record.id === selectColor.id ? styles.clickRowStyle : '');

  useEffect(() => {
    if (pickItem) {
      updateTableData(pickItem.name, searchWord);
    }
  }, [pickItem]);

  useEffect(() => {
    updateTrees();
    GetBasicInfo().then(res => {
      setKeepId(res.data);
    });
  }, []);

  // 获取Tree数据
  const updateTrees = () => {
    setTreeLoading(true);
    typeList({ name: '二维' }).then(res => {
      if (res.say.statusCode === '0000') {
        setTreeLoading(false);
        if (!pickItem) {
          // setPickItem(res.getMe[0]);
          updateTableData('', searchWord);
        }
        setTreeData(res.getMe);
      }
    });
  };

  // 获取表格数据
  const updateTableData = (e, searchWord) => {
    console.log(e);
    console.log(pickItem);
    setTableLoading(true);
    setSelectedRowKeys([]);
    modelManageList({
      dimonsion: '二维',
      name: searchWord,
      type: e,
    }).then(res => {
      setTableLoading(false);
      if (res.say.statusCode === '0000') {
        if (searchWord != '') {
          setShowSearchStyle(true);
        } else {
          setShowSearchStyle(false);
        }
        if (res.getMe.length > 0) {
          if (!pickItem) {
            let aa = [];
            console.log(res.getMe);
            res.getMe.map(i => {
              i.list.map(j => {
                aa.push(j);
              });
            });
            let bb = aa;
            if (bb.length > 0) {
              bb.map(i => {
                if (i.children.length > 0) {
                  i.children.map(j => {
                    delete j.children;
                  });
                } else {
                  delete i.children;
                }
              });
            }
            console.log(bb);
            console.log(bb.length);
            setTotal(bb.length);
            setTableData(bb);
            setSelectGroup(bb);
          } else {
            let aa = res.getMe[0].list;
            if (aa.length > 0) {
              aa.map(i => {
                if (i.children.length > 0) {
                  i.children.map(j => {
                    delete j.children;
                  });
                } else {
                  delete i.children;
                }
              });
            }
            console.log(aa.length);
            setTotal(aa.length);
            setTableData(aa);
            setSelectGroup(aa);
          }
        } else {
          setTotal(0);
          setTableData([]);
        }
      }
    });
  };

  // 获取表格数据
  const updateTableDataAll = (e, searchWord) => {
    setTableLoading(true);
    setSelectedRowKeys([]);
    modelManageList({
      dimonsion: '二维',
      name: searchWord,
      type: e,
    }).then(res => {
      setTableLoading(false);
      if (res.say.statusCode === '0000') {
        if (searchWord != '') {
          setShowSearchStyle(true);
        } else {
          setShowSearchStyle(false);
        }
        if (res.getMe.length > 0) {
          let aa = [];
          console.log(res.getMe);
          res.getMe.map(i => {
            i.list.map(j => {
              aa.push(j);
            });
          });
          let bb = aa;
          if (bb.length > 0) {
            bb.map(i => {
              if (i.children.length > 0) {
                i.children.map(j => {
                  delete j.children;
                });
              } else {
                delete i.children;
              }
            });
          }
          console.log(bb);
          console.log(bb.length);
          setTotal(bb.length);
          setTableData(bb);
          setSelectGroup(bb);
        } else {
          setTotal(0);
          setTableData([]);
        }
      }
    });
  };

  const columns = [
    {
      title: '模型类型',
      align: 'center',
      width: 200,
      dataIndex: 'typeName',
      key: 'typeName',
      render: (text, record) => {
        console.log(record);
        if (record.children) {
          console.log(record.children.length);
        }

        const obj = {
          children: <>{record.realModel == 0 ? <span size="middle">{text}</span> : <span />}</>,
          props: {},
        };
        obj.props.colSpan = 1;
        return obj;
      },
    },
    {
      title: '模型名称',
      align: 'center',
      width: 300,
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => {
        const obj = {
          children: <span>{searchStyle(text)} </span>,
          props: {},
        };
        obj.props.colSpan = 1;
        return obj;
      },
    },
    {
      title: '图像',
      align: 'center',
      width: 200,
      dataIndex: 'modelPath',
      key: 'modelPath',
      render: (text, record) => {
        let time = new Date();
        let timestamp = Date.parse(time);
        const obj = {
          children: (
            <Image
              src={
                window.location.origin +
                `/Publish/Web/File/ModelManage/ModelFilePreview/${encodeURIComponent(text)}?
                ${timestamp}`
              }
              height="50px"
            />
          ),
          props: {},
        };
        obj.props.colSpan = 1;
        return obj;
      },
    },
    // {
    //   title: '模型属性',
    //   align: 'center',
    //   width: 200,
    //   dataIndex: 'property',
    //   key: 'property',
    //   render: (text, record) => {
    //     const obj = {
    //       children: <span>{text} </span>,
    //       props: {},
    //     };
    //     obj.props.colSpan = 1;
    //     return obj;
    //   },
    // },
    {
      title: '设计者',
      align: 'center',
      dataIndex: 'people',
      width: 100,
      key: 'people',
      render: (text, record) => {
        const obj = {
          children: <span>{text} </span>,
          props: {},
        };
        obj.props.colSpan = 1;
        return obj;
      },
    },
    {
      title: '创建日期',
      align: 'center',
      width: 250,
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text, record) => {
        const obj = {
          children: <span>{text} </span>,
          props: {},
        };
        obj.props.colSpan = 1;
        return obj;
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 200,
      key: 'action',
      render: record => {
        let aa = (
          <Space size="middle">
            <Tooltip title="编辑">
              <FormOutlined
                onClick={() => onedit(record)}
                style={{ fontSize: '16px', color: '#1890FF' }}
              />
            </Tooltip>
            <Tooltip title="导出">
              <DownloadOutlined
                onClick={() => ExportSingle(record)}
                style={{ fontSize: '16px', color: '#1890FF' }}
              />
            </Tooltip>
            <Tooltip title="删除">
              <DeleteOutlined
                onClick={() => ondelete(record)}
                style={{ fontSize: '16px', color: '#1890FF' }}
              />
            </Tooltip>
          </Space>
        );
        const obj = {
          children: aa,
          props: {},
        };
        obj.props.colSpan = record.realModel == 0 ? 1 : 1;
        return obj;
      },
    },
    {
      title: '添加子模型',
      align: 'center',
      dataIndex: 'stateModel',
      key: 'stateModel',
      render: (text, record) => {
        const obj = {
          children: (
            <>
              {record.realModel == 0 ? (
                <Space size="middle">
                  <Tooltip title="新增">
                    <PlusOutlined
                      onClick={() => onadd(record)}
                      style={{ fontSize: '16px', color: '#1890FF' }}
                    />
                  </Tooltip>
                </Space>
              ) : (
                <Space size="middle" />
              )}
            </>
          ),
          props: {},
        };
        obj.props.colSpan = record.realModel == 0 ? 1 : 1;
        return obj;
      },
    },
  ];

  const onadd = e => {
    setObj(e);
    setChildAddTemplateVisible(true);
  };

  const onedit = e => {
    setObj(e);
    setEditVisible(true);
  };

  const onexport = e => {
    console.log(e);
    setObj(e);
    let a = document.createElement('a');
    a.href = `${e.imgUrl}${encodeURIComponent(e.modelPath)}?_site=null`;
    console.log(a);
    let sufStr = e.modelPath.split('.').pop();
    a.download = `${e.name}.${sufStr}`;
    a.click();
    a.remove();
  };

  const ondelete = e => {
    setObj(e);
    setDeleteVisible(true);
  };

  const submitSearchUser = () => {
    updateTableData(pickItem.name, searchWord);
  };

  const handleSearch = e => {
    setSearchWord(e.target.value);
    updateTableData(pickItem.name, e.target.value);
  };

  const addModal = () => {
    setAddModalVisible(true);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
      console.log(selectedRowKeys);
    },
    renderCell: (checked, record, index, originNode) => {
      if (record.realModel != 0) {
        return null;
      }
      return originNode;
    },
  };

  const onUnfold = (expanded, record) => {
    if (record.children) {
      const data = [...selectGroup];
      let index = data.indexOf(record);
      // let index = selectGroup.find(i => i.type || i.name == record.name);
      if (expanded) {
        data.push(record);
        setSelectGroup(data);
      } else {
        data.splice(index, 1);
        setSelectGroup(data);
      }
    }
  };

  // 模糊查询匹配的样式
  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 addTemplate = () => {
    setAddTemplateVisible(true);
  };

  const deleteModalData = () => {
    setTableLoading(true);
    DelModelType({ modelId: changeObj.id }).then(res => {
      setTableLoading(false);
      if (res.code === 0) {
        setDeleteModalVisible(false);
        notification.success({
          message: '删除成功',
          duration: 2,
        });
        updateTrees();
        if (pickItem.name == changeObj.name) {
          setPickItem('');
          setChangeObj('');
          updateTableDataAll('', searchWord);
        }
      } else {
        notification.error({
          message: '删除失败',
          description: res.msg,
        });
      }
    });
  };

  const deleteData = () => {
    setTableLoading(true);
    deleteByModel({ ids: obj.id }).then(res => {
      setTableLoading(false);
      if (res.statusCode === '0000') {
        setDeleteVisible(false);
        notification.success({
          message: '删除成功',
          duration: 2,
        });
        updateTableData(pickItem.name, searchWord);
      } else {
        notification.error({
          message: '删除失败',
          description: res.info,
        });
      }
    });
  };

  const multDeleteData = () => {
    setMultDeleteVisible(true);
  };

  const multDelete = () => {
    setTableLoading(true);
    deleteByModel({ ids: selectedRowKeys.toString() }).then(res => {
      setTableLoading(false);
      if (res.statusCode === '0000') {
        setMultDeleteVisible(false);
        notification.success({
          message: '删除成功',
          duration: 2,
        });
        updateTableData(pickItem.name, searchWord);
      } else {
        notification.error({
          message: '删除失败',
          description: res.info,
        });
      }
    });
  };

  const onAddTemplateSubmit = () => {
    setAddTemplateVisible(false);
    updateTableData(pickItem.name, searchWord);
  };

  const onChildAddTemplateSubmit = () => {
    setChildAddTemplateVisible(false);
    updateTableData(pickItem.name, searchWord);
  };

  const onEditTemplateSubmit = () => {
    setEditVisible(false);
    updateTableData(pickItem.name, searchWord);
  };

  const onImportSubmit = () => {
    setImportVisible(false);
    updateTableData(pickItem.name, searchWord);
  };

  const oneditlist = (e, item) => {
    e.stopPropagation();
    setChangeObj(item);
    setEditModalVisible(true);
  };

  const ondeletelist = (e, item) => {
    e.stopPropagation();
    setChangeObj(item);
    setDeleteModalVisible(true);
  };

  const importFile = () => {
    setImportVisible(true);
  };

  const ExportData = () => {
    if (selectedRowKeys.length == 0) {
      message.warning('请先选择导出的数据');
    } else {
      window.location.href = DownLoadModelType({ modelList: selectedRowKeys.toString() });
    }
  };

  const ExportSingle = e => {
    console.log(e);
    window.location.href = DownLoadModelTypeSingle({ modeId: e.id });
  };

  const choose = () => {
    setPickItem('');
    updateTableDataAll('', searchWord);
  };

  return (
    <div className={styles.base_container}>
      <Card style={{ width: '100%', height: 'calc(100vh - 130px)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%' }}>
          {/* 左侧类型树 */}

          <div style={{ width: '250px' }}>
            <Spin spinning={treeLoading} tip="loading...">
              <div
                style={{ display: 'flex', justifyContent: 'space-between', alignContent: 'center' }}
              >
                <span
                  style={{
                    fontSize: '15px ',
                    fontWeight: 'bold',
                  }}
                >
                  模型类型
                </span>
                <Tooltip title="添加模型类型">
                  <PlusSquareFilled
                    onClick={() => addModal()}
                    style={{
                      color: '#1890FF',
                      fontSize: '25px',
                      marginTop: '3px',
                    }}
                  />
                </Tooltip>
              </div>
              <hr style={{ width: '100%', color: '#eeecec' }} />
              <div
                style={{
                  height: 'calc(100vh - 250px)',
                  overflowY: 'scroll',
                }}
              >
                <div
                  onClick={choose}
                  className={classnames({
                    [styles.allItem]: true,
                    [styles.pickItem]: pickItem === '',
                  })}
                >
                  <span style={{ marginLeft: '14px', lineHeight: '36px' }}>全部类型</span>
                </div>
                {treeData.length > 0 &&
                  treeData.map((item, index) => (
                    <div
                      className={classnames({
                        [styles.listItem]: true,
                        [styles.pickItem]: item.id === pickItem.id,
                        [styles.listHover]: item !== pickItem && item === hoverItemIndex,
                      })}
                      onClick={e => {
                        setPickItem(item);
                        setRember1(item);
                      }}
                      onMouseEnter={() => {
                        setHoverItemIndex(item);
                      }}
                      onMouseLeave={() => {
                        setHoverItemIndex('');
                      }}
                      key={item.id}
                    >
                      <div className={styles.title}>
                        <span>{item.name}</span>
                        <span className={styles.tip}>
                          <span>
                            <FormOutlined
                              onClick={e => oneditlist(e, item)}
                              style={{ color: '#1890FF', fontSize: '16px' }}
                            />
                          </span>
                          <span style={{ marginLeft: '10px' }}>
                            <DeleteOutlined
                              onClick={e => ondeletelist(e, item)}
                              style={{ color: '#e86060', fontSize: '16px' }}
                            />
                          </span>
                        </span>
                      </div>
                    </div>
                  ))}
              </div>
            </Spin>
          </div>

          {/* 右侧表格 */}
          <div
            style={{ width: '1400px', marginLeft: '20px', marginTop: '-10px', overflow: 'scroll' }}
          >
            <div
              style={{
                height: '41px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <div>
                <span style={{ width: '200px', display: 'inline-block' }}>
                  {pickItem.name}（已选{selectedRowKeys.length}/共{total}条）
                </span>
              </div>
              <div>
                <span style={{ lineHeight: '32px' }}>模型检索：</span>
                <Search
                  style={{ width: 260 }}
                  placeholder="请输入关键词"
                  onSearch={submitSearchUser}
                  onChange={e => handleSearch(e)}
                  enterButton
                  value={searchWord}
                />
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={addTemplate}
                  style={{ marginLeft: '20px' }}
                >
                  新增
                </Button>
                <Button
                  type="primary"
                  icon={<DeleteOutlined />}
                  onClick={multDeleteData}
                  style={{ marginLeft: '20px' }}
                >
                  删除
                </Button>
                {/* <Button
                  type="primary"
                  icon={<UploadOutlined />}
                  onClick={importFile}
                  style={{ marginLeft: '20px' }}
                >
                  导入
                </Button>
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={ExportData}
                  style={{ marginLeft: '20px' }}
                >
                  导出
                </Button> */}
              </div>
            </div>
            <Table
              rowSelection={{ ...rowSelection, selectedRowKeys }}
              rowClassName={setRowClassName}
              size="small"
              expandIconAsCell={false}
              expandIconColumnIndex={-1}
              rowKey={record => record.id}
              locale={zhCN}
              bordered
              expandedRowKeys={selectGroup.map(item => item.id)}
              // expandRowByClick
              columns={columns}
              dataSource={tableData}
              loading={tableLoading}
              scroll={{ x: 'max-content', y: 'calc(100vh - 262px)' }}
              onExpand={onUnfold}
              onRow={record => ({
                // onDoubleClick: event => {
                //   event.stopPropagation();
                //   editEventType(record);
                // }, // 双击
                onClick: e => {
                  setSelectColor(record);
                },
              })}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
          </div>
        </div>
      </Card>
      {/* 新增模板类型 */}
      <AddModal
        visible={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        updateTrees={updateTrees}
      />
      <EditModal
        visible={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        updateTrees={updateTrees}
        changeObj={changeObj}
      />
      <AddTemplate
        visible={addTemplateVisible}
        onClose={() => setAddTemplateVisible(false)}
        treeData={treeData}
        placement="right"
        pickItem={pickItem}
        callBackSubmit={onAddTemplateSubmit}
      />
      <ChildAddTemplate
        visible={childAddTemplateVisible}
        onClose={() => setChildAddTemplateVisible(false)}
        treeData={treeData}
        placement="right"
        pickItem={pickItem}
        obj={obj}
        callBackSubmit={onChildAddTemplateSubmit}
      />
      <EditTemplate
        visible={editVisible}
        onClose={() => setEditVisible(false)}
        treeData={treeData}
        placement="right"
        pickItem={pickItem}
        obj={obj}
        callBackSubmit={onEditTemplateSubmit}
      />
      <Modal
        visible={deleteModalVisible}
        onCancel={() => setDeleteModalVisible(false)}
        title="删除模型类型"
        okText="确认"
        cancelText="取消"
        onOk={deleteModalData}
      >
        <span>
          是否删除<span style={{ color: 'red' }}>{changeObj.name}</span>
        </span>
      </Modal>
      <Modal
        visible={deleteVisible}
        onCancel={() => setDeleteVisible(false)}
        title="删除"
        okText="确认"
        cancelText="取消"
        onOk={deleteData}
      >
        <span>是否删除该数据</span>
      </Modal>
      <Modal
        visible={multDeleteVisible}
        onCancel={() => setMultDeleteVisible(false)}
        title="批量删除"
        okText="确认"
        cancelText="取消"
        onOk={multDelete}
      >
        <span>是否批量删除所选数据</span>
      </Modal>
      <ImportModal
        visible={importVisible}
        onCancel={() => setImportVisible(false)}
        callBackSubmit={onImportSubmit}
      />
    </div>
  );
};
export default DrawBoardManage;
