/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import { Space, Table, Popconfirm, Tooltip, Button, notification, Spin, Card } from 'antd';
import {
  CM_Feedback_LoadPatrolFeedbacks,
  CM_Feedback_RemovePatrolFeedback,
} from '@/services/PatrolFeedback/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 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 columns = [
    {
      title: '巡检对象',
      dataIndex: 'layerName',
      key: 'layerName',
      width: 150,
      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',
    },
    {
      title: 'GIS图层',
      dataIndex: 'gisLayer',
      key: 'gisLayer',
      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: '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 placement="topLeft" 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 placement="topLeft" 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',
      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(() => {
    setTreeLoading(true);
    CM_Feedback_LoadPatrolFeedbacks({ pageIndex: 0, pageSize: 0 }).then(res => {
      setTreeLoading(false);
      if (res.code === 0) {
        console.log(res.data.list);
        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巡检']);
          }
        }
        console.log(data);
        console.log(data['区域巡检']);
        console.log(data.区域巡检);
        setTableData(data);
        let list = [];
        res.data.list.map(i => {
          list.push(i.layerName);
        });
        setKeepTableData(list);
      }
    });
  }, [flag]);

  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: '删除成功',
        });
        setFlag(flag + 1);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  const onSubmit = () => {
    setAddVisible(false);
    setFlag(flag + 1);
  };

  const onOK = () => {
    setFlag(flag + 1);
  };

  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([]);
        setFlag(flag + 1);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  const dragCallBack = value => {
    if (value) {
      console.log(value);
    }
  };

  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);
                      }}
                      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] ? tableData[item].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={classnames({
            [styles.userContainer]: true,
            [styles.userContainerHide]: !treeVisible,
          })}
        >
          <div style={{ height: '50px', backgroundColor: 'white' }}>
            <span style={{ float: 'right', 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>
            </span>
          </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={tableData[pickItem]}
            scroll={{ y: 'calc(100% - 205px)', x: 'max-content' }}
            pagination={{
              showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
              pageSizeOptions: [10, 20, 50, 100],
              defaultPageSize: 20,
              showQuickJumper: true,
              showSizeChanger: true,
            }}
          />
        </div>
        {/* 添加事件 */}
        <AddModal
          visible={addVisible}
          type={type}
          onClose={() => setAddVisible(false)}
          callBackSubmit={onSubmit}
          formObj={formObj}
          keepTableData={keepTableData}
          placement="right"
        />
        <SortModal
          title="调整顺序"
          visible={sortVisible}
          sortData={tableData[pickItem]}
          onCancel={() => setSortVisible(false)}
          callBackSubmit={onOK}
        />
      </div>
    </div>
  );
};

export default patrolFeedback;
