/* 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,
  notification,
  Tag,
} 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 [nameList, setNameList] = useState([]);
  const columns = [
    {
      title: '方案名称',
      dataIndex: 'name',
      align: 'center',
      key: 'name',
      render: (text, record) => (
        <div>
          {record.type === '定时推送' ? (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Tooltip title={text}>
                <FieldTimeOutlined
                  style={{
                    fontSize: '16px',
                    color: '#1890FF',
                    marginRight: '0.1rem',
                  }}
                />
              </Tooltip>
              {searchStyle(text)}
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Tooltip title={text}>
                <AlertTwoTone style={{ fontSize: '16px', marginRight: '0.1rem' }} />
              </Tooltip>
              {searchStyle(text)}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '消息标题',
      dataIndex: 'Title',
      align: 'center',
      key: 'Title',
      render: (text, record) => <div>{text === null || !text ? '-' : text}</div>,
    },
    {
      title: '方案类型',
      dataIndex: 'type',
      align: 'center',
      key: 'type',
      width: 200,
      render: (text, record) => <div>{text === null || !text ? '-' : text}</div>,
    },
    {
      title: '推送方式',
      dataIndex: 'send_pattern',
      key: 'send_pattern',
      align: 'center',
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: (text, record) => {
        console.log(text);
        let arr = text;
        if (text) {
          let list = new Set(text.split(','));
          console.log(list);
          let data = Array.from(list); // 将类数组转化为真数组
          console.log(data);
          arr = data.toString();
        }
        return (
          <span>
            {arr === null || !arr ? (
              '-'
            ) : (
              <Tooltip placement="topLeft" title={arr}>
                {arr}
              </Tooltip>
            )}
          </span>
        );
      },
    },
    // {
    //   title: '推送组',
    //   dataIndex: 'receive_person',
    //   key: 'receive_person',
    //   align: 'center',
    //   ellipsis: true,
    //   onCell: () => ({
    //     style: {
    //       maxWidth: 150,
    //       overflow: 'hidden',
    //       whiteSpace: 'nowrap',
    //       textOverflow: 'ellipsis',
    //       cursor: 'pointer',
    //     },
    //   }),
    //   render: (text, record) => (
    //     <span>
    //       {text === null || !text ? (
    //         '-'
    //       ) : (
    //         <Tooltip placement="topLeft" title={text}>
    //           {text}
    //         </Tooltip>
    //       )}
    //     </span>
    //   ),
    // },
    {
      title: '是否启用',
      dataIndex: 'is_use',
      align: 'center',
      key: 'is_use',
      width: '100px',
      // render: (text, record) => <div>{text === '0' ? '否' : '是'}</div>,
      render: record => {
        if (record === '1') {
          return <Tag color="success">是</Tag>;
        } else if (record === '是') {
          return <Tag color="success">是</Tag>;
        } else if (record === '否') {
          return <Tag color="processing">否</Tag>;
        }
        return <Tag color="processing">否</Tag>;
      },
    },
    {
      title: '操作',
      width: 250,
      align: 'center',
      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) {
      const escapedSearchValue = value.replace(/\\/g, '\\\\');
      const regex = new RegExp(escapedSearchValue, 'g');
      n = val.replace(
        regex,
        `<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,
      infoType: currentType == '全部' ? '' : currentType,
      msgType: currentName == '全部' ? '' : currentName,
    });
    setShowSearchStyle(true);
  };
  const changeDesc = record => {
    console.log(record);
    setCurrentTempalte(record);
    history.push({
      pathname: `/platform/schemeDetail`,
      state: { template: record, currentPage, nameList },
    });
    // 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: `/platform/schemeDetail`,
      state: { template: {}, nameList },
    });
  };
  const onTypeChange = value => {
    if (value == '全部') {
      setCurrentType('全部');
      GetMessageList({
        pageIndex,
        pageSize: 10,
        infoType: '',
        msgType: currentName == '全部' ? '' : currentName,
      });
    } else {
      GetMessageList({
        pageIndex,
        pageSize: 10,
        infoType: value,
        msgType: currentName == '全部' ? '' : currentName,
      });
      setCurrentType(value);
    }
  };
  const onNameChange = value => {
    if (value == '全部') {
      setCurrentName('全部');
      GetMessageList({
        pageIndex,
        pageSize: 10,
        msgType: '',
        infoType: currentType == '全部' ? '' : currentType,
      });
    } 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);
      if (res.code === 0) {
        console.log(res.data);
        let mesList = [];
        let nameArr = [];
        if (res.code === 0) {
          res.data.MessageConfigModels.map(item => {
            nameArr.push(item.MessageConfig.MsgType);
            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,
            });
          });
          setNameList(nameArr);
          setDataList(mesList);
        }
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  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>
              <Option value="平台公告">平台公告</Option>
            </Select>
          </div>
          <div className={styles.template_type}>
            {/* <div className={styles.title}>方案名称</div>
            <Select
              placeholder="请选择方案名称!"
              value={currentName}
              style={{ width: '150px' }}
              onChange={onNameChange}
              showSearch
            >
              <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
              showSearch
              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;