<template>
	<view class="min-page bg-gray u-font-28 u-p-30">
		<user-vue :orderInfo="orderDetail.info" :user="user"></user-vue>
		
		<goods-list @printOrder="onPrintOrder" @tuikuan="onTuikuan" :orderInfo="orderDetail.info"
		:user="user"
			:data="orderDetail.goodsList" :seatFee="orderDetail.seatFee" @tuicai="onTuiCai"></goods-list>
	
		<template v-if="true">
			<extra-vue @tuicai="onSeatFeeTuicai" @tuikuan="onSeatFeeTuiKuan" :orderInfo="orderDetail.info"
				:data="orderDetail.seatFee"></extra-vue>
		</template>
		<order-vue :data="orderDetail.info" :table="options" :seatFee="orderDetail.seatFee"></order-vue>
		<!-- <step-vue></step-vue> -->
		<view style="height: 200rpx;"></view>
		<view class="u-fixed bottom bg-fff ">
			<view class="u-flex u-abso">
				<template v-if="orderDetail.info.dineMode=='take-out'||!orderDetail.info.tableCode||pageData.shopInfo.registerType=='before'">
					<view class="u-flex-1" v-if="orderDetail.info.status=='unpaid'">
						<my-button @tap="toPay" borderRadius="100rpx" shape="circle"
							type="primary">结账</my-button>
					</view>
				</template>
				<template v-else>
					<template v-if="orderDetail.info.status=='unpaid'">
						
						<view class="u-flex-1">
							<my-button @tap="diancan" color="#fff" bgColor="rgb(57,53,52)" borderRadius="100rpx 0 0 100rpx" fontWeight="700" 
								shape="circle" plain type="primary">加菜</my-button>
						</view>
						<view class="u-flex-1" style="border-right: 1px solid #fff;">
							<my-button @tap="transformTable" borderRadius="0 0 0 0" shape="circle" fontWeight="700" 
								type="primary">转桌</my-button>
						</view>
						<view class="u-flex-1">
							<my-button @tap="toPay" borderRadius="0 100rpx 100rpx 0" shape="circle" fontWeight="700" 
								type="primary">结账</my-button>
						</view>
					</template>
				</template>
			</view>
		</view>

		<tuicai-vue @confirm="tuicaiConfirm" v-model:show="tuicai.show" :data="tuicai.selGoods"></tuicai-vue>
		
		<changeTable v-model="changeTableShow" :nowCartData="[]" :goodsList="orderDetail.info?orderDetail.info.detailMap:[]" :order="orderDetail.info"
		@update="changeTableUpdate"
		></changeTable>
	</view>
</template>

