/* eslint-disable array-callback-return */
/* eslint-disable eqeqeq */
/* eslint-disable no-shadow */
/* eslint-disable spaced-comment */
/* eslint-disable import/first */
import React, { useEffect, useState } from 'react';
import {
  // Tree,
  Table,
  Space,
  Input,
  Button,
  Select,
  Popconfirm,
  message,
  Tooltip,
  notification,
  Spin,
} from 'antd';
import { PlusCircleOutlined, EditTwoTone, DeleteOutlined } from '@ant-design/icons';

const { Search } = Input;
const { Option } = Select;
import EditModal from './components/EditModal';
import AddModal from './components/AddModal';
import {
  GetMessageTemplate,
  UpdateMessageTemplate,
  DeleteMessageTemplate,
  InsertMessageTemplate,
  GetThirdpartyTemplates,
} from '@/services/messagemanage/messagemanage';
import styles from './TemplateManage.less';

const TemplateManage = () => {
  const [visibleParams, setvisibleParams] = useState({
    addVisible: false, // 新增弹窗
    delVisible: false, // 删除弹窗
    editVisible: false, // 修改弹窗
    spinLoading: false, // 加载弹窗
    btnLoading: false,
    loading: false,
    checkBoxLoading: false,
  });
  const [currentTemplate, setCurrentTempalte] = useState({});
  const [data, setData] = useState([]);
  const [flag, setFlag] = useState(0);
  const [option, setOption] = useState([]); // 下拉列表数据
  const [treeLoading, setTreeLoading] = useState(false);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [value, setValue] = useState('');
  const [currentType, setCurrentType] = useState('全部');

  useEffect(() => {
    getTemplateList();
    selectFocus();
  }, [flag]);

  const getTemplateList = obj => {
    setTreeLoading(true);
    GetMessageTemplate(obj)
      .then(res => {
        setTreeLoading(false);
        let list = [];
        if (res.code === 0) {
          res.data.map((item, index) => {
            list.push({
              key: item.Id,
              Id: item.Id,
              name: item.LikeName,
              type: item.Type,
              third_name: item.Name,
              third_id: item.No,
              template_params2: item.ParsingParams, //模板参数2.0
              template_params1: item.TParameters, //模板参数1.0
              analysis_params: item.ParsingRules, //模板解析
              desc: item.ParsingDescription, //模板参数说明
              weixin: item.WorkWeiXinId, //企业微信ID
            });
          });
          setData(list);
        }
      })
      .catch(e => {
        setTreeLoading(false);
      });
  };

  const selectFocus = obj => {
    GetThirdpartyTemplates(obj)
      .then(res => {
        if (res.msg === 'Ok') {
          console.log(res.data);
          setOption(res.data);
        } else {
          notification.error({
            message: '提示',
            duration: 15,
            description: res.message,
          });
        }
      })
      .catch(err => {
        console.error(err);
      });
  };

  const columns = [
    {
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
      align: 'center',
      width: 80,
      render: text => <a>{text}</a>,
    },
    {
      title: '模板名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: item => searchStyle(item),
    },
    {
      title: '模板类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
    },
    {
      title: '第三方模板名称',
      dataIndex: 'third_name',
      key: 'third_name',
      align: 'center',
    },
    {
      title: '企业微信ID',
      dataIndex: 'weixin',
      key: 'weixin',
      align: 'center',
    },
    {
      title: '第三方模版编号',
      dataIndex: 'third_id',
      key: 'third_id',
      align: 'center',
      width: 150,
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: record => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '模板参数',
      dataIndex: 'template_params1',
      key: 'template_params1',
      align: 'center',
    },
    {
      title: '解析参数',
      dataIndex: 'template_params2',
      key: 'template_params2',
      align: 'center',
    },
    {
      title: '模板参数说明',
      dataIndex: 'desc',
      key: 'desc',
      align: 'center',
    },
    {
      title: '解析规则',
      dataIndex: 'analysis_params',
      key: 'analysis_params',
      align: 'center',
      width: 150,
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: record => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: 150,
      ellipsis: true,
      render: (text, record) => (
        <Space>
          <Tooltip title="编辑">
            <EditTwoTone
              type="primary"
              size="small"
              onClick={() => {
                changeDesc(record);
              }}
              style={{ fontSize: '16px' }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <div onClick={e => e.stopPropagation()}>
              <Popconfirm
                placement="bottomRight"
                title="是否删除该模板？"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  delTemplate(record);
                }}
              >
                <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
              </Popconfirm>
            </div>
          </Tooltip>
        </Space>
      ),
    },
  ];

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

  const placeholder = '请输入模板名称';
  const handleSearch = value => {
    setValue(value);
    if (currentType == '全部') {
      getTemplateList({ queryInfo: value });
    } else {
      getTemplateList({ queryInfo: value, tempType: currentType });
    }
    setShowSearchStyle(true);
  };
  const handleReset = () => {
    setCurrentType('全部');
    getTemplateList();
    setValue('');
    setShowSearchStyle(false);
  };
  const handleChange = e => {
    setValue(e.target.value);
  };
  const handleSelectType = value => {
    if (value === '全部') {
      setCurrentType('全部');
      getTemplateList();
    } else {
      getTemplateList({ tempType: value });
      setCurrentType(value);
    }
  };
  const changeDesc = record => {
    setCurrentTempalte(record);
    handleShowModal('editVisible', true);
  };
  const AddTemplate = () => {
    handleShowModal('addVisible', true);
  };
  const delTemplate = record => {
    DeleteMessageTemplate({
      id: record.Id,
    }).then(res => {
      if (res.code === 0) {
        message.success('模板删除成功!');
        setFlag(flag + 1);
      } else {
        message.warn('模板删除失败!');
      }
    });
  };
  // 弹出模态框
  const handleShowModal = (key, value) => {
    setvisibleParams({ ...visibleParams, [key]: value });
  };
  //编辑
  const editModal = () => {
    handleShowModal('editVisible', false);
  };
  const onSubmit = result => {
    if (result.type == '企业微信') {
      UpdateMessageTemplate({
        Id: result.Id,
        Type: result.type,
        LikeName: result.name,
        Name: result.third_name,
        ParsingRules: result.analysis_params,
        ParsingDescription: result.desc,
        TParameters: result.params,
        ParsingParams: result.param1,
        WorkWeiXinId: result.weixin,
      }).then(res => {
        if (res.code === 0) {
          message.success('模板保存成功！');
          handleShowModal('editVisible', false);
          setFlag(flag + 1);
        } else {
          message.warn('模板保存失败！');
        }
      });
    } else {
      UpdateMessageTemplate({
        Id: result.Id,
        Type: result.type,
        LikeName: result.name,
        Name: result.third_name,
        No: result.third_id,
        ParsingRules: result.analysis_params,
        ParsingDescription: result.desc,
        TParameters: result.params,
        ParsingParams: result.param1,
      }).then(res => {
        if (res.code === 0) {
          message.success('模板保存成功！');
          handleShowModal('editVisible', false);
          setFlag(flag + 1);
        } else {
          message.warn('模板保存失败！');
        }
      });
    }
  };
  //新增
  const addModal = () => {
    handleShowModal('editVisible', false);
  };
  const onAddSubmit = result => {
    if (result.type == '企业微信') {
      InsertMessageTemplate({
        Type: result.type,
        LikeName: result.name,
        Name: result.third_name,
        ParsingRules: result.analysis_params,
        ParsingDescription: result.desc,
        TParameters: result.params,
        ParsingParams: result.param1,
        WorkWeiXinId: result.weixin,
      }).then(res => {
        if (res.code === 0) {
          message.success('模板添加成功！');
          handleShowModal('addVisible', false);
          setFlag(flag + 1);
        } else {
          message.warn('模板添加失败！');
        }
      });
    } else {
      InsertMessageTemplate({
        Type: result.type,
        LikeName: result.name,
        Name: result.third_name,
        No: result.third_id,
        ParsingRules: result.analysis_params,
        ParsingDescription: result.desc,
        TParameters: result.params,
        ParsingParams: result.param1,
      }).then(res => {
        if (res.code === 0) {
          message.success('模板添加成功！');
          handleShowModal('addVisible', false);
          setFlag(flag + 1);
        } else {
          message.warn('模板添加失败！');
        }
      });
    }
  };

  const pagenation = {
    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: [10, 20, 50, 100],
    defaultPageSize: '10',
    showQuickJumper: true,
    showSizeChanger: true,
  };
  return (
    <div className={styles.template_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={handleSelectType}
              className={styles.select}
            >
              <Option value="全部">全部</Option>
              <Option value="公众号">公众号</Option>
              <Option value="短信">短信</Option>
              <Option value="APP">APP</Option>
              <Option value="WEB">WEB</Option>
              <Option value="企业微信">企业微信</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 style={{ verticalAlign: 'middle' }} />}
            onClick={AddTemplate}
          >
            <span style={{ marginTop: '-3px' }}>新增</span>
          </Button>
        </div>
        <div className={styles.list_view}>
          <Table
            columns={columns}
            dataSource={data}
            bordered
            pagination={pagenation}
            scroll={{ y: '500px' }}
          />
        </div>
        <EditModal
          visible={visibleParams.editVisible}
          template={currentTemplate}
          onCancel={() => handleShowModal('editVisible', false)}
          option={option}
          confirmModal={editModal}
          onSubmit={onSubmit}
        />
        <AddModal
          visible={visibleParams.addVisible}
          template={currentTemplate}
          onCancel={() => handleShowModal('addVisible', false)}
          option={option}
          confirmModal={addModal}
          onSubmit={onAddSubmit}
        />
      </Spin>
    </div>
  );
};
export default TemplateManage;
