/* eslint-disable func-names */
/* eslint-disable no-else-return */
/* eslint-disable no-unneeded-ternary */
import React, { useState, useEffect, useRef } from 'react';
import {
  Input,
  Table,
  Button,
  notification,
  message,
  Tooltip,
  Tag,
  Modal,
  Popconfirm,
  Space,
  Switch,
  Select,
} from 'antd';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  CalendarOutlined,
  ZoomInOutlined,
} from '@ant-design/icons';
import 'moment/dist/locale/zh-cn';
import { FixedSizeList as List } from 'react-window';
import styles from './index.less';
import {
  GetIISAgentConfig,
  DeleteIISAgentConfig,
  AddIISAgentConfig,
  GetIISAgentLog,
} from '@/services/scheduledTasks/api';
import AddModal from './components/AddModal';
import LookModal from './components/LookModal';
import PushTest from './components/PushTest/PushTest';
// import logWorker from './components/logWorker';

const { Option } = Select;
let timer = null;
const ScheduledTasks = () => {
  const [loading, setLoading] = useState(false); // 源数据
  const [requestUrl, setRequestUrl] = useState(''); // 接口名称筛选
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [keepTableList, setKeepTableList] = useState([]);
  const [addVisible, setAddVisible] = useState(false);
  const [lookVisible, setLookVisible] = useState(false);
  const [type, setType] = useState('');
  const [recordItem, setRecordItem] = useState();
  const [pushTestVisible, setPushTestVisible] = useState(false);
  const typeValue = useRef('重复执行');
  const [columnsData, setColumnsData] = useState([]);
  const scroll = useRef();
  const listRef = useRef();
  const [logList, setLogList] = useState([]);
  const keepLength = useRef(0);
  const [loadingLog, setLoadingLog] = useState(false);

  const columns = [
    {
      title: '计划名称',
      dataIndex: 'Name',
      key: 'Name',
      width: 300,
      fixed: 'left',
      onCell: () => ({
        style: {
          maxWidth: 300,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: text => <Tooltip title={text}>{searchStyle(text)}</Tooltip>,
    },
    {
      title: '计划类型',
      dataIndex: 'LoopMode',
      key: 'LoopMode',
      align: 'center',
      width: 200,
      render: text => {
        if (text === 'ByOnce') {
          return <span>执行一次</span>;
        } else {
          return <span>重复执行</span>;
        }
      },
    },
    {
      title: '执行方式',
      dataIndex: 'LoopMode',
      key: 'LoopMode',
      align: 'center',
      width: 150,
      render: text => {
        if (text === 'ByLoop') {
          return <Tag color="purple">循环</Tag>;
        } else if (text === 'ByDay') {
          return <Tag color="cyan">每天</Tag>;
        } else if (text === 'ByWeek') {
          return <Tag color="volcano">每周</Tag>;
        }
      },
    },
    {
      title: '计划开始时间',
      dataIndex: 'StartFrom',
      key: 'StartFrom',
      align: 'center',
      width: 300,
    },
    {
      title: '计划结束时间',
      dataIndex: 'EndAt',
      key: 'EndAt',
      align: 'center',
      width: 300,
    },
    {
      title: '是否启用',
      dataIndex: 'Enabled',
      key: 'Enabled',
      align: 'center',
      width: 150,
      render: (text, record) => {
        if (text === false) {
          return <Tag color="blue">否</Tag>;
        } else if (text === true) {
          return <Tag color="green">是</Tag>;
        }
        // return (
        //   <Switch
        //     checkedChildren="开启"
        //     unCheckedChildren="关闭"
        //     onChange={e => changeSwitch(e, record)}
        //     checked={text}
        //   />
        // );
      },
    },
    {
      title: '操作',
      width: 150,
      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={() => {
                editData(record);
              }}
            />
          </Tooltip>
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除方案？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                deleteData(record);
              }}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getTableList();
    setColumnsData(columns);
    getIISAgentLog();
    // updateInfo();
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, []);

  // const updateInfo = () => {
  //   let worker = new Worker('logWorker');
  //   debugger;
  //   worker.onmessage = m => {
  //     debugger;
  //     console.log(m);
  //   };
  //   debugger;
  //   worker.postMessage('123');
  // };

  // updateInfo(payload={}){
  //   debugger
  //   this._updateInfo(payload);
  //   let worker = new Worker(worker, {name: 'myWorker'});
  //   const {pressions} = payload;
  //   worker.onmessage = (event) =>{
  //     debugger
  //     const { routeMap={}, codeMap = {}} = event.data;
  //     console.log(routeMap, "routeMap", event.data);
  //     this.updateRouteMap(routeMap);
  //     this.updateCodeMap(codeMap);
  //     worker.terminate();
  //   }
  //   if(pressions&&pressions.length>0){
  //     debugger
  //     worker.postMessage(pressions);
  //   }
  // }

  const getIISAgentLog = () => {
    if (loadingLog) {
      return;
    }
    setLoadingLog(true);
    GetIISAgentLog().then(res => {
      setLoadingLog(false);
      if (res.code === 0) {
        let arr = [];
        let list = res.data
          .split(/(\r\n)|(\n)/)
          .filter(item => item !== '\r\n' && item !== undefined);
        arr = list
          .map((item, index) => {
            let mes = item?.indexOf('[信息]');
            let warn = item?.indexOf('[警告]');
            if (mes !== -1) {
              return (
                <div
                  style={{ color: 'aqua' }}
                  key={index}
                  dangerouslySetInnerHTML={{ __html: item }}
                />
              );
            } else if (warn !== -1) {
              return (
                <div
                  style={{ color: 'yellow' }}
                  key={index}
                  dangerouslySetInnerHTML={{ __html: item }}
                />
              );
            } else {
              if (!item) {
                return null;
              }
              return <div key={index} dangerouslySetInnerHTML={{ __html: item }} />;
            }
          })
          .filter(item => item !== null);
        if (keepLength.current !== list.length) {
          setLogList(arr);
          listRef.current.scrollTo((arr.length - 1) * 22);
        }
        keepLength.current = list.length;
        scroll.current.scrollTop = scroll.current.scrollHeight;
        timer = setTimeout(() => {
          getIISAgentLog();
        }, 2000);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
        clearInterval(timer);
        timer = null;
      }
    });
  };

  const getTableList = (search, planType) => {
    let newSearch = search ? search : requestUrl;
    let newType = planType ? planType : typeValue.current;
    setLoading(true);
    GetIISAgentConfig({ agentName: newSearch }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        let newData = [];
        if (newType === '重复执行') {
          newData = res.data.filter(i => i.LoopMode !== 'ByOnce');
        } else {
          newData = res.data.filter(i => i.LoopMode === 'ByOnce');
        }
        setKeepTableList(newData);
      } else {
        setKeepTableList([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const TestDesc = val => {
    setRecordItem(val);
    setPushTestVisible(true);
  };

  const editData = val => {
    setType('edit');
    setRecordItem(val);
    setAddVisible(true);
  };

  const deleteData = val => {
    DeleteIISAgentConfig({ agentName: val.Name }).then(res => {
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        getTableList();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

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

  const handleAdd = () => {
    setType('add');
    setAddVisible(true);
  };

  const handleLook = () => {
    setLookVisible(true);
  };

  const onOk = val => {
    changeTable(val);
    typeValue.current = val;
    getTableList('', val);
  };

  const changeTable = e => {
    if (e === '执行一次') {
      let newColumns = columns;
      let data = newColumns.filter(i => i.title !== '执行方式');
      setColumnsData(data);
    } else {
      setColumnsData(columns);
    }
  };

  const Row = ({ index, style }) => {
    return <div style={style}>{logList[index]}</div>;
  };

  return (
    <div className={styles.scheduledTasks}>
      <div className={styles.head}>
        <div className={styles.headLeft}>
          <span style={{ marginLeft: '5px' }}>计划类型：</span>
          <Select
            placeholder="请选择计划类型"
            style={{ width: '155px' }}
            value={typeValue.current}
            onChange={e => {
              changeTable(e);
              typeValue.current = e;
              getTableList('', e);
            }}
          >
            <Option value="重复执行">重复执行</Option>
            <Option value="执行一次">执行一次</Option>
          </Select>
          <span style={{ marginLeft: '15px' }}>计划名称：</span>
          <Input.Search
            style={{ width: '250px' }}
            placeholder="请输入计划名称"
            onChange={e => {
              setRequestUrl(e.target.value);
            }}
            onSearch={e => {
              getTableList(e);
              setShowSearchStyle(true);
            }}
            value={requestUrl}
          />
        </div>
        <div className={styles.headRight}>
          <Button
            icon={<ZoomInOutlined className={styles.icon} />}
            onClick={handleLook}
            style={{
              marginLeft: '25px',
              verticalAlign: 'middle',
              marginTop: '-3px',
            }}
          >
            调用日志
          </Button>
          <Button
            icon={<PlusOutlined className={styles.icon} />}
            type="primary"
            onClick={handleAdd}
            style={{
              marginLeft: '25px',
              verticalAlign: 'middle',
              marginTop: '-3px',
            }}
          >
            新增
          </Button>
        </div>
      </div>
      <div className={styles.table}>
        <Table
          size="small"
          bordered
          columns={columnsData}
          dataSource={keepTableList}
          onRow={record => ({
            onDoubleClick: event => {
              event.stopPropagation();
              editData(record);
            }, // 双击
          })}
          scroll={{ y: 'calc(100% - 40px)' }}
          pagination={false}
          loading={loading}
        />
      </div>
      <div className={styles.footer}>
        <CalendarOutlined style={{ color: '#1685ff' }} />
        <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>运行日志</span>
        <div className={styles.runLog} ref={scroll}>
          <List
            ref={listRef}
            height={284} // 这里设置列表的高度
            itemCount={logList.length}
            itemSize={22} // 这里设置每个列表项的高度
          >
            {Row}
          </List>
          <div className={styles.blinkingCursor}>|</div>
        </div>
      </div>
      <AddModal
        visible={addVisible}
        onCancel={() => setAddVisible(false)}
        submitCallback={onOk}
        type={type}
        record={recordItem}
      />
      <LookModal
        visible={lookVisible}
        onCancel={() => setLookVisible(false)}
        keepTableList={keepTableList}
      />
      <PushTest
        visible={pushTestVisible}
        onCancel={() => setPushTestVisible(false)}
        pushTestMsg={recordItem}
      />
    </div>
  );
};
export default ScheduledTasks;
