import React from 'react';
import SockJS from 'sockjs-client';
import { notification, Row, Icon, Modal } from 'antd';
import { config, dataUtils } from '../../utils';
import { default as logger } from '../../utils/logger';
import styles from '@routes/message/notification/index.less'
import * as notifyService from '@services/message/notification';

const { api, baseURL } = config;

const handleClick = (msg) => {
  const { id, type, createTime, payload } = msg;
  const sendTime = dataUtils.dtm(createTime);
  Modal.info({
    width: '50%',
    maskClosable: true,
    iconType: 'exclamation-circle',
    okText: '关闭',
    content: <div>
      <Row type="flex" justify="start" className={styles.header}>
        <div className={styles.msgSubject}>
          <div dangerouslySetInnerHTML={{ __html: payload.subject }} />
        </div>
      </Row>
      <Row type="flex" justify="start">
        <div className={styles.msgSendTime}>
          <Icon type="clock-circle-o" className={styles.msgClock} />
          <span className={styles.msgTimeContent}>{sendTime}</span>
        </div>
      </Row>
      <Row type="flex" justify="start">
        <div className={styles.msgContent}>
          <div dangerouslySetInnerHTML={{ __html: payload.content }} />
        </div>
      </Row>
    </div>
  });
  notification.close(id); // 关闭推送消息
  notifyService.getSingle({ id, type }) // 调用消息接口，将消息置为`已阅`
}

// console.log(`${baseURL}${api.basic.socket}`);

export function close(socket) {
  socket.close();
}

export function listen(actionReducer) {
  // console.log(actionReducer);
  let socket;
  // console.log(socket);
  if (socket === undefined) {
    try {
      socket = new SockJS(`${baseURL}${api.basic.socket}`);
      // actionReducer({
      //   type: 'connect',
      //   state: 'success',
      // });
    } catch (err) {
      // actionReducer({
      //   type: 'connect',
      //   state: 'fail',
      // });
    }
  }

  socket.onopen = (e) => {
    logger.network(`[WS] [OPENED]`);
    actionReducer({
      type: 'opened',
    });
  };

  socket.onclose = (e) => {
    logger.network(`[WS] [CLOSED]`);
    actionReducer({
      type: 'closed',
    });
  };

  socket.onmessage = (e) => {
    // console.log(e);
    const msg = JSON.parse(e.data);
    const payload = msg.payload;
    // console.log(msg);
    // console.log(payload);
    logger.network(`[WS] [MSG]`, msg);

    switch (msg.type) {
      case 'INBOX_STAT': {
        actionReducer({
          type: 'msgCnt',
          payload: {
            warn: payload.INBOX_WARN || 0,
            info: payload.INBOX_INFO || 0,
            todo: payload.INBOX_TODO || 0,
          },
        });
        break;
      }
      case 'INBOX_MINUS': {
        actionReducer({
          type: 'updateMsgCnt',
          payload: {
            type: 'todo',
            mode: 'minus'
          }
        });
        break;
      }

      default: {
        notification.warning({
          style: {
            border: '1px solid #ffe58f',
            backgroundColor: '#fffbe6',
          },
          key: msg.id,
          message: <a onClick={() => handleClick(msg)}>{payload.subject}</a>,
          description: <a onClick={() => handleClick(msg)}>请点击查看消息内容</a>,
          // description: payload.content.slice(0, 15) || '点击查看消息内容',
          duration: null,
        });

        // Update count
        actionReducer({
          type: 'updateMsgCnt',
          payload: {
            type: msg.type === 'INBOX_TODO' ? 'todo' : 'info',
            mode: 'add'
          }
        });

        break;

      }
    }

  };

  return socket;
}
