/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import { Space, Table, Popconfirm, Tooltip, Button, notification } from 'antd';
import {
  CM_Feedback_LoadPatrolFeedbacks,
  CM_Feedback_RemovePatrolFeedback,
} from '@/services/PatrolFeedback/api';
import { EditTwoTone, DeleteOutlined, PlusOutlined, OrderedListOutlined } from '@ant-design/icons';
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 columns = [
    {
      title: '巡检对象',
      dataIndex: 'layerName',
      key: 'layerName',
      align: 'center',
    },
    {
      title: 'GIS图层',
      dataIndex: 'gisLayer',
      key: 'gisLayer',
      align: 'center',
    },
    {
      title: 'GIS条件',
      dataIndex: 'gisFilterValue',
      key: 'gisFilterValue',
      align: 'center',
    },
    {
      title: '反馈表',
      dataIndex: 'tableName',
      key: 'tableName',
      width: 400,
      onCell: () => ({
        style: {
          maxWidth: 400,
          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: 100,
      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: 100,
    },
    // {
    //   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);
        setTableData(res.data.list);
        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}>
        <div style={{ height: '50px', backgroundColor: 'white' }}>
          <span style={{ float: 'right', marginRight: '10px' }}>
            <Button
              icon={<PlusOutlined className={styles.icon} />}
              onClick={add}
              type="primary"
              style={{
                marginLeft: '30px',
                verticalAlign: 'middle',
                marginTop: '10px',
              }}
            >
              <span style={{ marginTop: '-2px' }}>新增</span>
            </Button>
            <Button
              icon={<OrderedListOutlined className={styles.icon} />}
              onClick={sort}
              style={{
                marginLeft: '30px',
                verticalAlign: 'middle',
                marginTop: '10px',
              }}
            >
              <span style={{ marginTop: '-2px' }}>调序</span>
            </Button>
            <Button
              icon={<DeleteOutlined className={styles.icon} />}
              style={{
                marginLeft: '30px',
                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}
          scroll={{ y: 'calc(100vh - 205px)', x: 'max-content' }}
          pagination={{
            showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
            pageSizeOptions: [10, 20, 50, 100],
            defaultPageSize: 20,
            showQuickJumper: true,
            showSizeChanger: true,
          }}
        />
        {/* 添加事件 */}
        <AddModal
          visible={addVisible}
          type={type}
          onClose={() => setAddVisible(false)}
          callBackSubmit={onSubmit}
          formObj={formObj}
          keepTableData={keepTableData}
          placement="right"
        />
        <SortModal
          title="调整顺序"
          visible={sortVisible}
          sortData={tableData}
          onCancel={() => setSortVisible(false)}
          callBackSubmit={onOK}
        />
      </div>
    </div>
  );
};

export default patrolFeedback;
