import axios from 'axios';
import { logType } from './enum';
import { getBrowser, getEnvConfig, getMid, getUserInfo, appVersionCode, appType } from '../utils';

const { logHost } = getEnvConfig();
const logAPIUrl = logHost + '/log-center';

export function Report(params: any) {
    let baseInfo = params.baseInfo || {}
    let {eventData = {}, extParams = {}} = params.params ||  {
        params: {}
    }
    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();
    let userInfo = getUserInfo();
    let extData = {
        url: location.href,
        browser,
        platform,
        twitterId: userInfo && userInfo.nickName || '',
        ...eventData,
    }
    eventData = wrapObject(extData)
    params.baseInfo = {
        mid: getMid(),
        machineCode: getMid(),
        loginUid: userInfo && userInfo.uid || '',
        token: userInfo && userInfo.accessToken || '',
        appType,
        appVersionCode,
        ...baseInfo,
    }
    params.params.logType = logType.denet;
    params.params.eventData = JSON.stringify(eventData)
    params.params.extParams  = JSON.stringify(extParams)
    
    axios.post(`${logAPIUrl}/statistics/uploadLogFromFrontend`, params)
}

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

function typeDecide(o: any, type: string) {
    return Object.prototype.toString.call(o) === `[object ${type}]`;
}