import { useHttp } from '@crami/http';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
// 模块联邦：替换成远程加载
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
import { notification } from 'ant-design-vue';
import { h, ref } from 'vue';
import { UserOutlined } from '@ant-design/icons-vue';
/* import bus from '@/utils/bus'; */
import router from '@/router';
import { message } from '@crami/ui';

let socket = null;
const messageUrl = ref();
const getUrl = async () => {
  const data = await useHttp({
    url: '/api/msg/serverUrl/getWebsocketServerUrl',
    method: 'get',
  });
  if (data.code === 200) {
    return data.data;
  } else {
    return false;
  }
};
//处理消息弹窗内容，返回innerhtml
const handleMessageData = (messageContentParams, messageContentUrlParams) => {
  let messageContent = messageContentParams;
  const messageUrl = JSON.parse(messageContentUrlParams);
  for (const i in messageUrl) {
    const reg = new RegExp(`\%${i}\%`, 'g');
    messageContent = messageContent.replace(
      reg,
      `<a href='javascript:void(0)' onclick="aClic('` +
        messageUrl[i].name +
        `')">` +
        messageUrl[i].name +
        `</a>`,
    );
  }
  window.aClic = aClic;
  return messageContent;
};
const aClic = e => {
  for (const i in messageUrl.value) {
    if (messageUrl.value[i].name == e) {
      router.push({
        path: messageUrl.value[i].url,
        query: {
          key: JSON.stringify(messageUrl.value[i].params),
        },
      });
    }
  }
};
const setSocket = async (opts = {}) => {
  const router = opts.router;
  const userInfo = getInfo(ICP_CONFIG);
  const socketUrl = await getUrl();
  if (!userInfo || !socketUrl) return;
  const URL = `${socketUrl}${userInfo.user_id}`;
  socket = new WebSocket(URL);
  socket.addEventListener('message', event => {
    const { data } = event;
    bus.emit('getMessageData');
    let result: Record<string, any> = {};
    try {
      result = JSON.parse(data);
    } catch (e) {
      // TODO
    }
    const key = result.messageId || `open${Date.now()}`;
    if (result.messageTitle || result.abstractContent || result.messageContent) {
      //0830 处理content数据
      const messageContentData = handleMessageData(result.messageContent, result.messageContentUrl);
      messageUrl.value = JSON.parse(result.messageContentUrl);
      notification.open({
        message: ``,
        key,
        description: h(
          'div',
          {
            fontSize: '14px',
            fontWeight: '900',
            onClick: e => {
              if (e.target.nodeName !== 'A') {
                notification.close(key);
                const list = window.sessionStorage.getItem('HomeAdminRouter');
                const routerMenu = list ? JSON.parse(list) : [];
                // 存在消息中心导航菜单
                const messageCenter = routerMenu.find(route => route.name === 'MessageCenter');
                // 存在我收到的导航菜单
                if (
                  messageCenter &&
                  (messageCenter.children || []).find(route => route.name === 'ReceivedMsg')
                ) {
                  setTimeout(() => {
                    router.push({
                      path: `/platform/Message/MessageCenter/ReceivedMsg/Index`,
                      query: {
                        activeKey: result.msgType,
                        eid: result.msgReceivedEid,
                      },
                    });
                  }, 300);
                } else {
                  message.warning(`“消息中心-我收到的”菜单未授权`);
                }
              }
            },
          },
          [
            h('div', { style: { display: 'flex', width: '100%', marginBottom: '10px' } }, [
              h(
                'div',
                {
                  style: { width: `50px`, fontSize: '30px' },
                },
                [h(UserOutlined, { style: 'color: #108ee9' })],
              ),
              h(
                'div',
                {
                  style: { width: `calc(100% - 50px)`, lineHeight: '50px' },
                },
                `[一条新消息]`,
              ),
            ]),
            h('p', { innerHTML: `标题: ${result?.messageTitle}` }),
            h('p', { innerHTML: `摘要: ${result?.abstractContent}` }),
            result.messageContent ? h('p', { innerHTML: `内容: ${messageContentData}` }) : null,
            // h('div', { style: { display: 'flex', width: '100%', marginTop: '10px' } }, [
            //   h(
            //     Button,
            //     {
            //       style: { width: `40%` },
            //       onClick: () => {
            //         console.log('业务联查1');
            //       },
            //     },
            //     `业务联查1`,
            //   ),
            //   h(
            //     Button,
            //     {
            //       style: { width: `40%` },
            //       onClick: () => {
            //         console.log('业务联查2');
            //       },
            //     },
            //     `业务联查2`,
            //   ),
            // ]),
          ],
        ),
      });
    }
  });
};
const closeSocket = async () => {
  socket.close();
};
export { setSocket, closeSocket };
