import tools from '/common/tools';
import {
	apiCardConfigQuery,
	apiUserConfigQuery,
	apiWarnMessageQuery,
	apiUnReadMessageQuery,
	apiIsNewUserInCardComp,
	checkResCode
} from '/common/api';

import {
	defaultPopUpDataList,
	defaultPopUpDataList2,
	defaultPopUpDataList3
} from '/common/define';

var cardfunc = {
	caller: null,
	token: "",
	ecId: 0, // 卡片id
	isNewUser: false,	// 是否新用户
	
	cardConfigData: {
		tabActiveColor: "#81cd00",

		popupRuleConfig: {}, // 规则弹窗配置
		popupRuleList: [], // 规则弹窗数据

		popupExchgConfig: {}, // 兑换地址弹窗配置
		popupExchgList: [], // 兑换地址弹窗数据

		popupHelpConfig: {}, // 帮助弹窗配置
		popupHelpList: [],

		popupMessageConfig: {}, // 通知弹窗配置
		popupMessageList: [], // 通知弹窗数据

		popupWarnConfig: {}, // 警告弹窗配置
		popupWarnList: [], // 警告弹窗数据
	},
	
	userConfigData: {
		
	},
	
	init(caller, token, ecId) {
		this.caller = caller;
		this.token = token;
		this.ecId = ecId;
		this.removeCss();
	},
			
	// 清除css
	removeCss() {
		tools.removeCssCode("css-common");
		tools.removeCssCode("css-custom");
		tools.removeCssCode("css-user");
	},

	getCardConfig(loadConfig, testconfig) {
		const cardconfigType = getApp().$cardconfigType;
		// console.log("[getConfig] cardconfigType:", cardconfigType);

		if (cardconfigType == "local") {
			loadConfig(testconfig);
			// this.testCardConfig(testconfig, loadConfig);
		} else {
			this.cardConfigQuery(loadConfig);
		}
	},

	getUserConfig(loadConfig, testconfig) {
		const cardconfigType = getApp().$cardconfigType;
		// console.log("[getConfig] cardconfigType:", cardconfigType);

		if (cardconfigType == "local") {
			loadConfig(testconfig);
			// this.testCardConfig(testconfig, loadConfig);
		} else {
			this.userConfigQuery(loadConfig);
		}
	},
	
	parseCardConfig(cardconfig) {
		// console.log("[parseCardConfig] cardconfig:", cardconfig);
		if (cardconfig == undefined || cardconfig == "") {
			return;
		}
		
		if (typeof cardconfig == "string") {
			cardconfig = cardconfig.replace(/[\r|\n|\t]/g, "");
			const config = JSON.parse(cardconfig);
			// console.log("[parseCardConfig] config:", config);
			return config;
		} else {
			return cardconfig;
		}
	},

	// 加载卡片通用配置
	loadCardCommonConfig(config_common) {
		// console.log("[loadCardCommonConfig] config_common:", config_common);
		config_common = this.parseCardConfig(config_common);
		if (config_common == undefined || config_common == "") {
			return;
		}

		if (config_common.css != undefined && config_common.css.length > 0) {
			tools.loadCssCode(config_common.css, "css-common");
		}

		if (config_common.tabActiveColor != undefined && config_common.tabActiveColor.length > 0) {
			this.cardConfigData.tabActiveColor = config_common.tabActiveColor;
		}

		// 加载规则弹窗配置
		if (config_common.popupRuleConfig != undefined) {
			this.cardConfigData.popupRuleConfig = config_common.popupRuleConfig;
		}

		// 加载帮助弹窗配置
		if (config_common.popupHelpConfig != undefined) {
			this.cardConfigData.popupHelpConfig = config_common.popupHelpConfig;
		}

		// 加载警告弹窗配置
		if (config_common.popupWarnConfig != undefined) {
			this.cardConfigData.popupWarnConfig = config_common.popupWarnConfig;
		}

		// 加载兑换地址弹窗配置
		if (config_common.popupExchgConfig != undefined) {
			this.cardConfigData.popupExchgConfig = config_common.popupExchgConfig;
		}

		// 加载通知弹窗配置
		if (config_common.popupMessageConfig != undefined) {
			this.cardConfigData.popupMessageConfig = config_common.popupMessageConfig;
		}

		// 加载弹窗(规则)数据
		const popupRuleList = config_common.popupRuleList;
		// console.log("[loadCardCommonConfig] popupRuleList:", popupRuleList);
		if (popupRuleList != undefined && popupRuleList.length > 0) {
			this.cardConfigData.popupRuleList.length = 0;
			for (var i = 0; i < popupRuleList.length; i++) {
				// console.log("[loadCardCommonConfig] popupRuleList", i, popupRuleList[i]);
				if (popupRuleList[i] == 'default') {
					for (var j = 0; j < defaultPopUpDataList.length; j++) {
						this.cardConfigData.popupRuleList.push(defaultPopUpDataList[j]);
					}
				} else if (popupRuleList[i] == 'default2') {
					for (var j = 0; j < defaultPopUpDataList2.length; j++) {
						this.cardConfigData.popupRuleList.push(defaultPopUpDataList2[j]);
					}
				} else if (popupRuleList[i] == 'default3') {
					for (var j = 0; j < defaultPopUpDataList3.length; j++) {
						this.cardConfigData.popupRuleList.push(defaultPopUpDataList3[j]);
					}
				} else {
					this.cardConfigData.popupRuleList.push(popupRuleList[i]);
				}
			}
		} else {
			this.cardConfigData.popupRuleList = defaultPopUpDataList2;
			// console.log("[loadCardCommonConfig] popupRuleList 加载默认列表");
		}

		// 加载弹窗(兑换地址)数据
		const popupExchgList = config_common.popupExchgList;
		if (popupExchgList != undefined && popupExchgList.length > 0) {
			this.cardConfigData.popupExchgList.length = 0;
			for (var i = 0; i < popupExchgList.length; i++) {
				// console.log("[loadCardCommonConfig] popupExchgList", i, popupExchgList[i]);
				this.cardConfigData.popupExchgList.push(popupExchgList[i]);
			}
		}

		// 加载弹窗(帮助)数据
		const popupHelpList = config_common.popupHelpList;
		if (popupHelpList != undefined && popupHelpList.length > 0) {
			this.cardConfigData.popupHelpList.length = 0;
			for (var i = 0; i < popupHelpList.length; i++) {
				// console.log("[loadCardCommonConfig] popupHelpList", i, popupHelpList[i]);
				this.cardConfigData.popupHelpList.push(popupHelpList[i]);
			}
		}
		// console.log("[loadCardCommonConfig] cardConfigData:", this.cardConfigData);
	},
	
	// 加载用户的弹窗数据
	loadUserPopupRule(config) {
		const tplInfo = config.tplInfo;
		const matchInfo = config.matchInfo;
		if (matchInfo) {
			let hint = "<span style='color:#FF5E00;'>参赛要求</span><br>";
			hint += "① 赛事以自身安全为最高要求，请正确评估自身健康，切勿超负荷运动，适时参赛<br>② 参赛人群建议：6-60岁健康居民<br>";
			hint += "<br><span style='color:#FF5E00;'>安全提醒</span><br>";
			hint += "① 请着运动服及运动鞋<br>② 避免聚集、分散参与<br>③ 及时增减衣物，预防感冒<br>④ 注意交通安全与自身安全";
			const contact = `联系人：${matchInfo.contactName} &nbsp;&nbsp; 电话：<a href='tel:${matchInfo.phone}' style='color: #ff5500;'>${matchInfo.phone}</a>`;
			const content = `${hint}<br><br>${contact}`;
			// const content = `${matchInfo.description}<br><br>${contact}`;
			const popupRule = [{
				"type": 1,
				"data": {
					"title": matchInfo.compName,
					"logo": {
						"src": tplInfo.matchLogo,
						"width": "260px",
						 "height": "90px"
					},
					"content": content
				}
			}];
			this.cardConfigData.popupRuleList.unshift(...popupRule);
		}
	},
	
	// 获取用户的比赛路线数据
	getUserPathList(config) {
		const mapInfo = config.mapInfo;
		const mapNum = mapInfo.length;
		let pathList = {};
		if (mapNum > 0) {
			let activityList = [];
			// 将多地图的路线信息数组合并成一个数组
			for (var m = 0; m < mapNum; m++) {
				activityList.push(...mapInfo[m].activityList);
			}
			console.log("[getUserPathList] activityList:", activityList);
			const activityNum = activityList.length;
			let type = 4;
			let navImg = "/static/common/nav3.png";
			if (activityNum > 1) {
				type = 3;
				navImg = "/static/common/nav.png";
			}
			if (activityNum > 0) {
				const rowSize = 2; // 每行显示的路线数量
				const rowNum = Math.ceil(activityNum / rowSize);
				for (var i = 0; i < rowNum; i++) {
					let row = [];
					for (var j = 0; j < rowSize; j++) {
						// console.log(`[getUserPathList] i: ${i} j: ${j}`);
						const activity = activityList[i * rowSize + j];
						if (!activity) {
							break;
						}
						const path = {
							"type": type,
							"pathName": activity.showName,
							"pathImg": activity.pathImg,
							"path": {
								"ocaId": activity.ocaId,
								"mcType": activity.matchType
							},
							"navImg": navImg,
							"point": {
								"longitude": activity.point.longitude,
								"latitude": activity.point.latitude,
								"name": activity.point.name
							}
						};
						// console.log(`[getUserPathList] i: ${i} j: ${j} path: ${JSON.stringify(path)}`);
						row.push(path);
					}
					pathList["row" + (i + 1)] = row;
					// console.log("[getUserPathList] row:", row);
				}
			}
		} else {
			console.warn("[getUserPathList] mapInfo err:", mapInfo);
		}
		return pathList;
	},

	// 卡片配置信息查询
	cardConfigQuery(callback) {
		uni.request({
			url: apiCardConfigQuery,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"token": this.token,
			},
			method: "POST",
			data: {
				ecId: this.ecId,
				pageName: "all"
			},
			success: (res) => {
				console.log("[cardConfigQuery]", res);
				const data = res.data.data;
				const config = data.configJson;
				// console.log("[cardConfigQuery] config", config);
				callback(config);
			},
			fail: (err) => {
				console.log("[cardConfigQuery] err", err);
			},
		});
	},

	// 用户自定义配置信息查询
	userConfigQuery(callback) {
		uni.request({
			url: apiUserConfigQuery,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"token": this.token,
			},
			method: "POST",
			data: {
				ecId: this.ecId,
				pageName: "all"
			},
			success: (res) => {
				// console.log("[userConfigQuery]", res);
				const data = res.data.data;
				const config = data.configJson;
				// console.log("[userConfigQuery] config", config);
				callback(config);
			},
			fail: (err) => {
				console.log("[userConfigQuery] err", err);
			},
		});
	},
	
	// 警告列表查询
	warnMessageQuery(callback=null) {
		uni.request({
			url: apiWarnMessageQuery,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"token": this.token,
			},
			method: "POST",
			data: {
				ecId: this.ecId
			},
			success: (res) => {
				// console.log("warnMessageQuery", res);
				if (checkResCode(res)) {
					const warnRs = res.data.data;
					this.cardConfigData.popupWarnList.length = 0;
					for (var i = 0; i < warnRs.length; i++) {
						let popupData = {
							type: 9, // 9: 警告
							data: {}
						};
						popupData.data.warnType = warnRs[i].warnType;
						popupData.data.title = warnRs[i].warnTitle;
						popupData.data.iconUrl = warnRs[i].iconUrl;
						popupData.data.iconNum = warnRs[i].iconNum;
						popupData.data.message = warnRs[i].warnMessage;
						popupData.data.qrCodeUrl = warnRs[i].qrCodeUrl;
						this.cardConfigData.popupWarnList.push(popupData);
					}

					/* this.cardConfigData.popupWarnList.push(
						{
							type: 9, // 9: 警告
							data: {
								warnType: 1,
								title: "黄牌",
								iconUrl: "/static/common/card_yellows.png",
								iconNum: 1,
								message: `亲爱的参赛者:
　　	收到此黄牌，说明您的比赛数据被系统判定为存在异常，此次比赛（活动）为徒步定向校园文化主题活动，请自觉遵守规则，如果您收到的黄牌数量过多<span style='color: red'>（超过2张）</span>，您的成绩将影响到您的院系/单位成绩，同时您的个人成绩也有可能根据规则被取消。如果您坚持您的比赛数据没有问题，请联系我们的客服人员，谢谢！
　　让我们一起创造文明、和谐的校园生活，感谢您的支持！`,
								qrCodeUrl: "https://orienteering.beswell.com/shanda/%E8%AD%A6%E5%91%8A%E4%BA%8C%E7%BB%B4%E7%A0%81%402x.png"
								}
						}
					); */
					// console.log("popupWarnList", this.cardConfigData.popupWarnList);
					// console.log("caller.popupWarnList length:", this.caller.cardConfigData.popupWarnList.length);
					
					if (callback != null) {
						callback(this.cardConfigData.popupWarnList);
					}
				}
			},
			fail: (err) => {
				console.log("warnMessageQuery err", err)
			},
		});
	},
	
	// 未读消息列表查询
	unReadMessageQuery(callback=null) {
		uni.request({
			url: apiUnReadMessageQuery,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"token": this.token,
			},
			method: "POST",
			data: {
				relationType: 2, // 类型 1 成就 2 卡片
				relationId: this.ecId
			},
			success: (res) => {
				// console.log("getUnReadMessageQuery", res);
				if (checkResCode(res)) {
					const unReadMessageRs = res.data.data;
					this.cardConfigData.popupMessageList.length = 0;
					let mqIdListStr = "";
					for (var i = 0; i < unReadMessageRs.length; i++) {
						let popupData = {
							type: 6, // 6: 通知
							data: {}
						};
						mqIdListStr += "-" + unReadMessageRs[i].mqId;
						popupData.data.mqType = unReadMessageRs[i].mqType;
						popupData.data.title = unReadMessageRs[i].mqTitle;
						popupData.data.message = unReadMessageRs[i].mqMessage;
						this.cardConfigData.popupMessageList.push(popupData);
					}
					
					/* this.cardConfigData.popupMessageList.push(
						{
							type: 6,	// 6: 通知
							data: {
								mqType: 3,
								title: "特别提醒",
								message: `本次比赛的目的为体验校园文化，提升身体素质，让大家感受和熟悉定向运动魅力及技巧。<br>
								在此特别提醒：<br>
								无论是驰骋校园，还是漫步秋色，<b>“勿以轮带步，唯愿步量途”。让我们用脚步来丈量这片共同热爱的家园</b>，见证山大123周年的辉煌时刻！<br>
								<div style='text-align: right;'>山东大学体育委员会</div>`
								}
						}
					); */
					// console.log("popupMessageList", this.cardConfigData.popupMessageList);
	
					if (callback != null) {
						callback(this.cardConfigData.popupMessageList, mqIdListStr);
					}
				}
			},
			fail: (err) => {
				console.log("getUnReadMessageQuery err", err);
			},
		});
	},
	
	// 用户是否新用户
	isNewUserQuery(callback=null) {
		uni.request({
			url: apiIsNewUserInCardComp,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"token": this.token,
			},
			method: "POST",
			data: {
				// ecId: this.ecId
				ecId: 0	// 0 全部赛事活动
			},
			success: (res) => {
				// console.log("isNewUserInCardComp", res);
				if (checkResCode(res)) {
					this.isNewUser = res.data.data.isNew;
					// this.isNewUser = true;	// test
					if (callback != null) {
						callback(this.isNewUser);
					}
				}
			},
			fail: (err) => {
				console.log("isNewUserInCardComp err", err);
			},
		});
	},

}

export default cardfunc;