import { logApi, reportFrontLogApi } from '@/http/logApi'
import { getBrowser } from '@/uilts/help.js';
import { logType } from './logEnum.js';
import { getChromeStorageFromExtension } from '@/uilts/chromeExtension'
let userInfo = null;
let mid = '';
/**
 * @eventData 以键值对存储，会在最终上报里解开的参数
 * @extParams 最终上报到阿里云以json字符串存储的参数，如果extparams传入的不是obj会转换成obj
 */
export async function reportLog(eventData = {}, extParams = {}) {
    // 过滤空值
    let dataKey = Object.keys(eventData);
    dataKey.forEach(key => {
        if (eventData[key] === '') {
            delete eventData[key]
        }
    })
    // 2.reportLog 异常 存储到本地，再上报
    try {
        if (!userInfo) {
            userInfo = await getChromeStorageFromExtension('userInfo').catch((error) => {console.log(error) }) || null;
        }
        if (!mid) {
            mid = await getChromeStorageFromExtension('mid').catch((error) => {console.log(error) }) || '';
        }
        let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
        let platform = isMobile ? `mobile` : `pc`;
        let browser = getBrowser();
        if (chrome && chrome.tabs) {
            chrome.tabs.getCurrent((tab) => {
                if (tab && tab.url) {
                    let { url = '' } = tab;
                    let extData = {
                        url,
                        platform,
                        browser,
                        twitterId: userInfo && userInfo.nickName || '',
                        ...eventData,
                    }
                    paramsPretreatmentAndRequest(logType.denet, extData, extParams)
                } else {
                    let extData = {
                        platform,
                        browser,
                        twitterId: userInfo && userInfo.nickName || '',
                        ...eventData,
                    }
                    paramsPretreatmentAndRequest(logType.denet, extData, extParams)
                }
            })
        } else {
            paramsPretreatmentAndRequest(logType.denet, eventData, extParams)
        }
    } catch (error) {
        reportFrontLogApi({
            logData: JSON.stringify({
                funcName: 'reportLog',
                errmsg: error.message
            })
        })
    }
}

function paramsPretreatmentAndRequest(logType, eventData, extParams) {
    extParams = wrapObject(extParams)
    let obj = {};
    let pageSource = eventData.pageSource;
    if (eventData.pageSource) {
        delete eventData.pageSource;
    }
    obj.logType = logType;
    obj.eventData = JSON.stringify(eventData)
    obj.extParams = JSON.stringify(extParams)
    logApi({
        params: {
            pageSource,
            ...obj
        }
    }).then(() => {
    }).catch(err => {
        reportFrontLogApi({
            logData: JSON.stringify(err)
        })
    })
}

function wrapObject(extParams) {
    if (typeDecide(extParams, 'Object')) {
        return extParams
    }
    return { 'defaultExt': extParams }
}

/**
 * 检测对象类型
 */
function typeDecide(o, type) {
    return Object.prototype.toString.call(o) === `[object ${type}]`;
}

export async function getReportCommonParams () {
  let commonParams = {};
  if (!userInfo) {
      userInfo = await getChromeStorageFromExtension('userInfo') || null;
  }
  let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
  let platform = isMobile ? `mobile` : `pc`;

  if (chrome && chrome.tabs) {
      let tab = await chrome.tabs.getCurrent();
      commonParams = {
          url: tab && tab.url ? tab.url : '',
          platform,
          browser: getBrowser(),
          twitterId: userInfo && userInfo.nickName || '',
      }
  }
  return commonParams;
}
