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

export const logApi = {
	prod: 'https://log.denetme.net',
	pre: 'https://prelog.denetme.net',
	test: 'https://testlog.denetme.net',
};

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

/**
 * @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,
		refer: document ? document.referrer : '',
		...eventData,
	};
	eventData = wrapObject(extData);
	params.params.logType = logType;

	detectExtension(denetExtensionId, (isInstall) => {
		eventData.isExtensionInstalled = isInstall ? 1 : 0;
		params.params.eventData = JSON.stringify(eventData);
		params.params.extParams = JSON.stringify(extParams);
		axios.post(`${logAPIUrl}/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}]`;
}
