import axios from 'axios';
import { logType } from './logEnum.js';
import { getBrowser, getUserInfo, appVersionCode } from '../utils/help';

const logApi = {
	prod: 'https://log.weiqumeta.com',
	pre: 'https://prelog.weiqumeta.com',
	test: 'https://testlog.weiqumeta.com',
};

const logAPIUrl = logApi[process.env.NUXT_ENV.MODE] + '/log-center';

/**
 * @eventData 以键值对存储，会在最终上报里解开的参数
 * @extParams 最终上报到阿里云以json字符串存储的参数，如果extparams传入的不是obj会转换成obj
 */
export function reportLog(params) {
	paramsPretreatmentAndRequest(logType.denet, params);
}

function paramsPretreatmentAndRequest(logType, params) {
	let { eventData = {}, extParams = {} } = params.params || {
		params: {},
	};
	const userInfo = getUserInfo();
	if (userInfo) {
		params.baseInfo.loginUid = userInfo.uid;
	}
	params.baseInfo.appVersionCode = appVersionCode;
	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);
	params.baseInfo.appType = isMobile ? 2 : 1;
	let platform = isMobile ? `mobile` : `pc`;
	let browser = getBrowser();
	let extData = {
		url: location.href,
		browser,
		platform,
		...eventData,
	};
	eventData = wrapObject(extData);
	params.params.logType = logType;
	params.params.eventData = JSON.stringify(eventData);
	params.params.extParams = JSON.stringify(extParams);

	axios.post(`${logAPIUrl}/statistics/uploadLogFromFrontend`, params);
}

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

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