<template>
	<view class="container">
		<up-navbar :title="navTitle" @leftClick="onback" placeholder></up-navbar>
		<view class="headStatus">
			<view class="status">

				<up-icon v-if="listinfo.status =='done'||listinfo.status =='unpaid'||!listinfo.id"
					name="checkmark-circle-fill" color="#03C061" size="23"></up-icon>
				<view class="statusName" v-if="listinfo.status == 'unpaid'||!listinfo.id">待支付</view>
				<view class="statusName" v-if="listinfo.status=='done'">已完成</view>
				<view class="statusName" v-if="listinfo.status=='refund'">退单</view>
				<view class="statusName" v-if="listinfo.status=='part-refund'">部分退单</view>
				<view class="statusName" v-if="listinfo.status=='cancelled'">取消订单</view>
			</view>
			<view class="time" v-if="listinfo.createTime">下单时间：{{ listinfo.createTime }}</view>
			<view class="time" v-if="listinfo.paidTime && (listinfo.status!='cancelled' ||listinfo.status!='unpaid')">
				付款时间：{{listinfo.paidTime}}
			</view>
		</view>

		<view class="wxQrcode" v-if="shopQrcode">
			<view class="left">
				<text class="title">扫码加好友，优惠多多</text>
				<text>优惠活动多</text>
				<text>充值有好礼</text>
				<text>会员享低价</text>
				<text>长按保存，微信内扫一扫加好友</text>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<u-image width="152" height="152" radius="16" :src="shopQrcode"></u-image>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<image style="height: 150rpx;width: 150rpx;" :src="shopQrcode" @longpress="saveImage(shopQrcode)"
				mode="aspectFill"></image>
			<!-- #endif -->
		</view>


		{{cartStore.orderCostSummary}}

		<!-- 详情 -->
		<orderInfo :useVipPrice="cartStore.useVipPrice" :packfee="packfee" :shifu="shifu" :nowCarts="cartStore.carts"
			ref="orderInfoAfterRef" :freeCheck="freeCheck" :listinfo="listinfo" :orderVIP="orderVIP"
			:ordershopUserInfo='ordershopUserInfo' @istype="istype" @clickPointsamount='clickPointsamount'
			@learcoupons="learcoupons" :isBwc='isBwc'>
		</orderInfo>
		<!-- 订单备注 -->
		<view class="orderInfo">
			<view class="">
				<view class="t">
					订单备注：
				</view>
				<view class="u-m-t-18 ">
					<up-textarea border="none" placeholder="请填写口味、偏好等要求" :type="'textarea'" v-model="listinfo.remark"
						:clearable="true" />
				</view>
			</view>
		</view>
		<!-- 霸王餐 -->
		<rechargeFree :freeDineConfig="orderVIP.freeDineConfig" :payAmount="listinfo.totalPrices"
			v-if="(listinfo.status == 'unpaid'||!listinfo.id) && orderVIP.freeDineConfig.enable"
			@changeFree="changeFree">
		</rechargeFree>
		<!-- 充值享优惠 -->
		<view v-else>
			<ChargeVue @updateChargeSel="updateChargeSel" @updateRechargeId="updateRechargeId"
				v-if="(listinfo.status == 'unpaid'||!listinfo.id)"></ChargeVue>
		</view>
		<!-- 支付方式 -->
		<paymentMethodes ref="paymentMethodref" :orderVIP="orderVIP" @groupChange="groupChange"
			:disablePayType="disablePayType" :changeFreeenable="isBwc" v-if="listinfo.status == 'unpaid'||!listinfo.id">
		</paymentMethodes>
		<view class="fixedview">
			<view class="flex-between" v-if="listinfo.status == 'unpaid'||!listinfo.id">
				<view class="fixedview_one flex-start">
					<view class="fixedview_oneone"> 实付金额： </view>
					<view class="fixedview_onetow" v-if="rechargeItem.id">
						<text>¥</text>{{rechargeItem.amount}}
					</view>
					<view class="fixedview_onetow" v-else>
						<text>¥</text>{{cartStore.orderCostSummary.finalPayAmount}}
					</view>
				</view>
				<view class="flex-colum-end u-flex u-flex-y-center">

					<view class="u-m-r-30 u-flex u-flex-y-center">
						<template v-if="ordershopUserInfo.registerType=='before'">
							<up-button shape="circle" v-if="!listinfo.id" @click="toJiacai" plain
								:custom-style="customStyle">
								<view class="u-flex u-flex-y-center">
									<image style="width: 40rpx;height: 40rpx;" src="@/static/icon/add-goods.png"
										mode=""></image>
									<text class="u-font-32 color-main u-m-l-16">加菜</text>
								</view>
							</up-button>
							<up-button shape="circle" v-if="listinfo.id&&listinfo.status=='unpaid'" plain
								@tap="cancelOrder" :custom-style="customStyle">
								<view class="u-flex u-flex-y-center">
									<text class="u-font-32 color-main u-m-l-16">取消订单</text>
								</view>
							</up-button>
						</template>
						<template v-else>
							<up-button v-if="!cartStore.isEmpty" shape="circle" @click="onlyCreateOrder" plain
								:custom-style="customStyle">
								<view class="u-flex u-flex-y-center">
									<!-- <image style="width: 40rpx;height: 40rpx;" src="@/static/icon/add-goods.png" mode=""></image> -->
									<text class="u-font-32 color-main ">仅下单</text>
								</view>
							</up-button>
							<up-button v-else shape="circle" @click="toJiacai" plain :custom-style="customStyle">
								<view class="u-flex u-flex-y-center">
									<image style="width: 40rpx;height: 40rpx;" src="@/static/icon/add-goods.png"
										mode=""></image>
									<text class="u-font-32 color-main u-m-l-16">加菜</text>
								</view>
							</up-button>
						</template>
					</view>
					<view class="fixedview_tow" @tap="$u.debounce(istoricalorders,1000)">
						{{paymentmethod.paymentBtnText}}
					</view>
					<!-- <view class="fixedview_tows" @tap="$u.debounce(APIputuserorderclick,1000)">
						取消订单
					</view> -->
				</view>
			</view>
		</view>
		<view style="width: 100%;height: 200rpx;color: #fff; color: #fff;">
		</view>
		<payPassword ref="payPasswordref" :isShow="ispws" @inputComplete="accountPayevent" @close="ispws = false" />
	</view>
