import store from "@/store";
import axios from 'axios';
import router from "@/router";
import {getStorage,setStorage} from "@/utils/localStorage";
import '@/services/requestConfig.js'; //导入请求的拦截器
// import emojiConfig from '@/components/emojiComponent/lib/js/config'
// import Config from "@/components/emojiComponent/lib/js/config";
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
const common = {
    clearMap(type = 0){//清空地图相关
        console.log("***clearMap***",type)
		if(!window.map){//如果不存在地图对象,则不需要往下执行清空地图的动作
			return false;
		}
        if(type==1){//入股清空类型是1,则表示要清空地图上的项目信息和聚合信息-全面清空
            window.project && window.project.clearProjecttLayer();//先清空项目地图
        }
        window.modulePolygon && window.modulePolygon.clearPolygonLayer();//板块图层
        window.competition && window.competition.clearCompetitionLayer();//竞品图层
        window.poiOperate && window.poiOperate.clearPoiLayer();           //poi图层
        window.trafficOperate && window.trafficOperate.clearTrafficLayer();//交通路网图层
        window.massPointOperate && window.massPointOperate.clearMassLayer();//mass点位图层
    },
	hexToRgba(hex, opacity) {
	    if (!hex||!opacity){
	        return hex
	    }
	    let RGBA;
	    if (hex.includes('#')&&hex.length==7){
	        RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," +
	            parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
	    }else if (hex.includes('rgb(')){
	        var values = hex
	            .replace(/rgb?\(/, '')
	            .replace(/\)/, '')
	            .replace(/[\s+]/g, '')
	            .split(',')
	            return 'rgba(${values[0]},${values[1]},${values[2]},${opacity})'
	    }else if(hex.includes('rgba(')){
	        var values = hex
	            .replace(/rgba?\(/, '')
	            .replace(/\)/, '')
	            .replace(/[\s+]/g, '')
	            .split(',')
	            return 'rgba(${values[0]},${values[1]},${values[2]},${opacity})'
	    }else{
	        return hex
	    }
	    return RGBA
	},
	//项目切换时触发更新用户账号以及相关逻辑
	userProjectChangeHandle(project){
		if(!project){
			return false;
		}
		let uid = window.mapVue.$route.query.uid || '';//获取当前路由上的uid
		//当前缓存里面的账号信息
		let _account = null;
		let adversiterList = project.adversiterList || [];
		// let userInfo = window.userInfo;
		// let _a1 = userInfo ? userInfo['userAccount'] : null;

		let _a3 = (adversiterList && adversiterList[0]) ? adversiterList[0] : null;
		//当前项目下没有账号信息
		if(!_a3){
			this.userAccountChange(project,_account);//则设置当前账号为空
			return false;//同时不在往下执行
		}
		//如果检测存在用户账号信息
		if(uid){
			//当前项目中寻找这个账号
			_account = adversiterList.find(it=>it.advertiserId == uid);
			if(!_account){//当前项目中不存在路由中的这个账号
				_account = _a3;//使用当前项目下的 第一个账号作为当前账号;表示切换了项目地块
			}
		}else{//使用当前项目下的 第一个账号作为当前账号
			_account = _a3;
		}
		console.warn("***account-userAccountChange0***",_account,project,uid);
		this.userAccountChange(project,_account)
	},
	//切换账号,同时更新到全局变量中
	userAccountChange(project,account){
		if(!account){
			console.warn("***account-userAccountChange2***",account,project);
			window.userInfo['userAccount'] = null;//修改当前页面的
			return false;
		}
		switch(account.platform){
			case 1:
				account['type'] = 'tencent';
				account['typeName'] = '腾讯';
				break;
			case 2:
				account['type'] = 'huge';
				account['typeName'] = '巨量';
				break;
			case 3:
				account['type'] = 'baidu';
				account['typeName'] = '百度';
				break;
			default:
				break;
		}
		// if((_account && account && _account.advertiserId == account.advertiserId) || (account==null && (!_account || !_account.advertiserId))){ //账号相同,则不需要更新
		// 	console.warn("***账号相同,则不需更新***", _account,account);
		// }
		// else{//执行账号切换

		// }
		account.landId = project.id;//记录下当前选中账号 所属地块-因为不同地块可能有相同账号的情况
		userInfo['userAccount'] = account;//修改当前页面的当前账号信息
		// setStorage("userAccount", account);//更新到缓存里面-页面跳转时使用,window对象 不能跨页使用
		console.warn("***account-userAccountChange1***",account,project);
		//切换账号则切换路由中的uid
		window.mapVue.$router.push({ path: window.mapVue.$route.path, query: { uid: account.advertiserId || '' }})
	},
	async getLocationPOI(param) {
		const res = await requestConfig("locationPOI", param);
		if (res.success) {
			if (res.single) {
				//绘制poi
				this.getPois(res.single);
			}
		}else{
			massPointOperate.removeMassList();
		}
	},

	async recommendLocation(param) {
		const res = await requestConfig("recommendLocation", param);
		if (res.success) {
			if (res.single.poiList){
				let list = res.single.poiList;
				massPointOperate.removeMassList();
				window.massPointOperate.addMassPointList(list,true);
			}
			if (res.single.plateInfoModel&&res.single.plateInfoModel.length>0){
				massPointOperate.addPolygons(res.single.plateInfoModel);
			}
		}else{
			massPointOperate.removeMassList();
		}
	},

	async recommendPlanLocation(param) {
		const res = await requestConfig("recommendPlanLocation", param);
		if (res.success) {
			massPointOperate.removeMassList();
			if (res.list){
				let list = res.list;
				window.massPointOperate.addMassPointList(list,true);
			}
		}else{
			massPointOperate.removeMassList();
		}
	},

	// 判断是否为Mac 操作系统
	isMacAction() {
		return /macintosh|mac os x/i.test(navigator.userAgent);
	},

	//判断两个对象是否相等
	isEqual(objA,objB){
		//相等
		if(objA === objB) return objA !== 0 || 1/objA === 1/objB;
		//空判断
		if(objA == null || objB == null) return objA === objB;
		//类型判断
		if(Object.prototype.toString.call(objA) !== Object.prototype.toString.call(objB)) return false;

		switch(Object.prototype.toString.call(objA)){
			case '[object RegExp]':
			case '[object String]':
				//字符串转换比较
				return '' + objA ==='' + objB;
			case '[object Number]':
				//数字转换比较,判断是否为NaN
				if(+objA !== +objA){
					return +objB !== +objB;
				}

				return +objA === 0?1/ +objA === 1/objB : +objA === +objB;
			case '[object Date]':
			case '[object Boolean]':
				return +objA === +objB;
			case '[object Array]':
				//判断数组
				for(let i = 0; i < objA.length; i++){
					if (!this.isEqual(objA[i],objB[i])) return false;
				}
				return true;
			case '[object Object]':
				//判断对象
				let keys = Object.keys(objA);
				for(let i = 0; i < keys.length; i++){
					if (!this.isEqual(objA[keys[i]],objB[keys[i]])) return false;
				}

				keys = Object.keys(objB);
				for(let i = 0; i < keys.length; i++){
					if (!this.isEqual(objA[keys[i]],objB[keys[i]])) return false;
				}

				return true;
			default :
				return false;
		}
	},

	/**
	 * 获取字符串的字符数
	 * @param str
	 * @returns {number}
	 */
	wordLengthFilter(str){
		let size = this.byteLengthFilter(str)
		return Math.round(size/2)
	},

	/**
	 * 超出最大字节数截取
	 * @param e 原始字符串
	 * @param maxLength 最大字节数
	 * @returns {string} 截取后的字符串
	 */
	copyWritingInput(e,maxLength = 60) {
		let s = 0;
		e = JSON.parse(JSON.stringify(e))
		if (e==''){
			return e
		}
		let cheseReg = /[(\u4e00-\u9fa5)(\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3010|\u3011|\u007e)]+$/
		for (var i = 0; i < e.length; i++) {
			const code = e.charAt(i);
			if("\n" == code){ // 换行符不算入字节
				s += 0
			}else if(/\s/.test(code)){
				s += 1;
			}else if (/^[\u0000-\u00ffA-Za-z1-9]+$/.test(code)) {
				s += 1;
			}else if(cheseReg.test(code)){
				s += 2
			}else{
				s += 0;
			}
			if (s > maxLength) {
				return e.substring(0, i);
				// return resultStr;
			}
			// resultStr += code
		}
		return e
	},


	/**
	 * 新的截取功能
	 * @param e
	 * @param maxLength
	 */
	subinput(e,maxLength = 60){
		let s = 0;
		e = JSON.parse(JSON.stringify(e))
		let cheseReg = /[(\u4e00-\u9fa5)(\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3010|\u3011|\u007e)]+$/
		for (var i = 0; i < e.length; i++) {
			const code = e.charAt(i);
			if("\n" == code){ // 换行符不算入字节
				s += 0
			}else if(/\s/.test(code)){
				s += 1;
			}else if (/^[\u0000-\u00ffA-Za-z1-9]+$/.test(code)) {
				s += 1;
			}else if(cheseReg.test(code)){
				s += 1;
				if (s >= maxLength) {
					return e.substring(0, i);
				}else {
					s += 1;
				}
			}else{
				s += 0;
			}
			if (s >= maxLength) {
				return e.substring(0, i + 1);
			}
		}
	}
};

export default common;