<template>
	<view class="min-page bg-gray u-font-28 u-p-30">
		<user-vue :orderInfo="orderDetail.info" :user="user"></user-vue>
		<view class="default-box-padding bg-fff border-r-12 u-m-t-20">
			<text class="">桌位号：</text>
			<text class="">{{orderDetail.info.tableName}}</text>
		</view>
		<goods-list @printOrder="onPrintOrder" @tuikuan="onTuikuan" :orderInfo="orderDetail.info"
			:data="orderDetail.goodsList" :seatFee="orderDetail.seatFee" @tuicai="onTuiCai"></goods-list>
		<template v-if="orderDetail.seatFee.totalNumber&&orderDetail.seatFee.totalAmount">
			<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.status=='unpaid'">
					<view class="u-flex-1">
						<my-button @tap="diancan" color="#fff" bgColor="rgb(57,53,52)" borderRadius="100rpx 0 0 100rpx"
							shape="circle" plain type="primary">加菜</my-button>
					</view>
					<view class="u-flex-1">
						<my-button @tap="toPay" borderRadius="0 100rpx 100rpx 0" shape="circle"
							type="primary">结账</my-button>
					</view>
				</template>

			</view>
		</view>

		<tuicai-vue @confirm="tuicaiConfirm" v-model:show="tuicai.show" :data="tuicai.selGoods"></tuicai-vue>
	</view>
</template>

<script setup>
	import * as Api from '@/http/yskApi/Instead.js'
	import * as orderApi from '@/http/yskApi/order.js'
	import {queryAllShopUser} from '@/http/yskApi/shop-user.js'
	import {
		objToArrary
	} from '@/commons/utils/returrn-data.js'
	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 '@/http/yskApi/shop.js'
	import {hasPermission} from '@/commons/utils/hasPermission.js'
	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref
	} from 'vue';
	import OrderDetail from './page.js'
	const tuicai = reactive({
		show: false,
		isSeatFee: false,
		selGoods: {}
	})

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

	function onTuiCai(goods, index) {
		console.log(goods);
		tuicai.show = true
		tuicai.selGoods = goods
	}
	async function tuicaiConfirm() {
		console.log(tuicai.selGoods);
		const res = await Api.$returnCart({
			cartId: tuicai.selGoods.hasOwnProperty('cartId') ? tuicai.selGoods.cartId : tuicai.selGoods.id,
			tableId: orderDetail.info.tableId,
		})
		tuicai.show = false
		init()
	}


	async function printDishes() {
		try {
			const res = await Api.$printDishes({
				tableId: orderDetail.info.tableId
			})
			infoBox.showToast('已发送打印请求')
		} catch (e) {
			infoBox.showToast('发送打印请求失败')
			//TODO handle the exception
		}

	}

	function onPrintOrder() {
		uni.showModal({
			title: '提示',
			content: '是否打印当前台桌菜品',
			success(res) {
				if (res.confirm) {
					printDishes()
				}
			}
		})
	}
	
	
	async function onTuikuan(goods, index) {
		const canTuikuan=await hasTuiKuan()
		if(!canTuikuan){
			return
		}
		const {
			id,
			productId,
			productSkuId,
			productName,
			productSkuName,
			cartId,
			orderId,
			num,
			priceAmount,
			price
		} = goods
		go.to('PAGES_ORDER_TUIKUAN', {
			id,
			cartId,
			orderId,
			productId,
			productSkuId,
			productName,
			num,
			number: 0,
			productSkuName: productSkuName || '',
			priceAmount,
			price
		})

	}


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

	function diancan() {
		go.to('PAGES_CREATE_ORDER', {
			tableId: options.tableId || orderDetail.info.tableId,
			name: options.name || orderDetail.info.tableName,
			type: 'add'
		})
	}

	function toPay() {
		const userId=orderDetail.info.userId||''
		go.to('PAGES_ORDER_PAY', {
			tableId: options.tableId|| orderDetail.info.tableId,
			tableName: options.name,
			masterId: options.masterId,
			orderId: orderDetail.info.id,
			discount: 1,
			userId
		})
	}

	const orderDetail = reactive({
		goodsList: [],
		info: {},
		seatFee: {
			totalAmount: 0
		}
	})
	const options = reactive({})
	async function init() {
		const res = await orderApi.tbOrderInfoDetail(options.id)
		if(res.userId){
			queryAllShopUser({id:res.userId}).then(res=>{
				if(res.content[0]){
					user.value=res.content[0]
				}
			})
		}
	
		
		if (res.detailList.length) {
			uni.setStorageSync('useType', res.detailList[0].useType)
		}
		const masterId = res.masterId
		options.masterId = res.masterId
		// if (res.status == 'unpaid') {
		if (false) {
			const {
				records,
				seatFee
			} = await Api.getCart({
				masterId,
				tableId: res.tableId,
				page: 1,
				size: 200
			})
			orderDetail.goodsList = records
			orderDetail.seatFee = seatFee ? seatFee : orderDetail.seatFee
		} else {
			const goodsMap = {}
			for (let i in res.detailList) {
				const goods = res.detailList[i]
				if (goods.productName != '客座费') {
					if (goodsMap.hasOwnProperty(goods.placeNum)) {
						goodsMap[goods.placeNum].push(goods)
					} else {
						goodsMap[goods.placeNum] = [goods]
					}
				}

			}
			orderDetail.seatFee = res.seatInfo|| {
				name: '客座费',
				number: res.seatCount,
				totalNumber: res.seatCount,
				totalAmount: res.seatAmount,
				status:''
			}
			orderDetail.goodsList = Object.entries(goodsMap).map(([key, value]) => ({
				info: value,
				placeNum: key
			}))
			console.log(orderDetail.goodsList);
		}
		orderDetail.info = res
	}

	function watchEmit() {
		uni.$off('orderDetail:update')
		uni.$once('orderDetail:update', (newval) => {
			console.log(newval);
			init()
		})
	}

	// 监听选择用户事件
	let user = ref({
		headImg:'',
		telephone:'',
		amount:'0.00',
		totalScore:'0.00'
	})
	//更新选择用户
	function setUser(par) {
		const submitPar = {
			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)
		return Api.$setUser(submitPar)
	}

	function watchChooseuser() {
		uni.$off('choose-user')
		uni.$on('choose-user', (data) => {
			console.log(data);
			user.value = data
			setUser()
		})
	}

	onShow(() => {
		watchEmit()
		watchChooseuser()
		init()
	})
	onLoad((opt) => {
		Object.assign(options, opt)
		console.log(options);
	})
</script>

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

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