/* eslint-disable no-else-return */
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable camelcase */
import React, { useState, createContext, useEffect, useMemo, useReducer } from 'react';
import { Space, Table, Popconfirm, Tooltip, Button, notification, Tag, message } from 'antd';
import {
  CM_XWBPlan_DataList,
  NewCM_XWBPlan_DataList,
  CM_XWBPlan_RemovePlan,
  NewCM_XWBPlan_RemovePlan,
  CM_XWBPlan_ChangeOrder,
  NewCM_XWBPlan_ChangeOrder,
  GetDeviceConfigList,
  NewGetDeviceConfigList,
  EditDeviceConfig,
} from '@/services/maintenance/api';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  OrderedListOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';
import styles from './maintenance.less';
import AddModal from './AddModal';
import AddModalNew from './AddModalNew';
import OptionEditModal from './OptionEditModal';
import SortModal from './SortModal';
import DragTable from '@/components/DragTable/DragTable';
import { defaultState, reducer } from './store/reducer'; // 状态管理

export const Context = createContext();
const maintenance = () => {
  const [state, dispatch] = useReducer(reducer, defaultState);
  const [addVisible, setAddVisible] = useState(false);
  const [addVisibleNew, setAddVisibleNew] = useState(false);
  const [optionVisible, setOptionVisible] = useState(false);
  const [type, setType] = useState('');
  const [formObj, setFormObj] = useState('');
  const [treeLoading, setTreeLoading] = useState(false);
  const [flag, setFlag] = useState(0);
  const [sortVisible, setSortVisible] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [keepTableData, setKeepTableData] = useState([]);
  const [activeName, setActiveName] = useState('template');
  const [selectColor, setSelectColor] = useState({}); //

  const setRowClassName = nodeID => {
    return nodeID == selectColor ? styles.clickRowStyle : '';
  };

  useEffect(() => {
    setTreeLoading(true);
    if (activeName === 'template') {
      getDataList();
    } else if (activeName === 'project') {
      getNewDataList();
    } else {
      getConfigList();
    }
  }, [flag, activeName]);

  const getDataList = () => {
    CM_XWBPlan_DataList().then(res => {
      setTreeLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
        let list = [];
        res.data.map(i => {
          list.push(i.businessName);
        });
        setKeepTableData(list);
      } else {
        setTableData([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const getNewDataList = () => {
    NewCM_XWBPlan_DataList().then(res => {
      setTreeLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
        let list = [];
        res.data.map(i => {
          list.push(i.businessName);
        });
        setKeepTableData(list);
      } else {
        setTableData([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const getConfigList = () => {
    NewGetDeviceConfigList().then(res => {
      setTreeLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
      } else {
        setTableData([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const columns = useMemo(() => {
    if (activeName === 'template') {
      return [
        {
          title: '业务名称',
          dataIndex: 'businessName',
          key: 'businessName',
          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: 'businessType',
          key: 'businessType',
          width: 100,
          onCell: () => ({
            style: {
              maxWidth: 100,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),
          align: 'center',
          render: record => {
            if (record === '保养') {
              return <Tag color="purple">保养</Tag>;
            } else if (record === '巡检') {
              return <Tag color="geekblue">巡检</Tag>;
            } else if (record === '水箱清洗') {
              return <Tag color="cyan">水箱清洗</Tag>;
            } else if (record === '扫码巡检') {
              return <Tag color="cyan">扫码巡检</Tag>;
            } else {
              return <Tag color="orange">{record}</Tag>;
            }
          },
        },
        {
          title: '执行周期',
          dataIndex: 'docycle',
          key: 'docycle',
          width: 100,
          align: 'center',
          onCell: () => ({
            style: {
              maxWidth: 100,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        {
          title: '维保设备',
          dataIndex: 'accountName',
          key: 'accountName',
          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: 'parentBusinessName',
          key: 'parentBusinessName',
          width: 100,
          align: 'center',
        },
        {
          title: '反馈名称',
          dataIndex: 'feedbackName',
          key: 'feedbackName',
          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: 'doRole',
          key: 'doRole',
          align: 'center',
          width: 200,
          onCell: () => ({
            style: {
              maxWidth: 200,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),

          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        {
          title: '预生成天数',
          dataIndex: 'produceDays',
          key: 'produceDays',
          width: 90,
          align: 'center',
          onCell: () => ({
            style: {
              maxWidth: 90,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),
        },
        {
          title: '在线任务量',
          dataIndex: 'onLines',
          key: 'onLines',
          width: 90,
          align: 'center',
          onCell: () => ({
            style: {
              maxWidth: 90,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),
          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        // {
        //   title: '启停',
        //   dataIndex: 'doNot',
        //   key: 'doNot',
        //   width: 80,
        //   align: 'center',
        // },
        {
          title: '是否送审',
          dataIndex: 'isSubmit',
          key: 'isSubmit',
          width: 80,
          align: 'center',
          render: record => {
            if (record === '是') {
              return <Tag color="success">是</Tag>;
            } else {
              return <Tag color="processing">否</Tag>;
            }
          },
        },
        {
          title: '台账过滤条件',
          dataIndex: 'filterCondition',
          key: 'filterCondition',
          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: '操作',
          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>
          ),
        },
      ];
    } else if (activeName === 'project') {
      return [
        {
          title: '业务名称',
          dataIndex: 'businessName',
          key: 'businessName',
          width: 250,
          onCell: () => ({
            style: {
              maxWidth: 250,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          align: 'center',
          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        {
          title: '业务类型',
          dataIndex: 'businessType',
          key: 'businessType',
          width: 100,
          onCell: () => ({
            style: {
              maxWidth: 100,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          align: 'center',
          render: record => {
            if (record === '保养') {
              return <Tag color="purple">保养</Tag>;
            } else if (record === '巡检') {
              return <Tag color="geekblue">巡检</Tag>;
            } else if (record === '水箱清洗') {
              return <Tag color="cyan">水箱清洗</Tag>;
            } else if (record === '扫码巡检') {
              return <Tag color="cyan">扫码巡检</Tag>;
            } else if (record) {
              return <Tag color="orange">{record}</Tag>;
            }
          },
        },
        {
          title: '执行周期',
          dataIndex: 'docycle',
          key: 'docycle',
          align: 'center',
          width: 120,
          onCell: () => ({
            style: {
              maxWidth: 120,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          render: record => {
            if (record) {
              if (record.indexOf('{') === -1) {
                return record;
              } else {
                let list = JSON.parse(record);
                if (list.Unit === '小时') {
                  return <Tag color="#2db7f5">{list.CycleLen}小时一次</Tag>;
                } else if (list.Unit === '日') {
                  return <Tag color="#08979c">{list.CycleLen}日一次</Tag>;
                } else if (list.Unit === '周') {
                  return <Tag color="#d3adf7">{list.CycleLen}周一次</Tag>;
                } else if (list.Unit === '月') {
                  return <Tag color="#e3799e">{list.CycleLen}月一次</Tag>;
                }
              }
            }
          },
        },
        {
          title: '维保设备',
          dataIndex: 'accountName',
          key: 'accountName',
          width: 200,
          onCell: () => ({
            style: {
              maxWidth: 200,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          align: 'center',
        },
        {
          title: '填报内容',
          dataIndex: 'feedbackName',
          key: 'feedbackName',
          width: 300,
          onCell: () => ({
            style: {
              maxWidth: 300,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),
          align: 'center',
          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        {
          title: '联动条件',
          dataIndex: 'feedbackRule',
          key: 'feedbackRule',
          align: 'center',
          width: 100,
          render: record => {
            if (record) {
              return <Tag color="green">是</Tag>;
            } else {
              return <Tag color="blue">否</Tag>;
            }
          },
        },
        {
          title: '执行角色',
          dataIndex: 'doRole',
          key: 'doRole',
          align: 'center',
          width: 300,
          onCell: () => ({
            style: {
              maxWidth: 300,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            },
          }),

          render: record => (
            <Tooltip placement="topLeft" title={record}>
              {record}
            </Tooltip>
          ),
        },
        {
          title: '父业务模板',
          dataIndex: 'parentBusinessName',
          key: 'parentBusinessName',
          width: 100,
          align: 'center',
        },
        // {
        //   title: '台账过滤条件',
        //   dataIndex: 'filterCondition',
        //   key: 'filterCondition',
        //   width: 150,
        //   onCell: () => ({
        //     style: {
        //       maxWidth: 150,
        //       overflow: 'hidden',
        //       whiteSpace: 'nowrap',
        //       textOverflow: 'ellipsis',
        //     },
        //   }),
        //   align: 'center',
        //   render: record => (
        //     <Tooltip placement="topLeft" title={record}>
        //       {record}
        //     </Tooltip>
        //   ),
        // },
        {
          title: '操作',
          ellipsis: true,
          key: 'action',
          align: 'center',
          render: (text, record) => (
            <Space>
              <Tooltip title="修改">
                <EditTwoTone
                  onClick={() => {
                    editEventType(record);
                    setSelectColor(record.id);
                  }}
                  style={{ fontSize: '16px' }}
                />
              </Tooltip>
              <Tooltip title="删除">
                <Popconfirm
                  placement="bottomRight"
                  title={<p>是否确认删除？</p>}
                  okText="确认"
                  cancelText="取消"
                  onConfirm={() => {
                    deleteEventTypeNew(record);
                  }}
                >
                  <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                </Popconfirm>
              </Tooltip>
            </Space>
          ),
        },
      ];
    } else {
      return [
        {
          title: '维保设备',
          dataIndex: 'AccountName',
          key: 'AccountName',
          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: 'DeviceType',
          key: 'DeviceType',
          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: 'CarField',
          key: 'CarField',
          width: 100,
          align: 'center',
          render: record => {
            if (record) {
              return <Tag color="success">已配置</Tag>;
            } else {
              return <Tag color="processing">未配置</Tag>;
            }
          },
        },
        {
          title: '详情字段',
          dataIndex: 'DetailsField',
          key: 'DetailsField',
          width: 100,
          align: 'center',
          render: record => {
            if (record) {
              return <Tag color="success">已配置</Tag>;
            } else {
              return <Tag color="processing">未配置</Tag>;
            }
          },
        },
        {
          title: '维保反馈',
          dataIndex: 'FeedbackNames',
          key: 'FeedbackNames',
          width: 200,
          onCell: () => ({
            style: {
              maxWidth: 200,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),
          align: 'center',
          render: record => {
            if (record?.length) {
              return (
                <div>
                  {record.map(item => (
                    <div style={{ marginBottom: '2px' }}>
                      <Tag color="success">{item}</Tag>
                    </div>
                  ))}
                </div>
              );
            } else {
              return '-';
            }
          },
        },
        {
          title: '点检标准',
          dataIndex: 'StandardConfig',
          key: 'StandardConfig',
          width: 200,
          onCell: () => ({
            style: {
              maxWidth: 200,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          }),
          align: 'center',
          render: record => {
            let arr = JSON.parse(record || '[]');
            if (arr.length) {
              return <Tag color="success">已上传</Tag>;
            } else {
              return <Tag color="processing">未上传</Tag>;
            }
          },
        },
        {
          title: '操作',
          ellipsis: true,
          key: 'action',
          align: 'center',
          width: 200,
          render: (text, record) => (
            <Space>
              <Tooltip title="修改">
                <EditTwoTone onClick={() => editOption(record)} style={{ fontSize: '16px' }} />
              </Tooltip>
            </Space>
          ),
        },
      ];
    }
  }, [activeName]);

  const add = () => {
    if (activeName === 'project') {
      setAddVisibleNew(true);
    } else {
      setAddVisible(true);
    }

    setType('add');
  };
  const editEventType = record => {
    if (activeName === 'project') {
      setAddVisibleNew(true);
    } else {
      setAddVisible(true);
    }
    setType('edit');
    setFormObj(record);
  };
  const editOption = record => {
    let obj = record;
    obj.CarField = obj.CarField
      ? Array.from(new Set(obj.CarField.split(','))).join(',')
      : obj.CarField;
    obj.DetailsField = obj.DetailsField
      ? Array.from(new Set(obj.DetailsField.split(','))).join(',')
      : obj.DetailsField;
    setOptionVisible(true);
    setFormObj(obj);
  };
  const deleteEventType = record => {
    CM_XWBPlan_RemovePlan({ planId: record.id }).then(res => {
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        getDataList();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const deleteEventTypeNew = record => {
    NewCM_XWBPlan_RemovePlan({ planId: record.id }).then(res => {
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        getNewDataList();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  const onSubmit = () => {
    if (activeName === 'template') {
      setAddVisible(false);
    } else if (activeName === 'project') {
      setAddVisibleNew(false);
    } else {
      setOptionVisible(false);
    }
    setFlag(flag + 1);
  };

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

  const onOK = prop => {
    setSortVisible(false);
    let aa = prop.str.toString();
    CM_XWBPlan_ChangeOrder(aa).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 dragCallBack = value => {
    if (value && value.moveState) {
      let arr = [];
      value.data.forEach(i => {
        arr.push(i.id);
      });
      let aa = arr.toString();
      setTreeLoading(true);
      NewCM_XWBPlan_ChangeOrder(aa).then(res => {
        setTreeLoading(false);
        if (res.code === 0) {
          setFlag(flag + 1);
        } else {
          message.error(res.msg);
        }
      });
    }
  };

  return (
    <Context.Provider value={{ state, dispatch }}>
      <div className={styles.maintenanceContainer}>
        <div className={styles.contentContainers}>
          <div style={{ height: '50px', backgroundColor: 'white' }}>
            <div className={styles.tabs}>
              <div
                className={activeName === 'template' ? styles.active : ''}
                onClick={() => {
                  setActiveName('template');
                }}
              >
                维保模板
              </div>
              <div
                className={activeName === 'configuration' ? styles.active : ''}
                onClick={() => setActiveName('configuration')}
              >
                设备库配置
              </div>
              <div
                className={activeName === 'project' ? styles.active : ''}
                onClick={() => {
                  setActiveName('project');
                }}
              >
                方案制定
              </div>
            </div>
            <span
              style={{
                float: 'right',
                marginRight: '10px',
                display: activeName === 'template' || activeName === 'project' ? 'block' : 'none',
              }}
            >
              <Button
                icon={<PlusOutlined className={styles.icon} />}
                onClick={add}
                type="primary"
                style={{
                  verticalAlign: 'middle',
                  marginTop: '10px',
                  marginRight: '20px',
                }}
              >
                <span style={{ marginTop: '-2px' }}>新增</span>
              </Button>
              {activeName === 'template' && (
                <Button
                  icon={<OrderedListOutlined className={styles.icon} />}
                  onClick={sort}
                  style={{
                    verticalAlign: 'middle',
                    marginTop: '10px',
                  }}
                >
                  <span style={{ marginTop: '-2px' }}>调序</span>
                </Button>
              )}
            </span>
          </div>
          {activeName === 'project' ? (
            <DragTable
              rowClassName={record => setRowClassName(record.id)}
              size="small"
              ItemTypes="maintenance"
              rowKey={record => record.id}
              bordered
              loading={treeLoading}
              dragCallBack={dragCallBack}
              editEventType={editEventType}
              setSelectColor={setSelectColor}
              columns={columns}
              dataSource={tableData}
              scroll={{ y: 'calc(100vh - 215px)', x: 'max-content' }}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
          ) : (
            <Table
              // rowClassName={setRowClassName}
              size="small"
              rowKey="ID"
              bordered
              loading={treeLoading}
              onRow={record => ({
                onDoubleClick: event => {
                  event.stopPropagation();
                  if (activeName === 'template') {
                    editEventType(record);
                  } else {
                    editOption(record);
                  }
                }, // 双击
              })}
              columns={columns}
              dataSource={tableData}
              scroll={{ y: 'calc(100vh - 215px)', 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"
          />
          <AddModalNew
            visible={addVisibleNew}
            type={type}
            onClose={() => setAddVisibleNew(false)}
            callBackSubmit={onSubmit}
            formObj={formObj}
            keepTableData={keepTableData}
            placement="right"
          />
          <OptionEditModal
            visible={optionVisible}
            onClose={() => setOptionVisible(false)}
            callBackSubmit={onSubmit}
            formObj={formObj}
            placement="right"
          />
          <SortModal
            title="调整顺序"
            visible={sortVisible}
            sortData={tableData}
            onCancel={() => setSortVisible(false)}
            callBackSubmit={onOK}
          />
        </div>
      </div>
    </Context.Provider>
  );
};

export default maintenance;
