/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable camelcase */
import React, { useState, useEffect, useRef } from 'react';
import {
  Space,
  Table,
  Popconfirm,
  Tooltip,
  Button,
  notification,
  Spin,
  Card,
  Input,
  Pagination,
} from 'antd';
import {
  CM_Feedback_LoadPatrolFeedbacks,
  CM_Feedback_RemovePatrolFeedback,
} from '@/services/PatrolFeedback/api';
import { GetVectorService } from '@/services/webConfig/api';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  OrderedListOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
} from '@ant-design/icons';
import classnames from 'classnames';
import styles from './patrolFeedback.less';
import AddModal from './AddModal';
import SortModal from './SortModal';
import DragTable from '@/components/DragTable/DragTable';

const { Search } = Input;

const patrolFeedback = () => {
  const [addVisible, setAddVisible] = useState(false);
  const [type, setType] = useState('');
  const [formObj, setFormObj] = useState('');
  const [treeLoading, setTreeLoading] = useState(false);
  const [flag, setFlag] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [keepTableData, setKeepTableData] = useState([]);
  const [sortVisible, setSortVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 已选用户数,机构改变时重置
  const [groupName, setGroupName] = useState(['区域巡检', 'DMA巡检']);
  const [treeVisible, setTreeVisible] = useState(true); // 左边列表是否可见
  const [pickItem, setPickItem] = useState('区域巡检');
  const [hoverItemIndex, setHoverItemIndex] = useState('');
  // const [searchValue, setSearchValue] = useState('');
  const searchValue = useRef(null);
  const [keepSearch, setKeepSearch] = useState([]);
  const [newTableData, setNewTableData] = useState([]);
  const [pipeArr, setPipeArr] = useState([]);
  const groupNum = useRef({ 区域巡检: 0, DMA巡检: 0, 未分组: 0 });
  const tableList = useRef({
    pageIndex: 1,
    pageSize: 20,
    total: '',
  });

  const columns = [
    {
      title: '巡检对象',
      dataIndex: 'layerName',
      key: 'layerName',
      width: 150,
      fixed: 'left',
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      align: 'center',
      render: record => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '分组',
      dataIndex: 'groupType',
      key: 'groupType',
      align: 'center',
      width: 150,
    },
    {
      title: 'GIS图层',
      dataIndex: 'gisLayer',
      key: 'gisLayer',
      width: 200,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      align: 'center',
      render: record => <Tooltip title={record}>{record}</Tooltip>,
    },
    {
      title: 'GIS条件',
      dataIndex: 'gisFilterValue',
      key: 'gisFilterValue',
      width: 100,
      onCell: () => ({
        style: {
          maxWidth: 100,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      align: 'center',
      render: record => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '反馈表',
      dataIndex: 'tableName',
      key: 'tableName',
      width: 200,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      align: 'center',
      render: record => <Tooltip title={record}>{record}</Tooltip>,
    },
    {
      title: '关联事件',
      dataIndex: 'relationEvent',
      key: 'relationEvent',
      width: 200,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      align: 'center',
      render: record => <Tooltip title={record}>{record}</Tooltip>,
    },
    {
      title: '字段集',
      dataIndex: 'fields',
      key: 'fields',
      width: 80,
      align: 'center',
    },
    // {
    //   title: '异常值',
    //   dataIndex: 'exceptionValue',
    //   key: 'exceptionValue',
    //   width: 150,
    //   align: 'center',
    // },
    // {
    //   title: '触发事件',
    //   dataIndex: 'eventName',
    //   key: 'eventName',
    //   width: 150,
    //   align: 'center',
    // },
    {
      title: '权限',
      dataIndex: 'roles',
      key: 'roles',
      align: 'center',
      width: 50,
    },
    // {
    //   title: '分组',
    //   dataIndex: 'groupType',
    //   key: 'groupType',
    //   align: 'center',
    // },
    {
      title: '操作',
      ellipsis: true,
      key: 'action',
      align: 'center',
      width: 100,
      fixed: 'right',
      render: (text, record) => (
        <Space>
          <Tooltip title="修改">
            <EditTwoTone onClick={() => editEventType(record)} style={{ fontSize: '16px' }} />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              placement="bottomRight"
              title={<p>是否确认删除？</p>}
              okText="确认"
              cancelText="取消"
              onConfirm={() => deleteEventType(record)}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getTableList();
    pipeNetwork();
  }, []);

  // 获取管网及默认底图
  const pipeNetwork = () => {
    let pipeArr1 = [];
    GetVectorService().then(res => {
      if (res.code === 0) {
        if (res.data.VectorList.length > 0) {
          res.data.VectorList.map(item => {
            pipeArr1.push(item.ServiceName.split('.')[0]);
          });
        }
        if (pipeArr1.indexOf('虚拟图层') === -1) {
          pipeArr1.push('虚拟图层');
        }
        setPipeArr(pipeArr1);
      }
    });
  };

  const getTableList = (val, i) => {
    setTreeLoading(true);
    CM_Feedback_LoadPatrolFeedbacks({
      pageIndex: tableList.current.pageIndex,
      pageSize: tableList.current.pageSize,
      keyword: val ? val : searchValue.current,
    }).then(res => {
      let list = val ? val : searchValue.current;
      if (list) {
        setPickItem('');
      }
      if (i) {
        setPickItem('区域巡检');
      }
      setTreeLoading(false);
      if (res.code === 0) {
        let newGroupNum = {
          区域巡检: res.data.AreaInspectionCount,
          DMA巡检: res.data.DMAInspectionCont,
          未分组: res.data.ElseInspectionCont,
        };
        groupNum.current = newGroupNum;
        tableList.current.total = res.data.TotalCount;
        let data = {};
        if (res.data.list.length > 0) {
          let area = [];
          let dma = [];
          let other = [];
          res.data.list.map(i => {
            if (i.businessGroup === '区域巡检') {
              area.push(i);
            } else if (i.businessGroup === 'DMA巡检') {
              dma.push(i);
            } else if (
              i.businessGroup === '区域巡检,DMA巡检' ||
              i.businessGroup === 'DMA巡检,区域巡检'
            ) {
              area.push(i);
              dma.push(i);
            } else {
              other.push(i);
            }
          });
          data.区域巡检 = area;
          data.DMA巡检 = dma;
          if (other.length > 0) {
            data.未分组 = other;
            setGroupName(['区域巡检', 'DMA巡检', '未分组']);
          } else {
            setGroupName(['区域巡检', 'DMA巡检']);
          }
        }
        if (searchValue.current) {
          setNewTableData(res.data.list);
        } else {
          if (i) {
            setNewTableData(data['区域巡检']);
          } else {
            setNewTableData(data[pickItem]);
          }
        }
        setTableData(data);
        let list = [];
        res.data.list.map(i => {
          list.push(i.layerName);
        });
        setKeepTableData(list);
      }
    });
  };

  const add = () => {
    setAddVisible(true);
    setType('add');
  };
  const editEventType = record => {
    setAddVisible(true);
    setType('edit');
    setFormObj(record);
  };
  const deleteEventType = record => {
    CM_Feedback_RemovePatrolFeedback(record.id).then(res => {
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        getTableList();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const onOK = () => {
    getTableList();
  };

  const sort = () => {
    setSortVisible(true);
  };

  // 复选框
  const rowSelection = {
    selectedRowKeys,
    onChange: (RowKeys, Rows) => {
      setSelectedRowKeys(RowKeys);
    },
  };

  const hasSelected = selectedRowKeys.length > 0;

  const de = () => {
    CM_Feedback_RemovePatrolFeedback(selectedRowKeys.toString()).then(res => {
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '批量删除成功',
        });
        setSelectedRowKeys([]);
        getTableList();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  const dragCallBack = value => {
    if (value) {
      console.log(value);
    }
  };

  // 搜索
  const handleSearch = e => {
    searchValue.current = e;
    tableList.current.pageIndex = 1;
    let data = e === '' ? 1 : '';
    getTableList(e, data);
  };

  const paginationChange = (page, pageSizes) => {
    tableList.current.pageSize = pageSizes;
    tableList.current.pageIndex = page;
    getTableList();
  };

  return (
    <div className={styles.PatrolFeedbackContainer}>
      <div className={styles.contentContainers}>
        {/* 左侧事件树 */}
        <Spin spinning={treeLoading} tip="loading...">
          <Card
            className={classnames({
              [styles.orgContainer]: true,
              [styles.orgContainerHide]: !treeVisible,
            })}
          >
            <div style={{ height: '100%', display: treeVisible ? 'block' : 'none' }}>
              <span
                style={{
                  fontSize: '15px ',
                  fontWeight: 'bold',
                }}
              >
                业务划分
              </span>
              <hr style={{ width: '100%', color: '#eeecec' }} />
              <div
                style={{
                  height: 'calc(100% - 60px)',
                  overflowY: 'scroll',
                }}
              >
                {groupName.length > 0 &&
                  groupName.map((item, index) => (
                    <div
                      className={classnames({
                        [styles.listItem]: true,
                        [styles.pickItem]: item === pickItem,
                        [styles.listHover]: item !== pickItem && item === hoverItemIndex,
                      })}
                      onClick={e => {
                        setPickItem(item);
                        setNewTableData(tableData[item]);
                      }}
                      onMouseEnter={() => {
                        setHoverItemIndex(item);
                      }}
                      onMouseLeave={() => {
                        setHoverItemIndex('');
                      }}
                      key={index}
                    >
                      <div
                        style={{
                          width: '130px',
                          overflow: 'hidden',
                          whiteSpace: 'nowrap',
                          textOverflow: 'ellipsis',
                        }}
                      >
                        <Tooltip placement="top" title={item}>
                          {item}
                        </Tooltip>
                      </div>
                      （{tableData[item] ? groupNum.current[item] : ''}）
                    </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={{
              height: '50px',
              backgroundColor: 'white',
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span style={{ marginLeft: '20px', marginRight: '5px' }}>快速检索：</span>
              <Search
                allowClear
                placeholder="请输入巡检对象名称"
                onSearch={handleSearch}
                enterButton
                style={{ width: '300px' }}
              />
            </div>

            <div style={{ marginRight: '10px' }}>
              <Button
                icon={<PlusOutlined className={styles.icon} />}
                onClick={add}
                type="primary"
                style={{
                  verticalAlign: 'middle',
                  marginTop: '10px',
                }}
              >
                <span style={{ marginTop: '-2px' }}>新增</span>
              </Button>
              <Button
                icon={<OrderedListOutlined className={styles.icon} />}
                onClick={sort}
                style={{
                  verticalAlign: 'middle',
                  marginTop: '10px',
                }}
              >
                <span style={{ marginTop: '-2px' }}>调序</span>
              </Button>
              <Button
                icon={<DeleteOutlined className={styles.icon} />}
                style={{
                  verticalAlign: 'middle',
                  marginTop: '10px',
                }}
                onClick={de}
                disabled={!hasSelected}
              >
                <span style={{ marginTop: '-2px' }}>批量删除</span>
              </Button>
            </div>
          </div>
          <Table
            // rowClassName={setRowClassName}
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            size="small"
            rowKey={record => record.id}
            bordered
            loading={treeLoading}
            onRow={record => ({
              onDoubleClick: event => {
                event.stopPropagation();
                editEventType(record);
              }, // 双击
            })}
            columns={columns}
            dataSource={newTableData}
            scroll={{ y: '100%', x: 'max-content' }}
            pagination={false}
          />
          <div
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              // marginBottom: '10px',
            }}
          >
            <Pagination
              size="small"
              showTotal={(totals, range) => `第${range[0]}-${range[1]} 条/共 ${totals} 条`}
              total={tableList.current.total}
              showSizeChanger
              defaultPageSize={tableList.current.pageSize}
              defaultCurrent={1}
              pageSizeOptions={[10, 20, 50, 100]}
              current={tableList.current.pageIndex}
              onChange={paginationChange}
            />
          </div>
        </div>
        {/* 添加事件 */}
        <AddModal
          visible={addVisible}
          type={type}
          onClose={() => setAddVisible(false)}
          callBackSubmit={onOK}
          formObj={formObj}
          keepTableData={keepTableData}
          pipeArr={pipeArr}
          placement="right"
        />
        <SortModal
          title="调整顺序"
          visible={sortVisible}
          sortData={tableData[pickItem]}
          onCancel={() => setSortVisible(false)}
          callBackSubmit={onOK}
        />
      </div>
    </div>
  );
};

export default patrolFeedback;
