import { notification } from 'ant-design-vue';
import { h, ref } from 'vue';
import bus from '@/utils/bus';
import router from '@/router';
import { message, Divider } from '@crami/ui';
import _store from '@/store/index';
import { useI18n } from '@crami/locale';
import UserAvatar from '@/views/platform/components/UserAvatar.vue';
import { changeRouterByMsg } from '@/views/platform/Message/utils/generateMsgContent';
import { divide } from 'lodash';

let key;

const NOTIFICATION_CLS = 'message-prompt-notification';
const BUI_CONTAINER_CLS = 'bui-assoQuery-container';
const BUI_ITEM_CLS = 'bui-assoQuery-item';

const createStyleSheet = () => {
  let style = document.createElement("style");
  // WebKit处理
  style.appendChild(document.createTextNode(""));
  style.setAttribute('type', 'text/css');
  style.setAttribute(`${NOTIFICATION_CLS}-style`, '');
  document.head.appendChild(style);

  const addCSSRule = (sheet, selector, rules, index) => sheet.insertRule ?
    sheet.insertRule(selector + "{" + rules + "}", index) :
    sheet.addRule(selector, rules, index);

  const sheet = style.sheet;
  addCSSRule(sheet, `.${NOTIFICATION_CLS}`, `border-radius: 8px`);
}

requestIdleCallback(() => {
  createStyleSheet();
})

const clickNotification = (e, result, t) => {
  notification.close(key);
  const allowRouters = _store.getters['user/allowRouters'] || [];
  // 存在消息中心导航菜单
  const messageCenter = allowRouters.find(route => route.name === 'MessageCenter');
  // 存在我收到的导航菜单
  if (
    messageCenter &&
    messageCenter?.meta?.frontHidden !== true &&
    messageCenter.children && messageCenter.children.length
  ) {
    const receivedMsgPage =  messageCenter.children.find(route => route.name === 'ReceivedMsg');
    if (receivedMsgPage && receivedMsgPage?.meta?.frontHidden !== true) {
      setTimeout(() => {
        router.push({
          path: `/platform/Message/MessageCenter/ReceivedMsg/Index`,
          query: {
            activeKey: result.msgType,
            eid: result.msgReceivedEid,
          },
        });
      }, 300);
    } else {
      message.warning(`${t('messageGlobl.notification.noAuth')}`);
    }
  } else {
    message.warning(`${t('messageGlobl.notification.noAuth')}`);
  }
}

// 获取正常的跳转部分配置
const getLinkContent = (result) => {
  let messageContentUrlJson = {};
  try {
    messageContentUrlJson = JSON.parse(result.messageContentUrl);
  } catch (e) {

  }
  return Object.values(messageContentUrlJson);
}

// 获取content里可跳转的a标签内容
const getAtagContent = ({ messageContent: content }) => {
  let result = [];
  // 测试用
  // content = "<p>当前信息：流程消息提示插件；您收到一条待办信息,请查收！，点击：<a href='http://10.0.88.239:33380/platform/workflow/myWorkflow/viewWorkflow?operationMode=need&processInstanceId=22906fd2b2f44ffebd0892b9c416d521&taskId=ae7086a1b0e349bda61308031b632ae1&processDefinitionId=fee5a95babb54d389915a4b805884255&isView=false&viewed=&EID=22906fd2b2f44ffebd0892b9c416d521&currentNodeKeys=Activity_0th4m4g&entryId=1596104410415521794&nodeType=a56123d295d' target='_blank'>办理</a></p>";
  if (!content) return result;
  
  try {
    let _dom = document.createElement('div');
    _dom.innerHTML = content;
    const aDom = _dom.querySelectorAll('a');
    if (aDom && aDom.length) {
      result = [].map.call(aDom, a => ({
        name: a.innerText,
        target: a.getAttribute('target'),
        url: a.getAttribute('href'),
      }));
    }
    _dom = null;
  } catch (err) {
    console.log(err);
  }
  return result;
}

// 业务联查部分
const renderBusiAssoQuery = (result) => {
  const messageContentItems = getLinkContent(result);
  const extraContentItems = getAtagContent(result);  
  if (!messageContentItems.length && !extraContentItems.length) return null;

  const renderItem = (item, type = 'common') => {
    const default_props = {
      class: BUI_ITEM_CLS,
      style: {
        width: '48%',
        background: '#E8F0FD',
        borderRadius: '4px',
        overflow: 'hidden',
        color: '#3979F9',
        height: '28px',
        lineHeight: '28px',
        textAlign: 'center',
        cursor: 'pointer',
        marginBottom: '12px',
      },
    }
    const extra_props = {};
    switch (type) {
      case 'a':
        default_props.onClick = (e) => {
          item.url && window.open(item.url);
          e.stopPropagation();
        };
        break;
      case 'common':
        default_props.onClick = (e) => {
          item.url && changeRouterByMsg(item);
          e.stopPropagation();
        };
        break;
      default:
        default_props.onClick = () => {};
    }

    return h('div', Object.assign({}, default_props, extra_props), item.name);
  }

  return h('div', {}, [
    h(Divider, {
      style: {
        borderColor: '#E9E9E9',
        margin: '16px 0',
      },
      dashed: true,
    }),
    h('div', {
      class: BUI_CONTAINER_CLS,
      style: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-between',
        marginBottom: '-12px',
      },
    }, [
      ...messageContentItems.map(item => renderItem(item, 'common')),
      ...extraContentItems.map(item => renderItem(item, 'a')),
    ]),
  ])
}

const notificationContent = (result, t) => h(
  'div',
  {
    fontSize: '14px',
    onClick: (e) => clickNotification(e, result, t),
  },
  [
    // 因为数据问题先不展示
    // h('div', {
    //   class: `${NOTIFICATION_CLS}-msgInfo`,
    //   style: {
    //     display: 'flex',
    //     alignItems: 'center',
    //     marginBottom: '12px'
    //   }
    // }, [
    //   h(UserAvatar, {
    //     userInfo: result,
    //     avaterField: 'sender_avatar',
    //     size: 24,
    //     style: {
    //       marginRight: '8px',
    //     }
    //   }),
    //   h('div', {
    //     style: {
    //       marginRight: '8px',
    //       color: '#666666',
    //     }
    //   }, result.senderName),
    //   h('div', {
    //     style: {
    //       fontSize: '12px',
    //       color: '#999',
    //     }
    //   }, `[${t('messageGlobl.notification.newMessage')}]`),
    // ]),
    h('div', {
      style: {
        color: '#333333',
        fontWeight: '500',
        height: '21px',
        lineHeight: '21px',
        marginBottom: '8px',
      }
    }, `${t('messageGlobl.notification.title')}: ${result?.messageTitle}`),
    h('div', {
      style: {
        color: '#666666',
        height: '21px',
        lineHeight: '21px',
      }
    }, `${t('messageGlobl.notification.abstract')}: ${result?.abstractContent}`),
    renderBusiAssoQuery(result),
  ],
)

const handleMessage = (result) => {
  bus.emit('getMessageData');
 
  const { t } = useI18n();
  key = result.messageId || `open${Date.now()}`;

  if (result.messageTitle || result.abstractContent || result.messageContent) {
    notification.open({
      message: ``,
      key,
      class: NOTIFICATION_CLS,
      description: notificationContent(result, t),
      // duration: 10000,
    });
  }
}

export default handleMessage;