</template>
<script setup>
	import {
		back
	} from '@/utils/uniapp.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		BigNumber
	} from 'bignumber.js';
	import ChargeVue from './components/charge.vue';
	import {
		pay
	} from '@/utils/pay.js'
	import * as UTILS from '@/utils/goods-utils.js'
	import {
		findCoupon
	} from '@/common/api/market/coupon.js';

	function onback() {
		closeSocket()
		back()
	}
	const customStyle = {
		'width': '180rpx',
		'height': '70rpx',
		'background': 'FFFFFF',
		'border-radius': '106rpx',
		'border': '2rpx solid #E8AD7B'
	}
	import _ from "lodash";
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted,
		watchEffect,
		nextTick,
		watch,
		onBeforeMount,
		onBeforeUnmount
	} from 'vue';
	import {
		getTableInfo
	} from '@/common/api/shop/index.js'
	import {
		APIgetOrderById,
		APIputuserorder,
		APIhistoryOrder,
		rechargePayOrder,
		APIcancelOrder
	} from '@/common/api/order/index.js'
	import {
		APIusershopInfodetail,
		APIshopUserInfo
	} from '@/common/api/member.js'
	import {
		APImemberPointsmyPoints,
		APImemberPointscalcUsablePoints
	} from '@/common/api/shop/index.js'
	import {
		useCartsStore
	} from '@/stores/carts.js';
	import {
		useWebSocket
	} from '@/stores/carts-websocket.js';

	const cartStore = useCartsStore()



	const disablePayType = ref([])
	//充值相关
	const rechargeItem = ref({
		id: ''
	})
	const rechargeId = ref(null)

	function updateRechargeId(e) {
		rechargeId.value = e
	}

	function updateChargeSel(e) {
		rechargeItem.value = e
	}
	watch(() => rechargeItem.value.id, (newval) => {
		//充值并付款时只能微信支付
		if (newval) {
			disablePayType.value = ['余额支付']
			paymentMethodref.value.groupChanges(2)
		} else {
			disablePayType.value = []
		}
	})

	async function onMessage(Message) {
		cartStore.onMessage(Message, cartsSocket)
		listinfo.totalPrices = historyTotalPrices * 1 + cartStore.totalPrice * 1
		if (Message.operate_type == "init") {
			youhuiReset()
		}
		if (Message.operate_type == "cleanup") {
			listinfo.totalCost = 0;
			youhuiReset()
			if (listinfo.id) {
				let res = await APIgetOrderById({
					orderId: listinfo.id
				})
				console.log('onMessage:APIgetOrderById', res);
				if (res) {
					// cartStore.carts=[];
					// cartStore.setOldOrder(res)
				}
				if (noPayStatus[res.status]) {
					uni.showToast({
						title: noPayStatus[res.status],
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1000);
					return;
				}
			}
		}
		if (Message.operate_type == "del") {
			youhuiReset()
		}
		if (Message.operate_type == "edit") {
			youhuiReset()
		}
		if (Message.operate_type == 'clearOrder') {
			youhuiReset()
		}
		if (Message.type == 'product' && Message.data_type == 'product_update' && Message
			.operate_type == 'product_update') {
			youhuiReset()
		}
		return Message
	}
	let cartsSocket = null
	cartStore.goodsInit()
	const socketInitPar = {
		type: 'shopping',
		operate_type: 'init',
		table_code: uni.cache.get('tableCode'),
		shop_id: uni.cache.get('shopId'),
	}

	function socketInit() {
		cartsSocket = useWebSocket();
		cartsSocket.connect(socketInitPar, onMessage);
	}
	const noPayStatus = {
		cancelled: "订单已取消",
		done: "订单已关闭",
	};



	function youhuiReset() {
		listinfo.pointsDiscountAmount = 0;
		listinfo.pointsNum = 0;
		listinfo.pointsDiscountAmount = 0
		listinfo.Productroll = 0
		uniqueIds.value = []
		try {
			orderInfoAfterRef.value?.IntegralInputclose();
		} catch {

		}
	}


	// 结账管理
	import {
		Memberpay
	} from '@/stores/pay.js';

	const storeMemberpay = Memberpay();



	import {
		productStore
	} from '@/stores/user.js';
	const storeuser = productStore();

	import payPassword from '@/components/payPassword.vue'
	import orderInfo from './components/orderInfo.vue'
	// import orderInfoBefore from '../components/orderInfoBefore.vue'
	import rechargeFree from './components/rechargeFree.vue'
	import paymentMethodes from '@/components/paymentMethod.vue'; //支付方式
	import {
		onShow,
		onBackPress
	} from '@dcloudio/uni-app';
	import {
		onHide
	} from '@dcloudio/uni-app';
	// 输入支付密码
	const ispws = ref(false)


	// 会员信息
	const orderVIP = ref(uni.cache.get('orderVIP'))
	// 商品订单关联的店铺信息
	const ordershopUserInfo = ref(uni.cache.get('shopInfo'))


	cartStore.updateData('orderVIP', orderVIP.value)
	cartStore.updateData('shopInfo', ordershopUserInfo.value)
	// 是否显示商家二维码信息
	const shopQrcode = ref(ordershopUserInfo.shopInfo || false)

	// 霸王餐
	const isBwc = ref(false)
	// 订单详情
	const listinfo = reactive({
		combinedArray: [],
		Productroll: 0,
		coupondiscountAmount: 0,
		pointsDiscountAmount: 0,
		packFeess: 0,
		totalPrices: 0,
		Seatcharge: 0,
		pointsNum: 0,
		id: null
	})



	//判断是否是打包商品
	const is_type = ref(0)
	//打包商品切换
	const istype = (newValue) => {
		is_type.value = newValue;
	};
	//积分

	const freeCheck = ref(false)
	let backtimer = null
	let historyTotalPrices = 0;
	// * 获取订单详情接口
	const orderorderInfo = async () => {
		console.log('listinfo.id', listinfo.id);
		let res = listinfo.id ? await APIgetOrderById({
			orderId: listinfo.id
		}) : await APIhistoryOrder({
			tableCode: options.tableCode
		})
		if (res && res.tableCode) {
			socketInitPar.table_code = res.tableCode
			let tableRes = await getTableInfo({
				tableCode: options.tableCode
			})
			console.log(tableRes);
			listinfo.tableName = tableRes.name;
		} else {
			if (options.tableCode) {
				socketInitPar.table_code = options.tableCode
				let tableRes = await getTableInfo({
					tableCode: options.tableCode
				})
				console.log(tableRes);
				listinfo.tableName = tableRes.name;
			}
		}
		cartStore.setOldOrder(res);
		socketInit()
		console.log(res);

		getOrderInfoAfterCalcInit(res)
	}

	//拿到订单数据后续初始化处理
	function getOrderInfoAfterCalcInit(res) {
		if (res && res.id) {
			Object.assign(listinfo, res);
			// 历史订单
			if (listinfo.detailMap) {
				let combinedArray = [];
				for (const key in listinfo.detailMap) {
					if (listinfo.detailMap.hasOwnProperty(key)) {
						let subArray = listinfo.detailMap[key];
						combinedArray = [...combinedArray, ...subArray]
					}
				}
				listinfo.combinedArray = combinedArray
				listinfo.packFeess = cartStore.getTotalPackFee(listinfo.combinedArray)
				// 计算购物车商品费用
				historyTotalPrices = cartStore.getTotalTotalPrices(listinfo
					.combinedArray, isBwc.value) * 1

				listinfo.totalPrices = historyTotalPrices + cartStore.totalPrice * 1
				// 餐位费listinfo.seatNum
				listinfo.Seatcharge = cartStore.getTotalSeatcharge(listinfo.seatNum)
			}
			if (listinfo.discountInfo) {
				const discountObj = JSON.parse(listinfo.discountInfo);
				const tempArray = [];
				for (const [key, value] of Object.entries(discountObj)) {
					tempArray.push({
						name: key,
						amount: value
					});
				}
				listinfo.discountInfo = tempArray;
			}
			// 回填先质控
			listinfo.pointsDiscountAmount = 0
			// console.log(listinfo)

		} else {
			listinfo.totalPrices = cartStore.totalPrice * 1
		}

		// uni.showToast({
		// 	title:'订单已取消或已付款',
		// 	icon:'none'
		// })
		// backtimer=setTimeout(()=>{
		// 	const arr=getCurrentPages()
		// 	if(arr.length<=1){
		// 		toJiacai()
		// 	}else{
		// 		uni.navigateBack({delta:1})
		// 	}
		// },1000)
	}


	// 监听价格算法
	watchEffect(async () => {
		if (listinfo.combinedArray.length > 0 || cartStore.carts.length > 0) {
			// 打包费packFeess  计算购物车商品费用totalPrices  餐位费Seatcharge
			// try {
			let historyOrderPackFee = is_type.value != 0 ? listinfo.packFeess : 0;
			let nowCartPackFee = is_type.value != 0 ? cartStore.totalPackFee * 1 : 0;
			let seatFee = is_type.value == 0 ? listinfo.Seatcharge : 0;
			let sum = cartStore.totalPackFee * 1 + historyOrderPackFee + listinfo.totalPrices + seatFee;
			listinfo.originAmount = Math.round(sum * 100) / 100;

			// 打包费packFeess  计算购物车商品费用totalPrices  餐位费Seatcharge  商品卷Productroll 优惠卷coupondiscountAmount 积分listinfo.pointsDiscountAmount
			let sums = nowCartPackFee + historyOrderPackFee + listinfo.totalPrices + seatFee - (listinfo
				.Productroll || 0) - (listinfo.coupondiscountAmount || 0) - (listinfo
				.pointsDiscountAmount || 0);
			listinfo.totalCost = Math.round(sums * 100) / 100;

			// 总价格
			// console.log(listinfo.combinedArray, listinfo.packFeess, listinfo.totalPrices, listinfo
			// 	.Seatcharge, listinfo.Productroll, listinfo.coupondiscountAmount, sums) // 霸王餐
			// console.log(orderVIP.value.freeDineConfig.enable, changeFreeenable.value)
			if (orderVIP.value.freeDineConfig.enable && isBwc.value) {
				listinfo.totalCost = (parseFloat(listinfo.totalCost) * parseFloat(orderVIP.value
					.freeDineConfig.rechargeTimes)).toFixed(2)
			}
			// 积分
			if (listinfo.totalCost && (listinfo.status == 'unpaid' || !listinfo.id) && orderVIP.value.id) {
				uni.$u.debounce(memberPointscalcUsablePoints, 500)
			}
			// } catch (error) {
			// 	//TODO handle the exception
			// }
		}
	});



	const changeFree = (e) => {
		isBwc.value = e

		orderInfoAfterRef.value.bwcclear()
		uniqueIds.value = [] // 筛选出商品卷的id
		listinfo.coupondiscountAmount = 0 // 优惠卷减去的金额
		listinfo.pointsNum = 0 // 商品卷总价价格
		// 商品价格
		listinfo.totalPrices = cartStore.getTotalTotalPrices(listinfo.combinedArray, isBwc.value)
		// 支付方式切换
		// #ifdef MP-WEIXIN
		paymentMethodref.value.groupChanges(2)
		// #endif
		// #ifdef MP-ALIPAY
		paymentMethodref.value.groupChanges(3)
		// #endif


	}

	const saveImage = (url) => {
		uni.saveImage({
			url: url,
			success: () => {
				uni.showToast({
					title: "保存成功",
					icon: 'none'
				})
			},
		});
	}

	//
	const paymentMethodref = ref(null)

	// 支付方式切换
	const paymentmethod = reactive({
		radiovalue: 2,
		paymentBtnText: "微信支付",
		payType: 'wechatPay'
	})

	const groupChange = async (e) => {
		paymentmethod.radiovalue = e.type;
		paymentmethod.paymentBtnText = e.name;
		paymentmethod.payType = e.payType;
	}

	// * 去充值
	const goRecharge = () => {
		uni.pro.navigateTo('/pages/member/index', {
			shopId: listinfo.shopId
		})
	}

	// 操作下单时候
	const orderInfoAfterRef = ref(null)

	// 商品卷的id储存
	const uniqueIds = ref([])

	// 这是优惠卷传的值
	const handleReturnData = async (data) => {
		// 这是优惠卷
		if (data.typeOrder == 1) {
			if (data.item) {
				// 优惠卷减去的金额
				listinfo.coupondiscountAmount = data.item.discountAmount
				uniqueIds.value.push(data.item.id)
				orderInfoAfterRef.value.dataprocessing(data)
			}
		} else {
			// 筛选出商品卷的id
			// 商品卷总价价格
			// uniqueIds.value = [...uniqueIds.value, ...new Set(data.map(item => item.id))]
			uniqueIds.value = [...uniqueIds.value, ...data.map(item => item.id)]
			console.log(uniqueIds.value);
			listinfo.Productroll = cartStore.getTotalProductroll(data).value
			// TODO handle the exception
			let res = {
				Productroll: listinfo.Productroll,
				uniqueIds: uniqueIds.value.length
			}
			orderInfoAfterRef.value.dataprocessing(res)

		}

	};

	const learcoupons = (data) => {
		if (data == 'product') {
			uniqueIds.value = [] // 筛选出商品卷的id
			listinfo.coupondiscountAmount = 0 // 优惠卷减去的金额
			listinfo.Productroll = 0 // 商品卷总价价格
			listinfo.pointsNum = 0 // 积分总价格
		} else {
			// 每次点击优惠卷删除优惠卷里的id 
			if (listinfo.coupondiscountAmount != 0) {
				uniqueIds.value.pop()
			}
			listinfo.coupondiscountAmount = 0 // 优惠卷减去的金额
		}
	}

	//取消订单
	const cancelOrder = async () => {
		uni.showModal({
			title: '取消订单',
			content: '是否取消订单？',
			showCancel: true,
			success: async (res) => {
				if (res.confirm) {
					await APIcancelOrder({
						shopId: listinfo.shopId,
						orderId: listinfo.id
					})
					uni.showToast({
						title: '取消订单成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.pro.switchTab('order/index')
					}, 1000)
				}
			}
		})

	}

	// 删除订单
	const APIputuserorderclick = async () => {
		await APIputuserorder(listinfo.id)
		uni.showToast({
			title: '删除成功',
			icon: 'none'
		})
		uni.pro.switchTab('order/index')
	}
	async function onlyCreateOrder() {
		await createOrder()
		orderorderInfo()
	}
	// 生成订单
	const createOrder = async () => {
		cartStore.carts = [];
		const res = await storeMemberpay.actionscreateOrder({
			dineMode: is_type.value == 0 ? 'dine-in' : 'take-out', //堂食 dine-in 外带 take-out 外卖 take-away
			seatNum: uni.cache.get('dinersNum') ? uni.cache.get('dinersNum') : '', //用餐人数
			// packFee: packFee.value, //打包费
			packFee: packfee.value, //打包费
			originAmount: shifu.value, //订单原金额（包含打包费） 不含折扣价格 不含餐位费
			remark: '', //备注
			placeNum: listinfo.id ? (listinfo.placeNum * 1 + 1) : 1, //当前订单下单次数
			waitCall: '', //是否等叫 0 否 1 等叫
			orderId: listinfo.id || '',
			tableCode: options.tableCode,
			userId: uni.cache.get('userInfo').id || '' //
		})
		// 清空购物车
		if (res) {
			Object.assign(listinfo, res)
			// cartStore.setOldOrder(res)
			getOrderInfoAfterCalcInit(res)

			cartsSocket.sendMessage({
				type: 'shopping',
				table_code: uni.cache.get('tableCode'),
				shop_id: uni.cache.get('shopId'),
				operate_type: 'cleanup',
			})
			return res
		} else {
			uni.showToast({
				title: '生成订单失败'
			})
		}

	}

	function isPayBefor() {
		return ordershopUserInfo.value.registerType == 'before' ? true : false
	}


	function pay_lock() {
		cartsSocket.sendMessage({
			...socketInitPar,
			operate_type: 'pay_lock'
		})
	}

	function pay_unlock() {
		clearInterval(payStatusTimer)
		cartsSocket.sendMessage({
			...socketInitPar,
			operate_type: 'pay_unlock'
		})
	}
	async function search_pay_lock() {
		cartsSocket.sendMessage({
			...socketInitPar,
			operate_type: 'search_pay_lock'
		})
		return new Promise((relove, reject) => {
			cartsSocket.socketTask.onMessage(res => {
				relove(JSON.parse(res.data))
			})
		})
	}
	let payStatusTimer = null
	let orderIsLock = true;
	const istoricalorders = async () => {
		//先付
		if (isPayBefor()) {
			console.log('isPayBefor');
			console.log('cartStore.isEmpty', cartStore.isEmpty);
			console.log('cartStore.carts', cartStore.carts);
			// 购物车有数据
			if (!cartStore.isEmpty) {
				const res = await createOrder()
				//历史订单数据
				const res1 = await APIgetOrderById({
					orderId: res.id
				})
				cartStore.setOldOrder(res1)
			}
			nextTick(goToPay)

			// goToPay()

		} else {
			//后付

			// 先调用历史订单
			let APIhistoryOrderres = await APIhistoryOrder({
				tableCode: listinfo.tableCode
			})
			// 判断是否有历史订单
			if (APIhistoryOrderres.detailMap) {
				let combinedArray = [];
				for (const key in APIhistoryOrderres.detailMap) {
					if (APIhistoryOrderres.detailMap.hasOwnProperty(key)) {
						let subArray = APIhistoryOrderres.detailMap[key];
						combinedArray = [...combinedArray, ...subArray]
					}
				}
				// 判断支付之前是是否还有新加订单
				if (listinfo.combinedArray.length === combinedArray.length) {
					goToPay()
				} else {
					uni.showToast({
						title: '你的订单已更新！',
						icon: 'none'
					})
					orderorderInfo()
				}
			} else {
				uni.showToast({
					title: '你的小伙伴已提交订单~',
					icon: 'none'
				})
				setTimeout(() => {
					orderorderInfo()
				}, 1000)
			}
		}



	}

	// * 去支付
	const goToPay = async (isCreateOrder = false) => {
		// 余额支付
		if (paymentmethod.payType == 'accountPay') {
			// if (orderVIP.value.isVip == 0) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '您还不是会员,是否去注册会员？',
			// 		success: (res) => {
			// 			if (res.confirm) {
			// 				uni.pro.navigateTo('user/member/index', {
			// 					shopId: orderVIP.value.shopId,
			// 					type: 'detail'
			// 				})
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消');
			// 			}
			// 		}
			// 	})
			// 	return 

			// }  

			if (orderVIP.value.payPwd == '') {
				uni.showModal({
					title: '提示',
					content: '您还未设置支付密码，是否去设置？',
					success: (res) => {
						if (res.confirm) {
							uni.pro.navigateTo('user/member/setPassword', {
								shopId: orderVIP.value.shopId,
								type: 'detail'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
				// } else if (orderVIP.value.amount == 0) {
				// 	uni.showToast({
				// 		title: '您的余额不足',
				// 		icon: 'none'
				// 	})
				// } else {
			} else {
				ispws.value = true
			}
			return false
		}

		const canPayRes = await search_pay_lock()
		console.log('canPayRes', canPayRes);
		const canPay = canPayRes.status == 1 ? true : false;
		console.log('canPay', canPay);
		if (!canPay) {
			uni.showToast({
				title: '有人正在付款中！',
				icon: 'none'
			})
			return
		}
		pay_lock()
		payStatusTimer = setInterval(() => {
			pay_lock()
		}, 1000)

		if (orderVIP.value.freeDineConfig.enable && isBwc.value) {
			await storeMemberpay.actionspayltPayVip({
				shopId: orderVIP.value.shopId,
				shopUserId: orderVIP.value.id,
				orderId: listinfo.id,
				userAllPack: is_type.value == 0 ? 0 : 1, //是否整单打包
				amount: cartStore.orderCostSummary.finalPayAmount, // 最终订单金额
				returnUrl: '', //跳转地址
				buyerRemark: '',
				seatNum: is_type.value == 0 ? listinfo.seatNum : 0, //用餐人数
			})

			orderorderInfo()
			return false;
		} else {
			console.log(' ordershopUserInfo.value', ordershopUserInfo.value);
			let checkOrderPay = {
				orderId: listinfo.id,
				vipPrice: cartStore.useVipPrice ? 1 : 0, //是否使用会员价0否1是
				userAllPack: is_type.value == 0 ? 0 : 1, //是否整单打包
				seatNum: is_type.value == 0 ? cartStore.seatFeeConfig.personCount : 0, //用餐人数
				originAmount: cartStore.orderCostSummary.goodsRealAmount, //订单原金额（包含打包费+餐位费） 不含折扣价格
				discountRatio: 1, //折扣比例(计算时 向上取整保留 两位小数)   写死1
				discountAmount: 0, //手动优惠金额  写死0
				productCouponDiscountAmount: cartStore.orderCostSummary.productCouponDeduction, //商品优惠券抵扣金额
				otherCouponDiscountAmount: cartStore.orderCostSummary.fullCouponDeduction, //其他优惠券抵扣金额
				couponList: cartStore.backendCoupons.map(v => v.id), //用户使用的卡券
				orderAmount: cartStore.orderCostSummary.finalPayAmount, // 最终订单金额
				roundAmount: 0, //抹零金额 减免多少钱
				pointsDiscountAmount: cartStore.orderCostSummary
					.pointDeductionAmount, //积分抵扣金额(tb_points_basic_setting表)
				pointsNum: cartStore.orderCostSummary.pointUsed, //(扣除各类折扣 enable_deduction后使用)
				newCustomerDiscountAmount: cartStore.orderCostSummary.newUserDiscount, //新客立减
				newCustomerDiscountId: cartStore.orderCostSummary.newUserDiscount > 0 ? cartStore
					.consumeDiscount.id : '',
				remark: listinfo.remark, //用户备注
			}
			console.log('topay checkOrderPay', checkOrderPay);
			try {
				if (rechargeItem.value.id && rechargeId.value) {
					//充值支付
					const payRes = await rechargePayOrder({
						checkOrderPay: {
							...checkOrderPay,
							userId: uni.cache.get('shopUserInfo').userId || ''
						},

						payType: paymentmethod.payType,
						buyerRemark: '',
						returnUrl: '',
						rechargeId: rechargeId.value,
						rechargeDetailId: rechargeItem.value.id,
						shopUserId: orderVIP.value.id,
						shopId: orderVIP.value.shopId,
					})
					await pay(payRes)
					pay_unlock()
				} else {
					console.log('微信支付');
					await storeMemberpay.actionsltPayOrder({
						checkOrderPay,
						payType: paymentmethod.payType,
						buyerRemark: '',
						returnUrl: ''
					})
				}

			} catch (error) {
				console.log('error', error);
				pay_unlock()
				//TODO handle the exception
			}
		}
		pay_unlock()
		console.log('orderorderInfo');
		orderorderInfo()
	}

	//002-获取订单可用积分及抵扣金额（支付页面使用）
	const memberPointscalcUsablePoints = async () => {
		let res = await APImemberPointscalcUsablePoints({
			shopUserId: orderVIP.value.id,
			orderAmount: listinfo.totalCost,
		})
		orderInfoAfterRef.value?.getCalcUsablePoints(res)
	}
	// 
	const clickPointsamount = (Pointsamount) => {
		listinfo.pointsDiscountAmount = Pointsamount.pointsDiscountAmount
		listinfo.pointsNum = Pointsamount.pointsNum
	}

	const payPasswordref = ref(null)
	// 余额支付
	const accountPayevent = async (pwd) => {
		ispws.value = false;


		let checkOrderPay = {
			userId: uni.cache.get('userInfo').id,
			orderId: listinfo.id,
			vipPrice: cartStore.useVipPrice ? 1 : 0, //是否使用会员价0否1是
			userAllPack: is_type.value == 0 ? 0 : 1, //是否整单打包
			seatNum: is_type.value == 0 ? cartStore.seatFeeConfig.personCount : 0, //用餐人数
			originAmount: cartStore.orderCostSummary.goodsRealAmount, //订单原金额（包含打包费+餐位费） 不含折扣价格
			discountRatio: 1, //折扣比例(计算时 向上取整保留 两位小数)   写死1
			discountAmount: 0, //手动优惠金额  写死0
			productCouponDiscountAmount: cartStore.orderCostSummary.productCouponDeduction, //商品优惠券抵扣金额
			otherCouponDiscountAmount: cartStore.orderCostSummary.fullCouponDeduction, //其他优惠券抵扣金额
			couponList: cartStore.backendCoupons.map(v => v.id), //用户使用的卡券
			orderAmount: cartStore.orderCostSummary.finalPayAmount, // 最终订单金额
			roundAmount: 0, //抹零金额 减免多少钱
			pointsDiscountAmount: cartStore.orderCostSummary
				.pointDeductionAmount, //积分抵扣金额(tb_points_basic_setting表)
			pointsNum: cartStore.orderCostSummary.pointUsed, //(扣除各类折扣 enable_deduction后使用)
			newCustomerDiscountAmount: cartStore.orderCostSummary.newUserDiscount, //新客立减
			newCustomerDiscountId: cartStore.orderCostSummary.newUserDiscount > 0 ? cartStore.consumeDiscount
				.id : '',
			remark: listinfo.remark, //用户备注
		}
		try {
			await storeMemberpay.balancePayOrder({
				checkOrderPay,
				payType: paymentmethod.payType,
				pwd: pwd,
				shopUserId: orderVIP.value.id,
				buyerRemark: '',
				returnUrl: ''
			})
		} catch (error) {
			//TODO handle the exception
		}
		orderorderInfo()
	}

	onBeforeUnmount(() => {
		uni.$off('returnData', handleReturnData);
		clearTimeout(backtimer)
		clearInterval(payStatusTimer)
		closeSocket()
	});
	onHide(() => {
		closeSocket()
		clearInterval(payStatusTimer)
	})

	function closeSocket() {

		// cartsSocket.closeExistingConnection()
	}

	onShow(() => {
		if (cartsSocket) {
			cartsSocket.connect()
		}
		try {
			// 更新数据
			if (orderVIP.value) {
				orderVIP.value = uni.cache.get('orderVIP')
				paymentMethodref.value.orderVIPfun(uni.cache.get('orderVIP'))
				if (listinfo.id && ordershopUserInfo.value.registerType != 'before') {
					orderorderInfo()
				}
			}
		} catch (error) {
			//TODO handle the exception
		}


		orderorderInfo()
		uni.$off('selCoupon')
		uni.$on('selCoupon', function(data) {
			console.log('selCoupon', data)
			orderInfoAfterRef.value.dataprocessing(_.cloneDeep(data))
			cartStore.setCoupons(_.cloneDeep(data))
		})

	});
	let options = {}

	// 跳转到加菜页面
	function toJiacai() {
		back()
		return
		uni.navigateTo({
			url: '/pages/product/index'
		})
	}
	const packfee = computed(() => {
		return cartStore.orderCostSummary.packFee
	})
	//不计算各种折扣前的实付金额
	const shifu = computed(() => {
		const payAmount = listinfo.payAmount ? listinfo.payAmount * 1 : 0
		return payAmount + cartStore.totalPrice * 1 + packfee.value * 1
	})
	//减去各种折扣后的金额
	const lastPayMoney = computed(() => {
		return shifu.value * 1
	})


	const payStatus = {
		'unpaid': '待支付',
		'done': '已完成',
		'refund': '已退款',
		'part-refund': '部分退款',
		'cancelled': '已取消'
	}
	const navTitle = computed(() => {
		if (!listinfo.id && !cartStore.isEmpty) {
			return '待确认'
		}
		if (cartStore.isEmpty && listinfo.id) {
			return payStatus[listinfo.status] || '待确认'
		} else {
			return '待确认'
		}
	})

	async function init(opt) {
		cartStore.clearOrderConfig()
		Object.assign(options, opt)
		listinfo.id = options.orderId;
		console.log('options', options);
		if (options.shopId) {
			// 每次进来全局更新shopId
			uni.cache.set('shopId', options.shopId, 30)
			uni.$on('returnData', handleReturnData);
		}
		//如果已经生成订单，根据历史订信息设置相关配置
		if (options.orderId) {
			let res = await APIgetOrderById({
				orderId: listinfo.id
			})
			if (res) {
				uni.cache.set('tableCode', res.tableCode)
				uni.cache.set('tableCode', res.seatNum)
				options.tableCode = res.tableCode
				cartStore.setSeatFeeConfig('personCount', res.seatNum)
				cartStore.setDinnerType(res.dineMode || 'dine-in')
			}
		}
		//获取店铺信息
		const shopInfoRes = await APIusershopInfodetail({
			shopId: options.shopId
		})
		if (shopInfoRes) {
			cartStore.shopInfo = shopInfoRes.shopInfo;
		}
		await cartStore.goodsInit()
		// * 获取会员信息
		await storeuser.actionsproductqueryProduct()
		await nextTick()

		orderVIP.value = uni.cache.get('orderVIP')
		if (options.tableCode) {
			socketInitPar.table_code = options.tableCode
			socketInit()
		} else {
			orderorderInfo()
		}

	}
	onLoad((opt) => {
		init(opt)
	})
</script>

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

	.container {
		padding: 32rpx 28rpx 32rpx 28rpx;
	}

	.headStatus {
		display: flex;
		flex-direction: column;
		margin-bottom: 32rpx;
		align-items: center;

		.status {
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: bold;
			font-size: 36rpx;
			color: #333333;

			.statusName {
				margin-left: 16rpx;
			}
		}

		.time {
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			margin-top: 18rpx;
		}
	}

	.wxQrcode {
		background: #FFFFFF;
		border-radius: 18rpx 18rpx 18rpx 18rpx;
		padding: 32rpx 24rpx;
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 32rpx;

		.left {
			display: flex;
			flex-direction: column;
		}

		.title {
			font-weight: bold;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 16rpx;
		}
	}

	.card_box {
		background-color: #fff;
		// box-shadow: 0rpx 8rpx 12rpx 2rpx rgba(87,86,86,0.35);
		position: relative;
		width: 100%;
		height: 100%;
		// box-shadow: 0rpx 4rpx 12rpx 2rpx rgba(87, 86, 86, 0.35);
		border-radius: 18rpx;

		.card_head_box {
			width: 100%;
			display: flex;
			justify-content: space-between;
			position: absolute;
			top: -22.5rpx;
			padding: 0 44rpx;

			.card_head_item {
				width: 45rpx;
				height: 45rpx;
				background-color: #f9f9f9;
				border-radius: 50%;
				box-shadow: inset 0rpx -13rpx 18rpx -16rpx rgba(87, 86, 86, 0.35);
			}

		}
	}

	.card {
		// background-color: #fff;
		border-radius: 20upx;
		margin-bottom: 28upx;
		position: relative;

		.head {
			display: flex;
			justify-content: space-between;
			padding: 50rpx 0 32rpx 0;
			border-bottom: 2rpx dashed #E3E3E3;

			.head_left {
				.shopName {
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;
				}

				.tableName {
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
				}
			}

			.status {
				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
				}
			}
		}

		.number-wrap {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 32rpx;

			.t {
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
			}

			.number {
				font-weight: bold;
				font-size: 56rpx;
				color: #333333;
			}
		}


		.price {
			.i {
				font-size: 20upx;
			}

			.num {
				font-size: 38upx;
			}
		}

		.shop-box {
			padding: 36rpx 34rpx 30rpx 34rpx;
			border-bottom: 2rpx dashed #E3E3E3;

			.shop-head {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.shop-head-left {
					display: flex;
					align-items: center;

					.tag-wrap {
						width: 80rpx;
						height: 48rpx;
						background: #FFFFFF;
						border-radius: 10rpx 10rpx 10rpx 10rpx;
						border: 2rpx solid #E3AD7F;
						margin-right: 18rpx;
						display: flex;
						align-items: center;
						justify-content: center;

						.tag {
							font-weight: 400;
							font-size: 24rpx;
							color: #E3AD7F;
						}
					}

					.title {
						font-weight: bold;
						font-size: 28rpx;
						color: #333333;
					}

				}
			}

			.shop-info {
				margin-top: 32rpx;

				.item:nth-child(1) {
					margin-top: 0;
				}

				.item {
					padding: 32rpx 0 !important;
					display: flex;

					.cover {}

					.info {
						flex: 1;
						display: flex;
						flex-direction: column;
						padding-left: 16upx;

						.productName {
							font-weight: bold;
							font-size: 28rpx;
							color: #333333;
							margin-top: 20rpx;
						}

						.productSkuName {
							font-weight: 400;
							font-size: 24rpx;
							color: #999999;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 3;
							overflow: hidden;
							text-overflow: ellipsis;
						}

						.n {
							font-size: 24upx;
							color: #999;
						}
					}

					.price {
						display: flex;
						flex-direction: column;
						align-items: flex-end;
						padding-left: 68rpx;

						.priceAmount {
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
							margin-top: 26rpx;
						}

						.num {
							font-weight: 400;
							font-size: 24rpx;
							color: #999999;
							margin-top: 22rpx;
						}
					}
				}
			}

			.total-wrap {
				width: 100%;
				display: flex;
				justify-content: space-between;
				font-weight: 500;
				font-size: 28rpx;

				.price {
					font-weight: bold;
					font-size: 32rpx;
				}
			}
		}



		.order_footer {
			display: flex;
			flex-direction: column;
			padding: 34rpx;
			position: relative;

			.order_footer_icon {
				width: 100%;
				position: absolute;
				top: -22.5rpx;
				left: 0;
				display: flex;
				justify-content: space-between;

				.order_footer_left_icon {
					width: 45rpx;
					height: 45rpx;
					margin-left: -22.5rpx;
					background-color: #f9f9f9;
					border-radius: 50%;
					box-shadow: inset -20rpx 0rpx 22rpx -20rpx rgba(87, 86, 86, 0.35);

				}

				.order_footer_right_icon {
					width: 45rpx;
					height: 45rpx;
					margin-right: -22.5rpx;
					background-color: #f9f9f9;
					border-radius: 50%;
					box-shadow: inset 13rpx 0rpx 16rpx -9rpx rgba(87, 86, 86, 0.35);

				}
			}

			.title {
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
			}

			.order-info {
				.row {
					display: flex;
					justify-content: space-between;
					padding-top: 32upx;

					.t {
						font-weight: normal;
						font-size: 28rpx;
						color: #333333;
					}

					.info {
						font-weight: 400;
						font-size: 24rpx;
						color: #666666;
					}
				}
			}
		}


	}

	.pay-info-wrap {
		padding: 0;
		box-sizing: border-box;

		.info-wrap {
			padding: 64rpx 30rpx 30rpx 30rpx;
			box-sizing: border-box;

			.title {
				align-self: center;
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
			}
		}

		.info-content {
			.pay-title {
				display: flex;
				align-items: flex-end;
				justify-content: center;
				font-weight: bold;
				width: 100%;
				font-size: 48rpx;
				color: #333;
				margin-top: 48rpx;

				text {
					font-size: 60rpx;
					color: #333;
				}
			}

			.pay-password {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 64rpx;

				.list {
					width: 88rpx;
					height: 88rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 2rpx solid #999;
					border-radius: 8rpx;

					text {
						font-size: 32rpx;
					}
				}

			}

			.hint {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 100rpx;

				text {
					font-size: 28rpx;
					color: #ccc;
				}
			}
		}

	}

	.fixedview {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 999;

		// height: 80rpx;
		.flex-between {
			width: 100%;
			padding: 36rpx 36rpx 70rpx 36rpx;
			background: #FFFFFF;

			.fixedview_one {
				display: flex;
				align-items: flex-end;

				.fixedview_oneone {
					font-weight: 400;
					font-size: 28rpx;
					color: #666666;
				}

				.fixedview_onetow {
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;

					text {
						font-size: 24rpx;
					}
				}
			}

			.flex-colum-end {
				.fixedview_tow {
					background: #E3AD7F;
					border-radius: 36rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: #FFFFFF;
					padding: 14rpx 44rpx;
				}

				.fixedview_tows {
					margin-top: 10rpx;
					background: #c3c3c3;
					border-radius: 36rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: #FFFFFF;
					padding: 14rpx 44rpx;
				}
			}

		}
	}
	
	.orderInfo {
		background: #FFFFFF;
		border-radius: 18rpx 18rpx 18rpx 18rpx;
		margin-top: 32rpx;
		padding: 32rpx 34rpx;
	
			.t {
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				flex-shrink: 0;
			}
	
			.info {
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
			}
	
	}
</style>