<template>
	<view>
		<view class="goods">
			<image :src="detail.image" style="width: 100vw;" mode="widthFix"></image>
			<view class="title">
				<view class="text-bold">{{detail.name}}</view>
				<view class="padding-tb-xs">
					<text class="text-sm">￥</text>
					<text class="">{{detail.cashValue}} / {{detail.equalPoints}}积分</text>
				</view>
				<block  v-if="!$u.test.isEmpty(detail.description)">
					<view class="text-sm text-gray">产品说明：{{detail.description}}</view>
				</block>
			</view>
		</view>

		<block v-if="exchangeShow">
			<navigator :url="'../mine/order/address?userId='+userId" hover-class="none"
				class="container flex align-center justify-between" style="border-bottom: 1rpx solid #efefef;">
				<view class="flex padding align-center">
					<image src="/static/address.png" style="width: 65upx;height: 65upx;"></image>
					<view class="padding-left text-sm" v-if="!$u.test.isEmpty(address)">
						<view style="font-size: 28upx;font-family: PingFang SC;font-weight: 800;color: #000000;">
							{{address.consignee}} {{address.phone}}
						</view>
						<view class="text-gray">{{address.area}} {{address.detail}}</view>
					</view>
					<view class="padding-left"
						style="font-size: 28upx;font-family: PingFang SC;font-weight: 800;color: #000000;" v-else>
						请选择收货地址</view>
				</view>
				<view class="padding">
					<u-icon name="arrow-right" color="#d4d4d4"></u-icon>
				</view>
			</navigator>

			<view class="text-red  padding-sm">
				<view class="padding-tb-xs">
					1：请选择要兑换商品的组合方式
				</view>
				<view class="">
					2：组合合计达到 {{detail.cashValue}} 元即可兑换
				</view>
			</view>

			<view class="padding-sm">


				<view class="flex padding-xs">
					<text class="flex justify-center align-center">热力值：</text>
					<u-number-box :disabled="$u.test.isEmpty(proportion.usableHot)" :step="otherStep"
						:positive-integer="otherPositive" @change="hotValueChange" :input-width="200" :min="0"
						:max="+proportion.usableHot" v-model="data.hotValue">
					</u-number-box>
					<view v-if="changeCash.hotCash!=0"
						class="padding-left-sm text-red flex justify-center align-center">
						=
						<text class="padding-left-sm ">{{changeCash.hotCash}} 元</text>
					</view>
				</view>

				<view class="flex padding-xs">
					<text class="flex justify-center align-center">积分值：</text>
					<u-number-box :disabled="$u.test.isEmpty(proportion.usablePoints)" :step="otherStep"
						:positive-integer="otherPositive" @change="pointsValueChange" :input-width="200" :min="0"
						:max="+proportion.usablePoints" v-model="data.pointsValue">
					</u-number-box>
					<view v-if="changeCash.pointsCash!=0"
						class="padding-left-sm text-red flex justify-center align-center">
						=
						<text class="padding-left-sm ">{{changeCash.pointsCash}} 元</text>
					</view>
				</view>
				<view style="padding-top: 20rpx;display: flex;flex-direction: column;">
					<text
						class="text-gray padding-top-sm">可用热力值为：{{proportion.usableHot || 0}}，价值{{ hotCashMul }}元</text>
					<text
						class="text-gray padding-top-sm">可用积分值为：{{proportion.usablePoints || 0}}，价值{{ pointsCashMul}}元</text>
				</view>
			</view>
		</block>

		<view class="" style="height: 140rpx;">

		</view>

		<view v-if="!exchangeShow" class="footer-fixed flex align-center justify-end padding bg-white"
			style="padding: 30rpx;;border-top: 1rpx solid #e5e5e5;z-index: 9;">
			<button class="cu-btn round text-white theme-bg-color" style="width: 180upx;height: 80upx;"
				@click="exchange">兑换</button>
		</view>

		<view v-else class="footer-fixed flex align-center justify-between  bg-white"
			style="border-top: 1rpx solid #e5e5e5;padding: 30rpx;z-index: 9;">
			<view class="text-red">
				<text>需支付现金</text>
				<text>￥</text>
				<text>{{cashValue}}</text>
			</view>
			<view>
				<button class="cu-btn round text-white theme-bg-color"
					style="width: 180upx;height: 80upx;margin-right: 10upx;" @click="confirm">兑换</button>
				<button @click="exchangeShow = false" class="cu-btn round line-gray"
					style="width: 180upx;height: 80upx;z-index: 99;">取消</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		appId
	} from '@/common/conf/config.js';
	import {
		authUrl
	} from '@/common/conf/config.js';
	import {
		getUrlParams
	} from '@/common/utils/utils.js';
	export default {
		data() {
			return {
				activityId: '',
				userId: '',
				id: '',
				proportion: {},
				pointsCashMul:null,
				hotCashMul:null,
				

				detail: {},
				address: {},
				exchangeShow: false,

				data: {
					cashValue: 0,
					hotValue: 0,
					pointsValue: 0
				},

				changeCash: {
					hotCash: 0,
					pointsCash: 0
				},

				cashStep: 1,
				cashPositive: true,
				otherStep: 10,
				otherPositive: true,
			}
		},
		onLoad(options) {
			this.id = options.id;
			this.activityId = options.activityId;
			if (this.$u.test.isEmpty(this.id)) {
				this.$u.toast('商品id不能为空')
				return
			}
			this.userId = uni.getStorageSync("userId");
			this.authorization();
			this.fetchGoodsDetail();
		},
		computed: {
			totalCash: {
				get() {
					let tmp=this.floatAdd(this.data.cashValue,this.changeCash.hotCash)
					let total = this.floatAdd(tmp,this.changeCash.pointsCash)  
					return total
				}
			},
			cashValue: {
				get() {
					let m = this.detail.cashValue
					let n = this.floatAdd(this.changeCash.hotCash,this.changeCash.pointsCash)
					let val = this.floatSub(m, n)
					if (val < 0) {
						this.$u.toast('不可以超过商品价格')
						return 0
					}
					this.data.cashValue = val
					return val
				}
			}
		},
		onShow() {
			this.getAddress()
		},
		methods: {
			floatAdd(arg1, arg2) {
				var r1,r2,m;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				return (arg1 * m + arg2 * m) / m;
			},
			floatSub(arg1, arg2) {
				var r1, r2, m, n;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				n = (r1 >= r2) ? r1 : r2;
				return ((arg1 * m - arg2 * m) / m).toFixed(n)
			},
			initStep() {
				let cashValue = parseFloat(this.detail.cashValue)
				let equalPoints = parseFloat(this.detail.equalPoints)
				if (cashValue < 1.0) {
					this.cashStep = 0.1
					this.cashPositive = false
				}
				if (equalPoints < 1.0) {
					this.otherStep = 0.1
					this.otherPositive = false
				}
				console.log(this.cashStep, this.otherStep);
			},
			getAddress() {
				this.$u.api.user.userAddress({
					userId: this.userId
				}).then(res => {
					this.address = res.records[0];
				})
			},
			fetchGoodsDetail() {
				this.$u.api.pointsGoods.list({
					id: this.id
				}).then(res => {
					this.detail = res.records[0];
					this.initStep()
				})
			},
			getUsableHotAndPoints() {
				let params = {
					activityId: this.activityId,
					userId: this.userId
				}
				this.$u.api.pointsGoods.getUsableHotAndPoints(params).then(res => {
					this.proportion = res
					this.pointsCashMul=this.numberMul(this.proportion.usablePoints,this.proportion.pointsProportion)
					this.hotCashMul=this.numberMul(this.proportion.usableHot,this.proportion.hotProportion)
				})
			},
			//计数器变化
			hotValueChange(item) {
				this.changeCash.hotCash = this.numberMul(item.value, this.proportion.hotProportion)
			},
			pointsValueChange(item) {
				this.changeCash.pointsCash = this.numberMul(item.value, this.proportion.pointsProportion)
			},
			async confirm() {
				if (this.$u.test.isEmpty(this.address) || this.$u.test.isEmpty(this.address.id)) {
					this.$u.toast('请选择地址')
					return;
				}
				let m=parseFloat(this.detail.cashValue)
				let n=parseFloat(this.totalCash)
				if (this.floatSub(m,n)!=parseFloat(0)) {
					uni.showToast({
						title: "总金额不等于商品所需金额",
						duration: 3000,
						icon: "none"
					})
					return;
				}
				
				if (!this.$u.test.isEmpty(parseFloat(this.data.cashValue))) {
					let orderId = new Date().getTime()
					//去支付,支付成功后
					let orderInfo = (await this.$u.api.yeePay.initOrder({
						"appId": appId,
						"channel": "WECHAT",
						"channelPromotionInfo": "",
						"channelSpecifiedInfo": "",
						"csUrl": "",
						"expiredTime": "",
						"fundProcessType": "",
						"goodsName": this.detail.name,
						"memo": "",
						"notifyUrl": "https://music.nanyue6688.com/ldt/api/yeePay/notify",
						"orderAmount": this.data.cashValue,
						"orderId": orderId,
						"payWay": "WECHAT_OFFIACCOUNT",
						"redirectUrl": "",
						"scene": "OFFLINE",
						"uniqueOrderNo": "",
						"userId": uni.getStorageSync("openid"),
						"userIp": "127.0.0.1"
					}));
					this.$u.api.boost.billRecord({
						orderId: orderId,
						payPath: encodeURIComponent(window.location.href),
						userId: this.userId,
						openId: uni.getStorageSync("openid"),
						activityId: this.activityId,
						price: this.data.cashValue,
						presentId: '',
						presentCount: '',
						relationId: this.id,
						type: 3,
						payStatus: 0,
					}).then(res => {
						if (typeof orderInfo.prePayTn != 'undefined') {
							//调起支付
							this.toPay(JSON.parse(orderInfo.prePayTn));
						}
					})
				} else {
					this.doConfirm()
				}

			},
			toPay(info) {
				WeixinJSBridge.invoke('getBrandWCPayRequest', info, (res) => {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						this.doConfirm();
						this.getUsableHotAndPoints()
					} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
						console.log("取消支付");
					} else {
						console.log(res.err_msg);
					}
				});
			},
			async doConfirm() {
				this.data.pointsGoodsId = this.id
				this.data.userId = this.userId
				let res = await this.$u.api.pointsGoods.exchange(this.data)
				if (res.code == 400) {
					uni.showToast({
						title: res.msg,
						duration: 3000,
						icon: "none"
					})
					return;
				}
				uni.showModal({
					title: "提示",
					content: "兑换成功,可到个人中心查看!",
					confirmColor: "#5a3ee8",
					showCancel: true,
					confirmText: "去查看",
					cancelText: "暂不查看",
					success: (res) => {
						this.getUsableHotAndPoints()
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/activityList/mine/pointsGoods/list"
							})
						}
					}
				})
			},
			numberMul(arg1, arg2) {
				var m = 0;
				var s1 = arg1.toString();
				var s2 = arg2.toString();
				try {
					m += s1.split(".")[1].length;
				} catch (e) {}
				try {
					m += s2.split(".")[1].length;
				} catch (e) {}

				return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
			},
			exchange() {
				if (this.$u.test.isEmpty(this.userId)) {
					let path = "pages/activityList/goods/detail?id=" + this.id + "&activityId=" + this.activityId
					window.location.href = authUrl(path);
				} else {
					this.exchangeShow = true;
					this.getUsableHotAndPoints()
					this.getAddress()
				}
			},
			async authorization() {
				let agenterId = uni.getStorageSync("agenterId")
				let params = getUrlParams(window.location.search);
				if (!this.$u.test.isEmpty(params.code)) {
					let res = await this.$u.api.wxInfo.getUserInfo({
						userCode: params.code
					});
					uni.setStorageSync("openid", res.openid);
					let datas = {
						nickName: res.nickname,
						avatar: res.headimgurl,
						gender: res.sex,
						openid: res.openid,
						unionid: res.unionid,
						province: res.province,
						city: res.city
					}
					if (!this.$u.test.isEmpty(agenterId)) {
						datas.agenterId = agenterId
					}
					let result = await this.$u.api.user.login(datas);
					if (result) {
						this.userId = result.id;
						uni.setStorageSync("userId", result.id);
					}
				}
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
	}

	.goods {
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #efefef;

		.title {
			padding-top: 10rpx;
			margin-left: 20rpx;
			font-size: 32rpx;
			color: #363636;
		}
	}
</style>
