import {logApi} from '@/http/logApi'
import { getBrowser } from '@/uilts/help.js';
import { logType } from './logEnum.js';


/**
 * @eventData 以键值对存储，会在最终上报里解开的参数
 * @extParams 最终上报到阿里云以json字符串存储的参数，如果extparams传入的不是obj会转换成obj
 */
export function reportLog(eventData = {}, extParams = {}) {
    if (chrome && chrome.tabs) {
        chrome.tabs.getCurrent((tab) => {
            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 { url = '' } = tab;
            let platform = isMobile ? `mobile` : `pc`;
            let browser = getBrowser();
            let extData = {
                url,
                platform,
                browser,
                ...extParams,
            }
            paramsPretreatmentAndRequest(logType.denet, eventData, extData)
        })
    } else {
        paramsPretreatmentAndRequest(logType.denet, eventData, extParams)
    }
}

function paramsPretreatmentAndRequest(logType, eventData, extParams) {
    extParams = wrapObject(extParams)
    let obj = {};
    let pageSource = eventData.pageSource;
    if(eventData.hasOwnProperty('pageSource')) {
        delete eventData.pageSource;
    }
    obj.logType = logType;
    obj.eventData = JSON.stringify(eventData)
    obj.extParams = JSON.stringify(extParams)
    logApi({params: {
        pageSource,
        ...obj
    }})
}

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

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