<!-- 
[游戏] 网格赛事 - 网格拼图
http://localhost:5173/card/#/pages/game/grid/grid
https://oss-mbh5.colormaprun.com/card/#/pages/game/grid/grid
 -->
<template>
	<view class="body">
		<view v-if="pageReady" class="content uni-column">
			<view class="uni-column page-top">
				<my-topbar :mcName="compName" class="topbar-color" :showRule="false"
					@btnBackClick="btnBack"></my-topbar>
			</view>
			<view class="main uni-column">
				<view v-if="grid.state <= 1" class="mt-content">开始你的挑战吧</view>
				<view v-if="grid.state == 2" class="mt-content">很棒！继续你的挑战吧</view>
				<view v-if="grid.state >= 3" class="mt-content" style="color: #FF5733;">挑战成功！</view>
				<view class="grid uni-column uni-jcse" :style="getGridStyle()">
					<view class="grid-row uni-row uni-jcse" :style="getGridRowStyle()" v-for="rowId in grid.heightNum"
						:key="rowId">
						<view class="grid-cell" :style="getGridCellStyle(rowId, colId)" v-for="colId in grid.widthNum"
							:key="colId" @click="onCellClick(rowId, colId)">
							<template v-for="(item, index) in grid.detailRs" :key="index">
								<view class="cell-name" :class="item.isComplete ? 'cell-name-complete' : 'cell-name-uncomplete'" v-if="item.orderNum == getCellOrderNum(rowId, colId)">
									{{item.showName}}
								</view>
							</template>
						</view>
					</view>
				</view>
				<view class="introduce uni-column">
					<text class="introduce-title">{{introduce.title}}</text>
					<text class="introduce-content" v-html="introduce.content"></text>
				</view>

				<view v-if="activityRules.content.length > 0" class="activityRules uni-column">
					<text class="activityRules-title">{{activityRules.title}}</text>
					<text class="activityRules-content" v-html="activityRules.content"></text>
				</view>
				
			</view>

			<my-popup ref="mypopup" :config="popupDataConfig" :dataList="popupDataList"
				@popup-start="startGame"></my-popup>
		</view>
	</view>
</template>

