<!-- 
[商品兑换] 样式1 - 商品详情
http://localhost:5173/card/#/pages/exchange/style1/goodsDetail
https://oss-mbh5.colormaprun.com/card/#/pages/exchange/style1/goodsDetail
 -->
<template>
	<view class="body">
		<view v-if="pageReady" class="content uni-column">
			<view class="uni-column exchg-top">
				<my-topbar :exchangeTitle="exchangeTitle" ruleLable="兑换地点" class="exchgbar-color" @btnBackClick="btnBack"
					@btnInfoClick="btnInfo"></my-topbar>

				<view class="top-content">
					<view class="scoreBox uni-row uni-jcsb">
						<view class="scoreBox-score uni-row">
							<view class="scoreBox-title">剩余积分</view>
							<image class="scoreBox-score-ico" mode="aspectFit" src="/static/exchange/score.png"></image>
							<view class="scoreBox-score-value">{{scoreRs.score}}</view>
						</view>
						<view class="scoreBox-expire">{{fmtTime(scoreRs.extTime)}} 到期</view>
					</view>
				</view>
			</view>

			<view class="main uni-column">
				<view class="goodsBox uni-column">
					<view class="goods-title">{{goodsRs.goodsName}}</view>
					<image class="goods-pic" mode="aspectFit" :src="goodsRs.goodsPic"></image>
					
					<view class="goods-priceBox uni-row uni-jcsb">
						<view class="goods-priceBox-text uni-row">库存 {{goodsRs.goodsLeftNum}}<view v-if="goodsRs.goodsUnit.length > 0">{{goodsRs.goodsUnit}}</view></view>
						<view class="uni-row">
							<image class="goods-scoreIco" mode="aspectFit" src="/static/exchange/score2.png"></image>
							<view class="goods-priceBox-text uni-row">{{goodsRs.corrScore}}积分<view v-if="goodsRs.goodsUnit.length > 0">/{{goodsRs.goodsUnit}}</view></view>
						</view>
					</view>
					
					<view class="goods-exchNumBox">
						<uni-number-box :min="1" :max="exchMaxNum" v-model="exchNum"></uni-number-box>
					</view>
					
					<view class="goods-introduce uni-column uni-ais">
						<view class="goods-introduce-title">商品介绍：</view>
						<view class="goods-introduce-content" v-html="goodsRs.goodsDesc"></view>
					</view>
					
					<view class="goods-exchDesc" v-html="goodsRs.exchDesc"></view>
				</view>
				
				<button class="btnExchange" @click="btnExchange">兑 换</button>
			</view>
			
			<my-popup ref="mypopupExchg" :config="cardConfigData.popupExchgConfig" :dataList="cardConfigData.popupExchgList"></my-popup>
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import cardfunc from '../../../common/cardfunc';
	import {
		localCardConfig
	} from "./cardconfig/test.js";
	import {
		token,
		apiOnlineScoreQuery,
		apiCanExchangeGoodsDetail,
		apiScoreExchangeGoods,
		checkResCode
	} from '/common/api';

	export default {
		data() {
			return {
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				pageName: "goodsDetail",
				firstEnterKey: 'firstEnter-exchange-style1',
				queryObj: {},
				queryString: "",
				token: "",
				exchangeTitle: "商品详情",

				ecId: 0, // 卡片id
				goodsId: 0, // 商品id
				exchNum: 0, // 兑换数量
				exchMaxNum: 0, // 个人积分所能兑换的最大数量
				scoreRs: {
					score: 260, // 可用积分
					extTime: 0, // 积分到期时间戳
				},
				/* goodsRs: {
					goodsName: "", // 商品名称
					goodsPic: "", // 商品图片
					goodsLeftNum: 0, // 商品剩余数量
					corrScore: 0, // 兑换所需积分
					goodsUnit: "", // 商品单位
					goodsDesc: "", // 商品介绍
					exchDesc: "", // 兑换说明
					exchLimit: 0, // 个人兑换数量上限,0无限制

				} */
				goodsRs: {
					goodsName: "正宗农家土鸡蛋1枚", // 商品名称
					goodsPic: "/static/common/jidanquan.png", // 商品图片
					goodsLeftNum: 9, // 商品剩余数量
					corrScore: 20, // 兑换所需积分
					goodsUnit: "个", // 商品单位
					goodsDesc: "还记得小时候，奶奶亲手做的荷包蛋吗？那金黄的蛋黄，香浓的味道，至今让人回味无穷。我们的土鸡蛋，延续了传统的养殖方式，每一枚鸡蛋都承载着浓浓的乡愁。让您重温儿时的美好记忆。", // 商品介绍
					exchDesc: "兑换说明：<br>只限本次赛事积分在指定商超兑换。<br>有效期说明：<br>赛事结束后30天内可以兑换，过期失效！", // 兑换说明
					exchLimit: 3, // 个人兑换数量上限,0无限制
				}
			}
		},
		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;
			this.goodsId = query["goodsId"] ?? 0;

			this.firstEnterKey += "-" + this.ecId;
			console.log("firstEnterKey:", this.firstEnterKey);

			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
			
			this.onlineScoreQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {},
		onShow() {},
		onUnload() {},
		methods: {
			// 计算个人积分所能兑换的最大数量
			computeExchMaxNum() {
				if(!(this.scoreRs.score > 0 && this.goodsRs.corrScore > 0)) {
					return;
				}
				let maxNum = Math.floor(this.scoreRs.score / this.goodsRs.corrScore);
				if (this.goodsRs.exchLimit > 0 && maxNum > this.goodsRs.exchLimit) {
					maxNum = this.goodsRs.exchLimit;
				}
				if (maxNum > 0 && this.exchNum == 0) {
					this.exchNum = 1;
				}
				this.exchMaxNum = parseInt(maxNum);
			},
			fmtTime(timestamp, type = 3) {
				return tools.timestampToTime(timestamp * 1000, type);
			},
			cardConfigQueryCallback(cardconfig) {
				this.loadConfig(cardconfig);
				// setTimeout(this.dealFirstEnter, 500);
			},
			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);
				}

				this.pageReady = true;
			},
			// 卡片内可用积分查询
			onlineScoreQuery() {
				uni.request({
					url: apiOnlineScoreQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("onlineScoreQuery", res);
						if (checkResCode(res)) {
							this.scoreRs = res.data.data;
							this.canExchangeGoodsDetail();
						}
					},
					fail: (err) => {
						console.log("onlineScoreQuery err", err);
					},
				});
			},
			// 积分可兑换商品详情
			canExchangeGoodsDetail() {
				uni.request({
					url: apiCanExchangeGoodsDetail,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId,
						goodsId: this.goodsId
					},
					success: (res) => {
						console.log("canExchangeGoodsDetail", res);
						this.goodsRs = res.data.data;
						this.computeExchMaxNum();
					},
					fail: (err) => {
						console.log("canExchangeGoodsDetail err", err);
					},
				});
			},
			// 积分兑换商品
			scoreExchangeGoods() {
				uni.request({
					url: apiScoreExchangeGoods,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId,
						goodsId: this.goodsId,
						exchNum: this.exchNum
					},
					success: (res) => {
						// console.log("scoreExchangeGoods", res);
						if (checkResCode(res, "兑换失败: ")) {
							uni.showToast({
								title: '商品兑换成功！',
								icon: 'none',
								duration: 3000
							});
							
							this.onlineScoreQuery();
						
							/* setTimeout(() => {
								// const url = "/pages/exchange/style1/goodsList?" + this.queryString;
								// tools.appAction(url, "uni.navigateTo");
								tools.appAction("reload");
							}, 2000); */
						}
					},
					fail: (err) => {
						console.log("scoreExchangeGoods err", err);
					}
				});
			},
			btnExchange() {
				if (!(this.exchNum > 0)) {
					uni.showToast({
						title: '请输入兑换数量',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				let that = this;
				uni.showModal({
					title: '兑换',
					content: `兑换数量：${this.exchNum}   消耗积分：${this.exchNum * this.goodsRs.corrScore}\r\n\r\n您确定要兑换吗？`,
					confirmText: '确定', //确定文本的文字
					cancelText: '取消', //确定文本的文字
					showCancel: true, //没有取消按钮的弹框
					success: function(res) {
						if (res.confirm) {
							that.scoreExchangeGoods();
						} else if (res.cancel) {
						}
					}
				})
			},
			btnBack() {
				const url = "/pages/exchange/style1/goodsList?" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			btnInfo() {
				this.$refs.mypopupExchg.popupOpen();
			},
		}
	}
</script>

<style scoped>
	.content {
		width: 100vw;
		height: 100vh;
		background: linear-gradient(119.37deg, #FFEF9E 0%, #FFEEDB 31.6%, #FFF3C2 100%);
	}

	.exchg-top {
		width: 100%;
		/* height: 170px; */
		padding-top: 36px;
		justify-content: space-between;
	}
	
	.exchgbar-color {
		/* color: #000000; */
	}
	
	.main {
		width: 100%;
		flex-grow: 1;
		margin-top: 10px;
		padding-bottom: 20px;
		border-radius: 19px 19px 0px 0px;
		border: 1px solid #FFFFFF;
		background: #F6F6F6;
	}

	.top-content {
		position: relative;
		width: 90%;
		height: 30px;
		margin-top: 10px;
	}

	.scoreBox {
		width: 100%;
		height: 80%;
		margin-top: 10px;
		/* background-color: #A65600; */
	}

	.scoreBox-score {
		font-size: 12px;
		font-weight: 500;
		color: #A65600;
	}

	.scoreBox-score-ico {
		width: 19px;
		height: 15px;
	}

	.scoreBox-title {
		margin-right: 10px;
		font-size: 12px;
		font-weight: 550;
		color: #000000;
	}

	.scoreBox-score-value {
		margin: 0 6px;
		font-size: 18px;
		font-weight: 700;
	}

	.scoreBox-score-unite {
		margin-top: 12px;
	}

	.scoreBox-expire {
		font-size: 12px;
		font-weight: 500;
		color: #A6A6A6;
	}
	
	.goodsBox {
		width: 90%;
		margin-top: 20px;
		/* background-color: #FFEF9E; */
	}

	.goods-title {
		font-size: 16px;
		font-weight: 500;
	}
	
	.goods-pic {
		width: 90%;
		height: 160px;
		margin: 20px 0;
	}
	
	.goods-priceBox {
		width: 200px;
		height: 25px;
		padding: 2px 12px;
		border-radius: 3px;
		background: #FFC300;
	}
	
	.goods-scoreIco {
		width: 22px;
		height: 14px;
		margin-right: 3px;
	}
	
	.goods-priceBox-text {
		font-size: 14px;
		white-space: nowrap;
	}
	
	.goods-exchNumBox {
		margin: 20px;
	}
	
	::v-deep .uni-numbox-btns {
		width: 10px;
		border: 1px solid #A6A6A6;
	}
	
	.goods-introduce {
		width: 90%;
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
	}
	
	.goods-introduce-title {
		width: 100%;
		margin-bottom: 10px;
		text-align: left;
		font-weight: 550;
	}
	
	.goods-exchDesc {
		width: 90%;
		margin-top: 20px;
		padding: 10px;
		border-radius: 5px;
		background: #FFF8E3;
		font-size: 12px;
		font-weight: 400;
		line-height: 20px;
	}
	
	.btnExchange {
		width: 289px;
		height: 53px;
		margin-top: 30px;
		margin-bottom: 20px;
		border-radius: 27px;
		background: linear-gradient(117.53deg, #FFCD29 0%, #FFE694 42.36%, #FFC508 100%);
		
		font-size: 18px;
		font-weight: 550;
		line-height: 53px;
		color: #A65600;
	}
	
</style>