import VConsole from "vconsole";
import store from "../store/store";
import Vue from 'vue'
import axios from "axios";

// import LzEvent from 'lz-event-tracking/lib/vue';
import LzEvent from '../../static/utils/tracking.js'
import apis1 from './apis1.js';
// import {
//   jdReminder
// } from './jdReminderNew.js'
const getCookie = name => {
	//获取cookie
	var strCookie = document.cookie;
	var arrCookie = strCookie.split("; ");
	for (var i = 0; i < arrCookie.length; i++) {
		var arr = arrCookie[i].split("=");
		if (arr[0] == name) return arr[1];
	}
	return "";
};
const getUrlQueryValueByKey = (keyName, url) => {
	/*获取url地址栏中参数值，url为可选，默认为当前页面url*/
	if (!url) {
		url = location.href;
	}
	var reg = new RegExp("(^|[&?])" + keyName + "=([^&]*)(&|$)");
	var r = url.match(reg); //search,查询？后面的参数，并匹配正则
	if (r != null) return unescape(r[2]);
	return "";
};

// 设置debug工具
if (getUrlQueryValueByKey("isDebug") === "true") {
	new VConsole();
}

// 返回当前链接全部参数的一个对象
const getQueryObject = () => {
	let obj = {};
	let query = location.search.replace("?", "").split("&");

	query.forEach((item) => {
		const temp = item.split("=");
		obj[temp[0]] = temp[1];
	});
	return obj;
};

//组装json数据的style样式
const styleUtil = (styleJson) => {
	var json = styleJson
	var sty1 = ''
	for (var key in json) {
		console.log(key + ':' + json[key])
		sty1 = key + ':' + json[key] + ';' + sty1
	}
	return sty1;
};

//客态变主态
const changeStates = () => {
	apis1.changeState(data => {
		console.log(data, '客态 客变主111')
		if (data.resp_code == 0) {
			if (data.data.joinCodeInfo.joinCode == '1001') {
				// callback && callback('success');
				// this.$router.push({ path: '/index', query: { activityType: this.activityType, templateId: this.templateId, activityId: store.state.activityId, shareUserId: this.shareUserId1 } });
			} else if (data.data.joinCodeInfo.joinCode == '1002') {
				// callback && callback(data.data);
				// joinVipService.create(datas, submit => {
				//     console.log("121212")
				// })
				let comCreate = './comCreate.js'
				console.log(comCreate, '客态 客变主222')
			} else if (data.data.joinCodeInfo.joinCode == '1003') {

				console.log(joinVipService, '客态 客变主333')
				// callback && callback(data.data);
				// joinVipService.create(datas, submit => {
				//     console.log("121212")
				// })
			}

		} else {
			Notify(data.resp_msg);
		}
	})
};

//开卡
const goToOpenCard = url => {
	console.log(url, '开卡链接')
	// url = sessionStorage.getItem('oldUrl')
	let urlHerf = sessionStorage.getItem('oldUrl')
	console.log(urlHerf, '开卡链接')
	if (url.indexOf('shopmember') != -1) {
		location.href = url + '&returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId;
	} else {
		location.href = url + '&rn_returnUrl=' + encodeURIComponent(urlHerf) + '&shareUuid=' + store.state.shareUserId;
	}
	// console.log(url + '&returnUrl=' + encodeURIComponent(location.href) + '&shareUuid=' + store.state.shareUserId)
	// alert(url + '&returnUrl=' + encodeURIComponent(location.href) + '&shareUuid=' + store.state.shareUserId);
};



// 跳转店铺方法
const goToShopPage = shopId => {
	// console.log('章子')
	if (shopId) {
		// trackLog(shopId);
		// writePersonInfo(4);
		// reportClick("v_shop", shopId);
		if (store.state.clientType == "WeChat") {
			if (store.state.isMiniProgram) {
				wx.miniProgram.navigateTo({
					url: "/pages/shop/index/index?shopId=" + shopId
				});
			} else {
				location.href = "https://wq.jd.com/mshop/gethomepage?shopId=" + shopId;
			}
		} else {
			location.href = "https://shop.m.jd.com/?shopId=" + shopId;
		}
	}
};


// 跳转商品方法
const goToSkuPage = skuId => {
	console.log('*****', skuId)
	if (skuId) {
		// trackLog(skuId);
		// writePersonInfo(5);
		// reportClick("v_sku", store.state.shopId, skuId);
		if (store.state.clientType == "WeChat") {
			if (store.state.isMiniProgram) {
				wx.miniProgram.navigateTo({
					url: "/pages/item/detail/detail?sku=" + skuId
				});
			} else {
				location.href = "https://wq.jd.com/item/view?sku=" + skuId;
			}
		} else {
			location.href =
				"https://item.m.jd.com/product/" +
				skuId +
				".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";

			let a = "https://item.m.jd.com/product/" +
				skuId +
				".html?wjfrom=ISV_2180A2AFA5B2452F9061C01C053C4756_WX&wjwxpubid=wxd9fd3549c5fdb283&wjunionid=&wjopenid=";
			console.log(a, 'a')
		}
	}
};

// 跳转到通天塔，会场方法
const goToActive = url => {
	let tempUrl = url;

	if (url) {
		// reportClick("v_channel", store.state.shopId);
		if (store.state.clientType == "WeChat") {
			if (store.state.isMiniProgram) {
				tempUrl = tempUrl.replace("/mall", "/mini");
				tempUrl = tempUrl.replace("/wq", "/mini");
				tempUrl = tempUrl + "?wxAppName=jd";

				wx.miniProgram.navigateTo({
					url: "/pages/h5/index?encode_url=" + encodeURIComponent(tempUrl)
				});
			} else {
				location.href = url;
			}
		} else {
			location.href = url;
		}
	}
};