<script>
	import tools from '../../../common/tools';
	import cardfunc from '../../../common/cardfunc';
	import {
		localCardConfig
	} from "./cardconfig/test.js";
	import {
		token,
		apiGridsQuery,
		apiUserJoinCardQuery,
		apiOnlineMcSignUp,
		checkResCode,
		checkToken
	} from '../../../common/api';

	export default {
		data() {
			return {
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				pageName: "grid",
				queryObj: {},
				queryString: "",
				token: "",
				ecId: 0, // 卡片id
				compId: 0, // 赛事id
				compName: "", // 赛事名称
				mcState: 0, // 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				isJoin: false, // 是否报名
				// acttime: "", // 活动时间
				// beginSecond: null, // 活动或赛事开始时间戳，单位秒
				// endSecond: null, // 活动或赛事结束时间戳，单位秒

				sltCellOrderNum: 0, // 用户选中网格的序号
				sltCellRs: {}, // 用户选中网格对应的活动记录
				popupDataConfig: {
					"height": "530px"
				},
				popupDataList: [],

				grid: { // 网格数据
					widthNum: 0, // 横向网格数量
					heightNum: 0, // 竖向网格数量
					maskImgPic: "", // 遮罩图url
					actualImgPic: "", // 真实图url
					state: 0, // 网格赛事状态 1 未开始 2 进行中 3 已完成
					detailRs: [{
						orderNum: 0, //序号
						ocaId: 0, //活动id    
						mcType: 0, //活动类型 1普通 2线下 3线上 
						isComplete: 0, //是否完赛
						showName: "", //显示名称
						description: "", //描述
						longitude: 0, //导航起点经度
						latitude: 0, //导航起点纬度
						popupImg: "" // 弹窗图片
					}]
				},

				grid0: { // 网格数据
					widthNum: 1, // 横向网格数量
					heightNum: 1, // 竖向网格数量
					maskImgPic: "static/backgroud/grid4_mask.png", // 遮罩图url
					actualImgPic: "static/backgroud/grid_bg.jpg", // 真实图url
					state: 0, // 网格赛事状态 1 未开始 2 进行中 3 已完成
				},
				grid1: { // 网格数据
					widthNum: 2, // 横向网格数量
					heightNum: 2, // 竖向网格数量
					maskImgPic: "static/backgroud/grid4_mask.png", // 遮罩图url
					actualImgPic: "static/backgroud/grid_bg.jpg", // 真实图url
					state: 0, // 网格赛事状态 1 未开始 2 进行中 3 已完成
					detailRs: [{
						orderNum: 1, //序号
						ocaId: 0, //活动id    
						mcType: 0, //活动类型 1普通 2线下 3线上 
						isComplete: 1, //是否完赛
						showName: "", //显示名称
						description: "", //描述
						longitude: 0, //导航起点经度
						latitude: 0 //导航起点纬度
					}]
				},
				grid2: { // 网格数据
					widthNum: 3, // 横向网格数量
					heightNum: 3, // 竖向网格数量
					maskImgPic: "static/backgroud/grid9_mask.png", // 遮罩图url
					actualImgPic: "static/backgroud/grid_bg.jpg", // 真实图url
					state: 2, // 网格赛事状态 1 未开始 2 进行中 3 已完成
					detailRs: [{
						orderNum: 1, //序号
						ocaId: 0, //活动id    
						mcType: 0, //活动类型 1普通 2线下 3线上 
						isComplete: 1, //是否完赛
						showName: "asdf", //显示名称
						description: "", //描述
						longitude: 0, //导航起点经度
						latitude: 0 //导航起点纬度
					}]
				},
				grid3: { // 网格数据
					widthNum: 4, // 横向网格数量
					heightNum: 4, // 竖向网格数量
					maskImgPic: "static/backgroud/grid4_mask.png", // 遮罩图url
					actualImgPic: "static/backgroud/grid_bg.jpg", // 真实图url
					state: 0, // 网格赛事状态 1 未开始 2 进行中 3 已完成
					detailRs: [{
						orderNum: 1, //序号
						ocaId: 0, //活动id    
						mcType: 0, //活动类型 1普通 2线下 3线上 
						isComplete: 0, //是否完赛
						showName: "", //显示名称
						description: "", //描述
						longitude: 0, //导航起点经度
						latitude: 0, //导航起点纬度
					}]
				},

				introduce: {
					title: "",
					content: ""
				},
				activityRules: {
					title: "",
					content: ""
				}
			}
		},
		computed: {},
		onLoad(query) { // 类型非必填，可自动推导
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.token = query["token"] ?? token;
			this.ecId = query["id"] ?? 0;

			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {},
		onUnload() {},
		methods: {
			// 获取网格序号 1-9
			getCellOrderNum(rowId, colId) {
				return (rowId - 1) * this.grid.widthNum + colId;
			},
			getGridStyle() {
				let style = "";
				// 网格赛事状态 1 未开始 2 进行中 3 已完成
				// if (this.grid.state >= 3) {
				// 	style = `background-image: url("${this.grid.actualImgPic}");`;
				// } else {
					style = `background-image: url("${this.grid.maskImgPic}");`;
				// }
				// console.log("getGridStyle", style);
				return style;
			},
			getGridRowStyle() {
				let style = "";
				let height = "";
				if (this.grid.heightNum == 1) {
					height = "98%";
				} else if (this.grid.heightNum == 2) {
					height = "49%";
				} else if (this.grid.heightNum == 3) {
					height = "32.5%";
				} else if (this.grid.heightNum == 4) {
					height = "24.2%";
				}
				style = `height: ${height};`;
				// console.log("getGridRowStyle", style);
				return style;
			},
			getGridCellStyle(rowId, colId) {
				let style = "";
				let width = "";
				let pos = "";
				const orderNum = this.getCellOrderNum(rowId, colId);
				const rs = tools.objArrGetObjByValue(this.grid.detailRs, "orderNum", orderNum);
				// console.log("[getGridCellStyle] rs ", rs);

				if (this.grid.widthNum == 1) {
					width = "98%";
					pos = "100%";
				} else if (this.grid.widthNum == 2) {
					width = "49%";
					pos = "100%";
				} else if (this.grid.widthNum == 3) {
					width = "32.5%";
					pos = "50%";
				} else if (this.grid.widthNum == 4) {
					width = "24.2%";
					pos = "33.33%";
				}
				style = `width: ${width};`;

				// if (this.grid.state < 3 && rs && rs.isComplete) {
				if (rs && rs.isComplete) {
					style += `background-image: url("${this.grid.actualImgPic}");`;
					style += `background-position: calc(${pos} * ${colId-1}) calc(${pos} * ${rowId-1});`;
				}
				// console.log("getGridCellStyle", style);

				return style;
			},
			cardConfigQueryCallback(cardconfig) {
				this.loadConfig(cardconfig);
				this.gridsQuery();
			},
			loadConfig(cardconfig) {
				cardconfig = cardfunc.parseCardConfig(cardconfig);
				// console.log("[loadCardConfig] cardconfig:", cardconfig);

				// 加载卡片通用配置
				if (cardconfig.common != undefined) {
					cardfunc.loadCardCommonConfig(cardconfig.common);
				}

				// -------- 加载当前页面的配置 --------

				const config = cardfunc.parseCardConfig(cardconfig[this.pageName]);
				// console.log("[loadConfig] config_page:", config);
				if (config == undefined || config == null) {
					this.pageReady = true;
					return;
				}

				// 加载CSS样式
				const css = config.css;
				if (css != undefined && css.length > 0) {
					tools.loadCssCode(css);
				}

				// 加载介绍内容
				const introduce = config.introduce;
				if (introduce != undefined) {
					if (introduce.title != undefined) {
						this.introduce.title = introduce.title;
					}
					if (introduce.content != undefined) {
						this.introduce.content = introduce.content;
					}
				}

				// 加载活动规则
				const activityRules = config.activityRules;
				if (activityRules != undefined) {
					if (activityRules.title != undefined) {
						this.activityRules.title = activityRules.title;
					}
					if (activityRules.content != undefined) {
						this.activityRules.content = activityRules.content;
					}
				}
				
				this.pageReady = true;
			},
			// 网格卡片信息查询
			gridsQuery() {
				uni.request({
					url: apiGridsQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("gridsQuery", res);
						const data = res.data.data;
						this.compId = data.compId,
							this.compName = data.compName;
						this.grid.widthNum = data.widthNum;
						this.grid.heightNum = data.heightNum;
						this.grid.maskImgPic = data.maskImgPic;
						this.grid.actualImgPic = data.actualImgPic;
						this.grid.state = data.state;
						this.grid.detailRs = data.detailRs;

						this.getUserJoinCardQuery();
					},
					fail: (err) => {
						console.log("gridsQuery err", err)
					},
				});
			},
			// 用户是否已经报名卡片对应赛事查询
			getUserJoinCardQuery() {
				uni.request({
					url: apiUserJoinCardQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("getUserJoinCardQuery", res)
						if (checkResCode(res)) {
							const data = res.data.data;
							this.isJoin = data.isJoin;
							if (!this.isJoin) { // 未报名，则自动给用户报名
								this.onlineMcSignUp();
							}
						}
					},
					fail: (err) => {
						console.log("getUserJoinCardQuery err", err)
					},
				});
			},
			// 线上赛报名
			onlineMcSignUp() {
				uni.request({
					url: apiOnlineMcSignUp,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcId: this.compId,
						// coiId: 0,
						// selectTeam: 0,
						// nickName: ''
					},
					success: (res) => {
						// console.log("onlineMcSignUp", res);

						if (checkResCode(res)) {
							// uni.showToast({
							// 	title: '比赛报名成功！',
							// 	icon: 'none',
							// 	duration: 3000
							// });
						}
					},
					fail: (err) => {
						console.log("onlineMcSignUp err", err);
						uni.showToast({
							title: '出错了，报名失败',
							icon: 'none',
							duration: 3000
						});
					},
				});
			},
			onCellClick(rowId, colId) {
				this.sltCellOrderNum = this.getCellOrderNum(rowId, colId);
				this.sltCellRs = tools.objArrGetObjByValue(this.grid.detailRs, "orderNum", this.sltCellOrderNum);
				if (this.sltCellRs && this.sltCellRs.ocaId > 0) {
					this.popupDataList = [{
						"type": 11,
						"data": {
							"title": this.sltCellRs.showName,
							"img": this.sltCellRs.popupImg,
							"content": this.sltCellRs.description,
							"point": {
								"longitude": this.sltCellRs.longitude,
								"latitude": this.sltCellRs.latitude,
								"name": this.sltCellRs.showName
							}
						}
					}];
					this.$nextTick(() => {
						this.$refs.mypopup.popupOpen();
					});
				} else {
					uni.showToast({
						icon: "none",
						title: "该格子未绑定赛事活动"
					})
				}
			},
			startGame() {
				if (this.sltCellRs) {
					const url = `action://to_detail/?id=${this.sltCellRs.ocaId}&matchType=${this.sltCellRs.mcType}`;
					tools.appAction(url);
				}
			},
			btnBack() {
				const url = `action://to_home/`;
				tools.appAction(url);
			},
			btnInfo() {
				this.$refs.mypopup.popupOpen();
			}
		}
	}
