import { loadScript } from '@/utils/commons';
import { PROJECT_NAME, BUILD_VERSION } from '@/config';
import { fetchJSON } from '@/utils/request'
import { usingStorage } from "@/hooks/usingStorage";

export const sendNotify = async (message) => {

    const { userId, travelAgencyId } = usingStorage();
  const notifyUrl = 'https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/SendMDMsgByDingRobotToGroup';

  const params = {
    groupid: 'cidFtzcIzNwNoiaGU9Q795CIg==',
    msgTitle: '有人求助',
    msgText: `${message}\\n\\nID: ${userId}, ${travelAgencyId} | ${PROJECT_NAME} (${BUILD_VERSION})`,
  };

  return fetchJSON(notifyUrl, params).then((json) => {
    if (json.errcode === 0) {
      console.info('发送通知成功');
    } else {
      throw new Error(json?.errmsg + ': ' + json.errcode);
    }
  });
};

export const loadPageSpy = (title) => {

  if (import.meta.env.DEV || window.$pageSpy) return

  const PageSpyConfig = { api: 'page-spy.mycht.cn', project: PROJECT_NAME, title: title, autoRender: false };
  const PageSpySrc = [
    'https://page-spy.mycht.cn/page-spy/index.min.js'+`?${BUILD_VERSION}`,
    'https://page-spy.mycht.cn/plugin/data-harbor/index.min.js'+`?${BUILD_VERSION}`,
    'https://page-spy.mycht.cn/plugin/rrweb/index.min.js'+`?${BUILD_VERSION}`,
  ];

  Promise.all(PageSpySrc.map((src) => loadScript(src))).then(() => {
    // 注册插件
    window.$harbor = new DataHarborPlugin();
    window.$rrweb = new RRWebPlugin();
    [window.$harbor, window.$rrweb].forEach(p => {
      PageSpy.registerPlugin(p)
    })
    window.$pageSpy = new PageSpy(PageSpyConfig);

    window.onerror = async function (msg, url, lineNo, columnNo, error) {

      // 当页面有 iframe 时，rrweb 会报错：Cannot set property attributeName of #<MutationRecord> which has only a getter
      // 而且这个错误无法修复，所以只能先忽略掉
      if (url && url.indexOf('https://page-spy.mycht.cn/plugin/rrweb/index.min.js') > -1) {
        console.info('ignore rrweb error')
      } else {
        // 上传最近 3 分钟的日志
        const now = Date.now()
        await window.$harbor.uploadPeriods({
          startTime: now - 3 * 60000,
          endTime: now,
          remark: `\`onerror\`自动上传. ${msg}`,
        })
      }
    }
  });
};

export const uploadPageSpyLog = async () => {

  if (import.meta.env.DEV) return true;

  if (window.$pageSpy) {
    try {
      // await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
      // 上传最近 1 小时的日志, 直接upload 所有日志: 413 Payload Too Large
      const now = Date.now();
      await window.$harbor.uploadPeriods({
        startTime: now - 60 * 60000,
        endTime: now,
      });
      return true;
    } catch (error) {
      return false;
    }
  } else {
    return false;
  }
}

/**
 * @deprecated
 * @outdated
 */
export const PageSpyLog = () => {
  return (
    <>
      {window.$pageSpy && (
        <a
          className='text-primary'
          onClick={() => {
            window.$pageSpy.triggerPlugins('onOfflineLog', 'download');
            window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
          }}>
          上传Debug日志 ({window.$pageSpy.address.substring(0, 4)})
        </a>
      )}
    </>
  );
};