//埋点初始化
const initBuriedPoint = loginData => {
	console.log(loginData, '登陆后的初始化埋点数据');

	if (store.state.clientType == '01') {
		var channel = 'app'
	} else if (store.state.clientType == '02') {
		var channel = 'wechat'
	} else if (store.state.clientType == '03') {
		var channel = 'qq'
	}
	 let cur_url = location.href;
	var activityType = getUrlQueryValueByKey("activityType", cur_url);
	var nodeId = getUrlQueryValueByKey("nodeId", cur_url);
	var activityId = getUrlQueryValueByKey("activityId", cur_url);
	var templateId = getUrlQueryValueByKey("templateId", cur_url);

	console.log(activityId, 'activityId登陆后的初始化埋点数据');

	setTimeout(() => {
		// console.log('LzEvent1222',LzEvent)
		LzEvent.setBaseInfo({
			shopId: loginData.shopId, // 店铺标识，不可以为空
			customerId: loginData.customerId, // C端用户唯一身份标识customerId，不可以为空
			nickName: loginData.nickName, // 用户昵称，不可以为空
			// 以下信息京东数据回流的时候需要使用
			jdActivityId: loginData.token, // 调用JOS创建活动接口返回的活动id
			activityid: activityId, //store.state.activityId,
			type: activityType, //sessionStorage.getItem('activityType'),
			channel: channel,
			shareuserid: loginData.shareUserPin,
			version: templateId, //sessionStorage.getItem('templateId'), //模板id
			versionName: "", //模板名称
			nodeId: nodeId //store.state.nodeId // 节点ID，可以为空
		})
	}, 300)
	// console.log(store.state.shopId, 'store.state.shopId')
	// console.log(store.state.nodeId, 'store.state.nodeId')
	// console.log(store.state.nickName, 'store.state.nickName')
}

//手机号校验
const phoneCheck = (value) => {
	const reg = /^[1][3-9][0-9]{9}$/;
	if (value == '' || value == undefined || value == null) {
		callback();
	} else {
		if ((!reg.test(value)) && value != '') {
			// callback(new Error('请输入正确的电话号码'));
			return false;
		} else {
			return true;
		}
	}
}

// 邮箱校验
const emailCheck = (value) => {
	const reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,8})$/;
	if (value == '' || value == undefined || value == null) {
		callback();
	} else {
		if ((!reg.test(value)) && value != '') {
			return false;
		} else {
			return true;
		}
	}
}

//特殊字符和表情符校验
const checkEmoj = (substring) => {
	console.log(substring, 'substring')
	var reg = /[\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/;
	var reg_mark = /[`~!@#$%^&*()+=|{}':;',/\/\[\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]/
	if (reg.test(substring) || reg_mark.test(substring)) {
		// alert("输入框内有特殊表情，请删除重新输入")
		return false;
	} else {
		return true;
		// alert("验证通过")
	}
}



const checkInput = (str) => {

	var reg = /[\u4E00-\u9FA5a-zA-Z0-9-\d_,—,-,_,(,),(),（）]/;

	var count = 0
	for (var i = 0; i < str.length; i++) {
		if (reg.test(str[i])) {
			count = count + 1
		}
	}
	if (count == str.length) {
		return true
	} else {
		return false
	}

}

//兑换plus会员卡和爱奇艺会员卡
const exchangePrize = () => {
	location.href = 'http://asset-m.jd.com/'
}

//活动提醒
const acReminder = (remindOption, callback) => {
	// console.log('122222222')
	let remindOption1 = {
		// url: '3.cn/100ZCR-4w',
		url: location.href,
		tag: store.state.actName,
		title: store.state.actName,
		type: 'HUODONG',
		// time: remindOption.acRemindTime,
		time: remindOption.acRemindTime,
		id: remindOption.acRemindTime
	}

	jdReminder.add(remindOption1).then((resData) => {
		callback(resData)
	}).catch((err) => {
		console.log(err, 'err')
		let errData = {
			appointed: false
		}
		callback(errData)
	})

	// jdReminder(remindOption1).then((resData) => {
	//   callback(resData)
	// }).catch((err) => {
	//   console.log(err, 'err')
	//   let errData = {
	//     appointed: false
	//   }
	//   callback(errData)
	// })

}

//去官方的待评价订单页面
const getJdPingJia = () => {
	console.log('去官方的待评价订单页面')
	if (store.state.clientType == '01') {
		var channel = 'app'
	} else if (store.state.clientType == '02') {
		var channel = 'wechat'
	} else if (store.state.clientType == '03') {
		var channel = 'qq'
	}
	if (channel == 'app') {
		var params = {
			category: "jump",
			des: "commentCenter"
		}
		params = JSON.stringify(params)
		var linkUrl = "openjd://virtual?params=" + params;
		window.location.replace(linkUrl);
	} else {
		window.location.replace("https://wqs.jd.com/order/orderlist_merge_old.shtml?tab=4")
	}
}

export {
	getCookie,
	getUrlQueryValueByKey,
	goToShopPage,
	goToSkuPage,
	goToActive,
	getQueryObject,
	goToOpenCard,
	initBuriedPoint,
	phoneCheck,
	checkEmoj,
	checkInput,
	changeStates,
	exchangePrize,
	acReminder,
	emailCheck,
	getJdPingJia
};
