import {
	getStorage
} from '@/utils/localStorage';
window.sessionTime = new Date();
var util = {
	reformParam(methodName, para) {
		var parameter = {}
		parameter['merchantid'] = '1'
		parameter['version'] = '1'
		parameter['sign_type'] = 'RSA'
		parameter['sign'] = '123'
		parameter['charset'] = 'UTF-8'
		parameter['method'] = methodName
		var context = ''
		for (var key in para) {
			context += '&' + key + '=' + para[key]
		}
		parameter['context'] = context
		return parameter
	},

	dateFormat(date, fmt) {
		let ret
		const opt = {
			'y+': date.getFullYear().toString(), // 年
			'M+': (date.getMonth() + 1).toString(), // 月
			'd+': date.getDate().toString(), // 日
			'H+': date.getHours().toString(), // 时
			'm+': date.getMinutes().toString(), // 分
			's+': date.getSeconds().toString(), // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		}
		for (let k in opt) {
			ret = new RegExp('(' + k + ')').exec(fmt)
			if (ret) {
				fmt = fmt.replace(
					ret[1],
					ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
				)
			}
		}
		return fmt
	},
	formatDate: function(date, fmt) {
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		let o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'h+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds()
		}
		for (let k in o) {
			if (new RegExp(`(${k})`).test(fmt)) {
				let str = o[k] + ''
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str))
			}
		}
		return fmt
	},
	padLeftZero: function(str) {
		return ('00' + str).substr(str.length)
	},
	formatDatetime(val, format) {
		const year = val.getFullYear();
		const month = val.getMonth() + 1;
		const day = val.getDate();
		const hour = val.getHours();
		const minute = val.getMinutes();
		const second = val.getSeconds();
		return year + '-' + (month > 9 ? month : '0' + month) + '-' + day + ' ' + hour + ':' + (minute > 9 ?
			minute : '0' + minute) + ':' + (second > 9 ? second : '0' + second);

	},
	formatDayTime(val) {
		const year = val.getFullYear();
		const month = val.getMonth() + 1;
		const day = val.getDate();
		const hour = val.getHours();
		const minute = val.getMinutes();
		const second = val.getSeconds();
		return year + '-' + (month > 9 ? month : '0' + month) + '-' + day + ' ' + hour + ':' + (minute > 9 ?
			minute : '0' + minute);
	},
	formatTodayTime(val) {
		const year = val.getFullYear();
		const month = val.getMonth() + 1;
		const day = val.getDate();
		const hour = val.getHours();
		const minute = val.getMinutes();

		if (month == new Date().getMonth() + 1 && day + 1 == new Date().getDate()) {
			return '昨天' + hour + ':' + (minute > 9 ? minute : '0' + minute);
		} else if (month == new Date().getMonth() + 1 && day == new Date().getDate()) {

			return hour + ':' + (minute > 9 ? minute : '0' + minute);
		} else {
			return year + '-' + (month > 9 ? month : '0' + month) + '-' + day + ' ' + hour + ':' + (minute > 9 ?
				minute : '0' + minute);
		}
	},

	/**
	 * 计算天数
	 * @param date1
	 * @param date2
	 * @returns {number}
	 * @constructor
	 */
	getNumberOfDays(date1, date2) { //获得天数
		if (!date1 || !date2) {
			return 0;
		}
		//date1：开始日期，date2结束日期
		var a1 = Date.parse(new Date(date1));
		var a2 = Date.parse(new Date(date2));
		var day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24)) + 1; //核心：时间戳相减，然后除以天数
		return day
	},

	getUrlParams(url) {
		url = url == null ? window.location.href : url;
		var search = url.substring(url.lastIndexOf("?") + 1);
		var obj = {};
		var reg = /([^?&=]+)=([^?&=]*)/g;
		// [^?&=]+表示：除了？、&、=之外的一到多个字符
		// [^?&=]*表示：除了？、&、=之外的0到多个字符（任意多个）
		search.replace(reg, function(rs, $1, $2) {
			var name = decodeURIComponent($1);
			var val = decodeURIComponent($2);
			val = String(val);
			obj[name] = val;
			return rs;
		});
		return obj;
	},
	formatTime(date) {
		var year = date.getFullYear()
		var month = date.getMonth() + 1
		var day = date.getDate()
		var hour = date.getHours()
		var minute = date.getMinutes()
		var second = date.getSeconds()
		return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this
			.formatNumber).join(
			':')
	},
	formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	},
	trackRequest(para, app = null) {
		if ((para.type && para.type.includes('Error'))) {
			//所有报错埋点以及曝光埋点不再发送至服务器
			return
		}
		try {
			var session = Number(getStorage('sessionNumber')) + 1;
			let data = {
				session: '',
				userAgent: navigator.userAgent.substring(0, 255) || '',
				browserName: navigator.appName || '',
				browserVersion: navigator.appVersion.substring(0, 255) || '',
				platform: location.href.indexOf("shareSign") > -1 ? 'h5' : 'tfb', //iframeUrl代表是顾问分享的外链
				fromPlatform: util.getUrlParams(location.href).fromPlatform || util.getUrlParams(location.href)
					.fromProduce || 'tfb',
				deviceType: '' || "",
				ip: window.ip || '',
				cookieId: from_cookie || getStorage("cookie_id") || '',
				openId: util.getUrlParams(location.href).openid,
				userId: util.getUrlParams(location.href).leavePhoneCustomerId || '',
				brandUserId: util.getUrlParams(location.href).leavePhoneCustomerId || '',
				createTime: this.formatTime(new Date()),
				uploadTime: this.formatTime(new Date()),
				product: location.href.indexOf("shareSign") > -1 ? 'h5' : 'tfb', //iframeUrl代表是顾问分享的外链
				project: para.project,
				brandId: util.getUrlParams(location.href).special_ID || util.getUrlParams(location.href)
					.brandId || null,
				// expand:typeof para.expand==='object'?JSON.stringify(para.expand):para.expand,//扩展字段
				expand: JSON.stringify(util.getUrlParams(location.href)), //扩展字段
				imTalkId: para.imTalkId || '', //IM对话编号
				imTalkType: para.imTalkType || '', //IM对话类型
				eventModuleDes: para.eventModuleDes || '', //模块描述信息
				eventInnerModuleId: para.eventInnerModuleId || '', //事件内部模块信息
				eventName: para.eventName || '', //事件名称
				eventId: para.eventId || '', //埋点ID
				adviserId: para.adviserId || '', //顾问id
				clkDesPage: para.clkDesPage || '', //点击前往的页面名称
				clkId: para.clkId || '', //点击ID
				clkName: para.clkName || '',
				pvId: para.pvId || '', //PV埋点ID
				clkParams: typeof para.clkParams === 'object' ? JSON.stringify(para.clkParams) : para
				.clkParams, //点击参数
				pvPageStayTime: para.pvPageStayTime || '',
				pvCurPageName: para.pvCurPageName || '', //当前页面名称
				pvCurPageParams: typeof para.pvCurPageParams === 'object' ? JSON.stringify(para
					.pvCurPageParams) : para.pvCurPageParams ||
					'', //当前页面参数
				pvLastPageName: para.pvLastPageName || '', //上一页页面名称
				pvLastPageParams: para.pvLastPageParams || '', //上一页页面参数
				pvPageLoadTime: para.pvPageLoadTime || '', //加载时间
				type: para.type || '', //埋点类型
			}
			let timeNow = new Date().getTime();
			if (timeNow - sessionTime > 180000 && !from_session) {
				// session++;
				getStorage('sessionNumber', session)
			}
			session = Number(getStorage('sessionNumber')) + 1;
			data.session = from_session || getStorage("cookie_id") + "_" + session || '';
			sessionTime = timeNow
			console.log(data.session)
			// return data;
			// app.globalData.session_id = data.session
			// app.globalData.sessionTime = timeNow;
			requestConfig('upload', data, true);
			// let param = ["SEND" +
			// 	"\nproject:" + "elab-marketing-system" + 
			// 	"\nmethod:" + 'POST' +
			// 	"\npath:" + '/behavior/brandMiniWeb/upload' +
			// 	"\ndestination:" + '/ws/remote/invoke' +
			// 	"\n\n" + JSON.stringify(data) +
			// 	"\u0000"
			// ];
			// app.wsSendOrder(param,data);//socket 消息发送
			console.warn("***mook***", (data.pvId || data.clkId || data.eventId), data.reserve3)
		} catch (e) {
			console.warn("***util.js-onError***", e);
		}
	},
	getSession() { //获取session
		let timeNow = new Date().getTime();
		let session = uni.getStorageSync('sessionNumber') || timeNow; //session具体的值
		uni.setStorage({
			key: "sessionNumber",
			data: session
		})
		return session;
	},
};
window.from_session = util.getUrlParams(location.href).session || '';
window.from_cookie = util.getUrlParams(location.href).cookie || '';
export default util;
// module.exports = util;