/* eslint-disable array-callback-return */
/* eslint-disable no-shadow */
/* eslint-disable indent */
/* eslint-disable eqeqeq */
import React, { useEffect, useState } from 'react';
import {
  // Tree,
  Table,
  Space,
  Input,
  Button,
  Select,
  Popconfirm,
  message,
  Tooltip,
  Spin,
} from 'antd';
import {
  PlusCircleOutlined,
  EditTwoTone,
  DeleteOutlined,
  FundViewOutlined,
  FieldTimeOutlined,
  AlertTwoTone,
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import EditModal from './components/EditModal';
import PushTest from './components/PushTest/PushTest';
import VisibleRoleModal from './components/RolseSelect/VisibleRoleModal';
import {
  GetMessageConfigList,
  TestPush,
  DeleteMessageConfig,
  GetMsgTypeList,
  DeleteIISAgentConfig,
} from '@/services/messagemanage/messagemanage';
import styles from './ProjectManage.less';
const { Search } = Input;
const { Option } = Select;
const ProjectManage = props => {
  const history = useHistory();
  const [visibleParams, setvisibleParams] = useState({
    addVisible: false, // 新增弹窗
    delVisible: false, // 删除弹窗
    editVisible: false, // 修改弹窗
    spinLoading: false, // 加载弹窗
    pushTestVisible: false, // 推送测试弹窗
    btnLoading: false,
    loading: false,
    checkBoxLoading: false,
  });
  const [currentType, setCurrentType] = useState('全部');
  const [currentName, setCurrentName] = useState('全部');
  const [messageTypes, setMessageTypes] = useState([]);
  const [currentTemplate, setCurrentTempalte] = useState({});
  const [flag, setFlag] = useState(0);
  const [pageIndex, setPageIndex] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [dataList, setDataList] = useState([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [value, setValue] = useState('');
  const [pushTestMsg, setPushTestMsg] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const columns = [
    {
      title: '方案名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div>
          {record.type === '定时推送' ? (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Tooltip title={text}>
                <FieldTimeOutlined
                  style={{
                    fontSize: '16px',
                    color: '#1890FF',
                    marginRight: '0.1rem',
                  }}
                />
              </Tooltip>
              {searchStyle(text)}
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Tooltip title={text}>
                <AlertTwoTone style={{ fontSize: '16px', marginRight: '0.1rem' }} />
              </Tooltip>
              {searchStyle(text)}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '方案类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '推送方式',
      dataIndex: 'send_pattern',
      key: 'send_pattern',
    },
    {
      title: '推送组',
      dataIndex: 'receive_person',
      key: 'receive_person',
      ellipsis: true,
    },
    {
      title: '是否启用',
      dataIndex: 'is_use',
      key: 'is_use',
      render: (text, record) => <div>{text === '0' ? '否' : '是'}</div>,
    },
    {
      title: '操作',
      width: 250,
      ellipsis: true,
      render: (text, record) => (
        <Space>
          <Tooltip title="测试">
            <FundViewOutlined
              style={{ fontSize: '16px', color: '#1890FF' }}
              onClick={() => {
                TestDesc(record);
              }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <EditTwoTone
              style={{ fontSize: '16px', color: '#e86060' }}
              onClick={() => {
                changeDesc(record);
              }}
            />
          </Tooltip>

          {record.name != '通用报警' && record.name != '工单提醒' && record.name != '系统通知' && (
            <div onClick={e => e.stopPropagation()}>
              <Popconfirm
                title="是否删除方案？"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  DeleteProject(record);
                }}
              >
                <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
              </Popconfirm>
            </div>
          )}
        </Space>
      ),
    },
  ];

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(value, 'g'), `<span style='color:red'>${value}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  const placeholder = '请输入方案名称';
  const handleSearch = value => {
    GetMessageList({ pageSize: 10, pageIndex: 0, search: value });
    setShowSearchStyle(true);
  };
  const changeDesc = record => {
    setCurrentTempalte(record);
    history.push({
      pathname: `/platformCenter/schemeDetail`,
      state: { template: record, currentPage },
    });
    // handleShowModal("editVisible", true)
  };
  const TestDesc = record => {
    setPushTestMsg(record);
    handleShowModal('pushTestVisible', true);
  };
  const DeleteProject = record => {
    let agen = record.item.AgentConfig;
    let config = record.item.MessageConfig;
    if (agen) {
      DeleteIISAgentConfig({
        agentName: config.MsgType,
      }).then(res => {
        if (res === 0) {
          DeleteMessageConfig({
            id: config.ID,
          }).then(res3 => {
            if (res3.code === 0) {
              message.success('删除方案成功');
              setFlag(flag + 1);
            }
          });
        } else {
          message.error(res.msg);
        }
      });
    } else {
      DeleteMessageConfig({
        id: config.ID,
      }).then(res3 => {
        if (res3.code === 0) {
          message.success('删除方案成功');
          setFlag(flag + 1);
        }
      });
    }
  };
  const handleReset = () => {
    setCurrentType('全部');
    setCurrentName('全部');
    setCurrentPage(1);
    GetMessageList({ pageSize: 10, pageIndex: 0 });
    setShowSearchStyle(false);
    setValue('');
  };
  // 弹出模态框
  const handleShowModal = (key, value) => {
    setvisibleParams({ ...visibleParams, [key]: value });
  };
  const editModal = () => {
    handleShowModal('editVisbile', false);
    setFlag(flag + 1);
  };
  const bddModal = () => {
    handleShowModal('addVisbile', false);
    setFlag(flag + 1);
  };
  const pushTestModal = () => {
    handleShowModal('pushTestVisible', false);
    setFlag(flag + 1);
  };
  const onAddClick = () => {
    setCurrentTempalte({});
    // handleShowModal("addVisible", true)
    history.push({
      pathname: `/platformCenter/schemeDetail`,
      state: { template: {} },
    });
  };
  const onTypeChange = value => {
    if (value == '全部') {
      setCurrentType('全部');
      GetMessageList({ pageIndex, pageSize: 10 });
    } else {
      GetMessageList({
        pageIndex,
        pageSize: 10,
        infoType: value,
        msgType: currentName == '全部' ? '' : currentName,
      });
      setCurrentType(value);
    }
  };
  const onNameChange = value => {
    if (value == '全部') {
      setCurrentName('全部');
      GetMessageList({ pageIndex, pageSize: 10 });
    } else {
      GetMessageList({
        pageIndex,
        pageSize: 10,
        msgType: value,
        infoType: currentType == '全部' ? '' : currentType,
      });
      setCurrentName(value);
    }
  };

  useEffect(() => {
    setTreeLoading(true);

    GetMsgTypeList().then(res => {
      setTreeLoading(false);
      if (res.code === 0) {
        setMessageTypes(res.data);
      }
    });
    console.log(history.location);
    if (history.location.query) {
      setCurrentPage(history.location.query.currentPage);
    }
  }, []);
  useEffect(() => {
    GetMessageList({ pageIndex, pageSize: 10 });
  }, [flag]);

  const GetMessageList = params => {
    setTreeLoading(true);
    GetMessageConfigList(params).then(res => {
      setTreeLoading(false);
      let mesList = [];
      if (res.code === 0) {
        res.data.MessageConfigModels.map(item => {
          mesList.push({
            name: item.MessageConfig.MsgType,
            type: item.MessageConfig.ThemeName,
            send_pattern: item.MessageConfig.PushMode,
            receive_person: item.MessageConfig.PushGroup,
            is_use: item.MessageConfig.IsStarted,
            ...item.MessageConfig,
            item,
          });
        });

        setDataList(mesList);
      }
    });
  };

  const handleChange = e => {
    setValue(e.target.value);
  };

  const pagenation = {
    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: [10, 20, 50, 100],
    defaultPageSize: 10,
    showQuickJumper: true,
    showSizeChanger: true,
    current: currentPage,
    onChange: page => {
      setCurrentPage(page);
    },
  };
  return (
    <div className={styles.project_container}>
      <Spin tip="loading..." spinning={treeLoading}>
        <div className={styles.operate_bar}>
          <div className={styles.template_type}>
            <div className={styles.title}>方案类型</div>
            <Select
              placeholder="请选择方案类型!"
              value={currentType}
              style={{ width: '150px' }}
              onChange={onTypeChange}
            >
              <Option value="全部">全部</Option>
              <Option value="监控报警">监控报警</Option>
              <Option value="工单办理">工单办理</Option>
              <Option value="平台公告">平台公告</Option>
              <Option value="定时推送">定时推送</Option>
            </Select>
          </div>
          <div className={styles.template_type}>
            <div className={styles.title}>方案名称</div>
            <Select
              placeholder="请选择方案名称!"
              value={currentName}
              style={{ width: '150px' }}
              onChange={onNameChange}
            >
              <Option value="全部">全部</Option>
              {messageTypes.map((item, idx) => (
                <Option key={idx} value={item.MsgType}>
                  {item.MsgType}
                </Option>
              ))}
            </Select>
          </div>
          <div className={styles.fast_search}>
            <div className={styles.title}>快速检索</div>
            <Search
              allowClear
              placeholder={placeholder}
              onSearch={handleSearch}
              onChange={e => {
                handleChange(e);
              }}
              enterButton
              style={{ width: '300px' }}
              value={value}
            />
          </div>
          <Button type="primary" onClick={handleReset}>
            重置
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: '10px' }}
            icon={<PlusCircleOutlined />}
            onClick={onAddClick}
          >
            <span style={{ marginTop: '-3px' }}>新增</span>
          </Button>
        </div>
        <div className={styles.list_view}>
          <Table
            bordered
            columns={columns}
            dataSource={dataList}
            pagination={pagenation}
            rowKey="ID"
          />
        </div>
        <EditModal
          visible={visibleParams.editVisible}
          template={currentTemplate}
          onCancel={() => handleShowModal('editVisible', false)}
          confirmModal={editModal}
        />
        <EditModal
          visible={visibleParams.addVisible}
          template={{}}
          onCancel={() => handleShowModal('addVisible', false)}
          confirmModal={bddModal}
        />
        {/* 推送测试模块 */}
        <PushTest
          visible={visibleParams.pushTestVisible}
          onCancel={() => handleShowModal('pushTestVisible', false)}
          confirmModal={pushTestModal}
          pushTestMsg={pushTestMsg}
        />
      </Spin>
    </div>
  );
};
export default ProjectManage;