</script>

<style scoped>
	.content {
		width: 100vw;
		min-height: 100vh;
	}

	.page-top {
		width: 100%;
		height: 60px;
		padding-top: 36px;
		justify-content: space-between;
		background: linear-gradient(135deg, #FFEF9E 0%, #FFFCF2 45.14%, #FFF4D4 100%);
	}

	.topbar-color {
		color: #000000;
	}

	.main {
		width: 88%;
		min-height: 300px;
		justify-content: space-around;
	}

	.mt-content {
		margin: 20px 0px;
		font-size: 20px;
		font-weight: 400;
		color: #333333;
	}

	.grid {
		width: 90vw;
		height: 90vw;
		border-radius: 10px;
		border: #FFC300 solid 10px;
		background-repeat: no-repeat;
		background-position: 2px 2px;
		background-size: calc(90vw - 4px) calc(90vw - 4px);
	}

	.grid-row {
		width: 100%;
	}

	.grid-cell {
		position: relative;
		height: 100%;
		background-repeat: no-repeat;
		background-size: calc(90vw - 4px) calc(90vw - 4px);
	}

	.cell-name {
		position: absolute;
		left: 5px;
		bottom: 2px;
		font-size: 12px;
		font-weight: 400;
	}

	.cell-name-uncomplete {
		color: #CF6B00;
	}

	.cell-name-complete {
		color: #CF6B00;
	}
		
	.introduce {
		width: 96%;
		margin-top: 10px;
		margin-bottom: 10px;
		align-items: flex-start;
		justify-content: space-around;
	}

	.introduce-title {
		color: #333333;
		font-size: 20px;
		line-height: 50px;
		font-family: Source Han Sans CN;
	}

	.introduce-content {
		color: #333333;
		font-size: 16px;
		line-height: 23px;
		font-family: Source Han Sans CN;
	}
	
	.activityRules {
		width: 96%;
		margin-top: 5px;
		margin-bottom: 10px;
		padding: 10px 15px;
		align-items: flex-start;
		justify-content: space-around;
		border-radius: 9px;
		background: #FAF5E6;
	}
	
	.activityRules-title {
		color: #333333;
		font-size: 16px;
		line-height: 25px;
		font-weight: 500;
		font-family: Source Han Sans CN;
	}
	
	.activityRules-content {
		color: #333333;
		font-size: 14px;
		line-height: 23px;
		font-family: Source Han Sans CN;
	}
</style>