<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { reactive, ref } from 'vue';
	import userVue from './components/user.vue';
	import orderVue from './components/order.vue';
	import goodsList from './components/list.vue';
	import stepVue from './components/step.vue';
	import extraVue from './components/extra.vue';
	import tuicaiVue from './components/tuicai.vue';
	
	import go from '@/commons/utils/go.js'
	import infoBox from '@/commons/utils/infoBox.js'
	import {hasPermission} from '@/commons/utils/hasPermission.js'
	
	import OrderDetail from './page.js'
	import { getHistoryOrder, refundOrder,getOrderById,printOrder } from '@/http/api/order.js'
	import { shopStaffDetail } from '@/http/api/staff.js'
	import { shopUserDetail } from '@/http/api/shopUser.js'
	import { getShopInfo } from '@/http/api/shop.js'
	
	import changeTable from '@/components/change-table.vue'
	const changeTableShow=ref(false)
	function transformTable(){
		changeTableShow.value=true
	}
	
	const tuicai = reactive({
		show: false,
		isSeatFee: false,
		selGoods: {}
	})
	const orderDetail = reactive({
		goodsList: [],
		info: {},
		seatFee: {
			totalAmount: 0
		}
	})
	const options = reactive({})
	// 监听选择用户事件
	let user = ref({
		headImg:'',
		phone:'',
		amount:'0.00',
		accountPoints:'0.00'
	})
	const pageData = reactive({
		shopInfo: {},
	})
	onLoad((opt) => {
		Object.assign(options, opt)
		getShopInfoData()
	})
	onShow(() => {
		watchEmit()
		watchChooseuser()
		getOrderDetail()
	})
	
	/**
	 * 获取店铺信息
	 */
	function getShopInfoData () {
		getShopInfo({id:uni.getStorageSync('shopInfo').id}).then(res=>{
			pageData.shopInfo = res;
			uni.setStorageSync('shopInfo',res)
		})
	}
	
	/**
	 * 获取订单详情
	 */
	async function getOrderDetail () {
		let res = await getHistoryOrder({orderId: options.id})
		// console.log("订单详情===",res)
		if(res.userId){
			let resUser = await shopUserDetail({userId:res.userId})
			user.value = resUser
		}
		orderDetail.seatFee =  {
			seatNum: res.seatNum,
			seatAmount: res.seatAmount,
		}
		
		orderDetail.goodsList = Object.entries(res.detailMap).map(([key, value]) => ({
			info: value,
			placeNum: key
		}))
		
		orderDetail.goodsList.map(item=>{
			item.info.map(item=>{
				item.unitPrice = uni.$utils.isGoodsPrice(item,user.value)
			})
		})
		console.log('orderDetail.goodsList',orderDetail.goodsList);
		console.log('orderDetail.info',orderDetail.info);
		orderDetail.info = res
	}

	function onSeatFeeTuicai(seatFee) {
		seatFee={...seatFee,num:seatFee.num,productName:seatFee.productName}
		tuicai.show = true
		tuicai.isSeatFee = seatFee
		tuicai.selGoods = seatFee
	}
	//是否有允许退款权限
	async function hasTuiKuan(){
		const isHas=await hasPermission('允许退款')
		return isHas
	}
	
	async function onSeatFeeTuiKuan(seatFee) {
		const canTuikuan=await hasTuiKuan()
		if(!canTuikuan){
			return
		}
		const {
			id,cartId,
			productId,
			productSkuId,
			productName,
			num,
			priceAmount,
			price
		} = seatFee
		go.to('PAGES_ORDER_TUIKUAN', {
			orderId:orderDetail.info.id,
			id,
			cartId,
			productId,
			productSkuId,
			productName,
			num,
			number: 0,
			skuName: '',
			priceAmount,
			price
		})
	}

	function onTuiCai(goods, index) {
		tuicai.show = true
		tuicai.selGoods = goods
	}
	async function tuicaiConfirm(e) {
		const res = await refundOrder(e)
		tuicai.show = false
		if(res){
			go.back()
		}else{
			getOrderDetail()
		}
	}
	
	/**
	 * 打印订单
	 */
	function onPrintOrder() {
		uni.showModal({
			title: '提示',
			content: '是否打印当前台桌菜品',
			async success(res) {
				if (res.confirm) {
					try {
						const res = await printOrder({
							id: orderDetail.info.id,
							type: orderDetail.info.status == 'unpaid' ? 1 : 0
							
						})
						infoBox.showToast('已发送打印请求')
					} catch (e) {
						infoBox.showToast('发送打印请求失败')
					}
				}
			}
		})
	}
	
	
	async function onTuikuan(goods, index) {
		const canTuikuan=await hasTuiKuan()
		if(!canTuikuan){
			return
		}
		if (Array.isArray(goods)) {
		
			go.to('PAGES_ORDER_TUIKUAN', {
				orderInfo: JSON.stringify(orderDetail.info),
				goodsList:JSON.stringify(goods)
			
			})
		} else {
			goods.number = 0
			goods.skuName = goods.skuName || ''
			goods.priceAmount = goods.priceAmount ? goods.priceAmount : (goods.num*uni.$utils.isGoodsPrice(goods,user.value)).toFixed(2)
			console.log(goods)
			goods.unitPrice = uni.$utils.isGoodsPrice(goods,user.value)
			goods.userCouponId = goods.userCouponId ? goods.userCouponId:''
			go.to('PAGES_ORDER_TUIKUAN', {
				orderInfo: JSON.stringify(orderDetail.info),
				goodsList:JSON.stringify([goods])
			})
		}
	}


	const uiPage = new OrderDetail()
	setTimeout(() => {
		uiPage.setVal('user', {
			name: 1
		})
	}, 1500)

	async function diancan() {
		const canXiadan=await hasPermission('允许下单')
		if(!canXiadan){
			return 
		}
		clearEmit()
		go.to('PAGES_CREATE_ORDER', {
			tableId: options.tableId || orderDetail.info.tableId,
			tableCode: options.tableCode || orderDetail.info.tableCode,
			name: options.name || orderDetail.info.tableName,
			type: 'add',
			vipUserId: orderDetail.info.userId?orderDetail.info.userId:''
		})
	}

	async function toPay() {
		const canJieZhang=await hasPermission('允许收款')
		if(!canJieZhang){
			return 
		}
		const userId=orderDetail.info.userId||''
		clearEmit()
		go.to('PAGES_ORDER_PAY', {
			tableId: options.tableId|| orderDetail.info.tableId,
			tableCode: options.tableCode || orderDetail.info.tableCode,
			tableName: options.name || orderDetail.info.tableName,
			orderId: orderDetail.info.id,
			discount: 1,
			userId
		})
	}


	function watchEmit() {
		uni.$off('orderDetail:update')
		uni.$once('orderDetail:update', (newval) => {
			getOrderDetail()
		})
	}

	
	//更新选择用户
	async  function setUser(par) {
		const submitPar = {
			orderId:options.id||'',
			masterId: options.masterId,
			tableId: options.tableId|| orderDetail.info.tableId,
			vipUserId: user.value.id ? user.value.id : '',
			type: user.value.id ? 0 : 1 //0 设置 1 取消
		}
		Object.assign(submitPar, par)
		 const res=await  Api.$setUser(submitPar)
		 getOrderDetail()
		 return res
	}
	
	
	 function clearEmit(){
		uni.$off('choose-user')
		uni.$off('orderDetail:update')
	}
	
	function watchChooseuser() {
		uni.$off('choose-user')
		uni.$on('choose-user', (data) => {
			console.log(data);
			user.value = data
			setUser()
		})
	}

	function changeTableUpdate(allMerge){
		if(allMerge===1){
			uni.navigateBack()
		}else{
			getOrderDetail()
		}
	}
</script>

<style lang="scss" scoped>
	.bottom {
		bottom: 0;
		left: 0;
		right: 0;
		height: 68rpx;

		.u-abso {
			bottom: 84rpx;
			left: 28rpx;
			right: 28rpx;
		}
	}
</style>