<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		computed,
	} from 'vue'
	import {
		onReachBottom,
		onPullDownRefresh,
		onShow,
		onLoad,
		onReady,
	} from '@dcloudio/uni-app';
	// 地址
	import JyCommodityAddress from '@/components/public/jy-commodity-address'
	// 店铺信息
	import JyShopInformation from '@/components/public/jy-shop-information'
	// 商品信息
	import JyCommodityInformation from '@/components/public/jy-commodity-information'
	// api
	import api from '@/api/index.js'
	// util
	import util from '@/common/js/util';
	// 二级支付
	import secondPwd from '@/components/mine/payPwd.vue'
	const {
		proxy
	} = getCurrentInstance()
	// 订单id
	const orderId = ref('')
	// 订单详情
	const detail = reactive({
		createTime: '',
		coutDownTime: '',
		orderDetailList: [],
	})
	// 支付方式列表
	const paytypeList = reactive([])
	// 支付方式
	const paytype = ref('')
	// 支付单项
	const payTypeItem = computed(() => paytypeList.find(item => item.paymentMethod == paytype.value) || {})
	// 当前时间
	const date = reactive(new Date())

	onLoad((option) => {
		if (option.orderId) orderId.value = option.orderId
		// 获取支付顺序
		getPaymentOrder()
		// 获取订单详情
		getDetail()
	})

	// 获取支付顺序
	function getPaymentOrder() {
		api.mine.getPaymentOrder({}).then(res => {
			if (res.code == 200) {
				Object.assign(paytypeList, res.data.map(item => {
					item.name = util.config.payType[item.paymentMethod].name
					return item
				}))
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}

	// 获取订单详情
	function getDetail() {
		api.shop.getOrderDetail({
			query: {
				id: orderId.value
			}
		}).then(res => {
			if (res.code == 200) {
				const result = res.data
				let time = new Date(result.createTime)
				// 
				result.createTime = new Date(result.createTime).valueOf()
				result.coutDownTime = time.setMinutes(time.getMinutes() + 30).valueOf()
				// 如果未到倒计时 计算相差时间
				if (date.valueOf() < result.coutDownTime) {
					let timeDiff = timeDifference(new Date(), result.coutDownTime)
					result.hours = timeDiff.hours
					result.minutes = timeDiff.minutes
					result.seconds = timeDiff.seconds
				}

				Object.assign(detail, {}, result)
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}

	/**
	 * 相差时间
	 * @param {Object} startTimeStr 开始时间
	 * @param {Object} endTimeStr 结束时间
	 */
	function timeDifference(startTimeStr, endTimeStr) {
		// 将时间字符串转换为 Date 对象
		let startDate = new Date(startTimeStr);
		let endDate = new Date(endTimeStr);

		// 计算时间差（毫秒）
		let timeDiff = endDate - startDate;

		// 计算小时、分钟和秒
		let hours = Math.floor(timeDiff / (1000 * 60 * 60));
		let minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
		let seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

		return {
			hours,
			minutes,
			seconds
		}
	}

	// 选择支付方式
	function handlePayment(ev) {
		let value = ev.detail.value
		if (value == paytype.value) return
		paytype.value = value
	}

	// 提交
	function handleSubmit() {
		api.shop.orderPay({
			query: {
				payType: paytype.value,
				addrId: detail.address.id,
			},
			data: [
				orderId.value,
			],
		}).then(res => {
			if (res.code == 200) {
				// 触发自定义事件
				uni.$off('updateOrderList')
				uni.$off('updateOrderDetail')
				uni.navigateBack()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}

	// 打开密码
	function showPwd() {
		if (!paytype.value) {
			util.alert('请选择支付方式')
			return
		}

		// 打开
		proxy.$refs.secondPwdRef.open()
	}
</script>

<template>
	<view class="app">
		<view class="bfff p25">
			<!-- 地址 -->
			<JyCommodityAddress v-model:address="detail.address" />
		</view>

		<!-- 店铺和商家信息 -->
		<view class="detail oh mtb20 plr30 bfff">
			<!-- 店铺 -->
			<view class="store mtb20 plr10 df aic">
				<image class="avaar wh60 br10" :src="detail.merImg" mode="aspectFill" />
				<view class="name ml20 c333 f28">{{detail.merName}}</view>
			</view>

			<!-- 商品信息 -->
			<view class="goods mtb20 plr10 df" v-for="(item,index) in detail.orderDetailList">
				<!-- 产品图 -->
				<image class="wh180 br10" :src="item.productInfo.sliderImage.split(',')[0]" mode="aspectFill" />
				<!-- 产品信息 -->
				<view class="f1 ml20 mr10">
					<view class="name f30 t2hd">{{item.productName}}</view>
					<view class="spec mt10 c999 f26">升级款 {{item.sku}}</view>
				</view>
				<!-- 其他 -->
				<view class="tar">
					<view class="price">
						<text class="f20">￥</text>
						<text class="f30">{{item.price}}</text>
					</view>
					<view class="c999 f28">x{{item.payNum}}</view>
				</view>
			</view>

			<!-- 应付 -->
			<view class="line df jcr aic ptb20 plr10">
				<text class="c333 f28">应付：</text>
				<text class="price f20 cFF9B27">￥</text>
				<text class="price f32 cFF9B27">{{detail.totalPrice}}</text>
			</view>
		</view>

		<!-- 支付方式选择 -->
		<radio-group class="payType mtb20 plr20 bfff" @change="handlePayment">
			<label class="item rows ptb20 plr10" v-for="(item, index) in paytypeList" :key="item.paymentMethod">
				<image :src="item.icon" class="wh60" mode="aspectFit" />
				<view class="f1 mlr20 c333 f28">{{item.name}}</view>
				<radio class="radio" color="#4cd964" :value="item.paymentMethod"
					:checked="item.paymentMethod === paytype" />
			</label>
		</radio-group>

		<!-- 订单备注 -->
		<view class="remark mtb20 ptb20 plr20 bfff" v-if="0">
			<view class="title f30">订单备注</view>
			<view class="txtarea mt10">
				<uni-easyinput :inputBorder="false" type="textarea" placeholder="选填" />
			</view>
		</view>

		<view class="fill" style="height: 210rpx;" />

		<!-- 提交订单 -->
		<view class="footer df jcr plr20 bfff" v-if="detail.id">
			<view class="df aic">
				<text class="c333 f28">应付：</text>
				<text class="price f20 cFF9B27">￥</text>
				<text class="price f36 cFF9B27">{{detail.totalPrice}}</text>
			</view>

			<template v-if="date.valueOf() < detail.coutDownTime">
				<view class="btn ti primary ml20 plr60" @click="showPwd">
					<text class="cfff f24">继续付款</text>
					<view class="df cfff aic f20">
						<text class="">剩余：</text>
						<uni-countdown splitorColor="#fff" color="#fff" :show-day="false" :hour="detail.hours"
							:minute="detail.minutes" :second="detail.seconds" @timeup="getDetail" />
					</view>
				</view>
			</template>
			<template v-else>
				<view class="btn disabled  ml20 plr60">订单已过期</view>
			</template>
		</view>
	</view>

	<!-- 二级密码 -->
	<secondPwd ref="secondPwdRef" :check="true" @confirm="handleSubmit" :unitKey="paytype" :price="detail.totalPrice" />
</template>

<style lang="scss" scoped>
	// 详情
	.detail {
		.line {
			border-top: 2rpx solid #eee;
		}
	}

	// 支付方式
	.payType {
		.item+.item {
			border-top: 2rpx solid #eee;
		}

		// 
		.radio {
			transform: scale(.7);
		}
	}
</style>