<template>
	<view class="page-container bg-gray u-font-28 u-p-30">

		<!-- 遍历所有分组：key = 第几次下单 -->
		<view class="group-wrap" v-for="(groupList, groupKey) in detailMap" :key="groupKey">
			<view class="group-title  u-font-28 u-font-bold">第{{ groupKey }}次下单</view>

			<!-- 遍历该分组下的所有商品 -->
			<view class="  u-flex u-m-b-20 u-row-between" v-for="(item, index) in groupList" :key="item.id">
				<view>
					<view class="u-font-26 ">{{ item.productName }}</view>
					<view class="u-font-24 color-999 u-m-t-10">{{ item.skuName }}</view>
					<view class="u-font-24 color-999 u-m-t-10" v-if="item.remark">{{ item.remark }}</view>
				</view>
				<view class="u-flex ">
					<view class="u-flex number-box1" :class="{'gray': item.productId == '-999'}">
						<up-number-box :min="0" :max="getMaxNum(item)" :button-size="20" v-model="item.selectNum"
							integer :disabled="item.productId == '-999'">
							<template #minus>
								<view class="minus number-box-btn"></view>
							</template>
							<template #input>
								<view class=" u-row-center u-text-center input">
									<up-input :disabled="item.productId == '-999'"
										@change="parseIntNumber(item, $event,false)"
										@blur="parseIntNumber(item, $event,true)" v-model="item.selectNum" border="none"
										type="digit"></up-input>
								</view>
							</template>
							<template #plus>
								<view class="plus number-box-btn">
									<up-icon v-if="item.productId == '-999'" name="plus" color="#ccc" size="10"
										bold></up-icon>
									<up-icon v-else name="plus" color="#999" size="10" bold></up-icon>
								</view>
							</template>
						</up-number-box>
					</view>
				</view>

			</view>
		</view>

		<!-- 统一退菜理由 -->
		<view class="u-p-l-30 u-p-r-30 u-m-t-32 reason">
			<view class="u-font-24">
				<text class="color-999">退菜理由</text>
				<text class="color-red">*</text>
			</view>
			<view class="u-flex u-flex-wrap u-m-t-24">
				<view class="u-flex u-m-r-16 u-m-b-16" v-for="(item,index) in tags" :key="index">
					<up-tag @click="changeTagSel(item)" :text="item.label" plain borderColor="#E6FOFF" color="#318AFE"
						v-if="item.checked"></up-tag>
					<up-tag @click="changeTagSel(item)" borderColor="#E5E5E5" color="#666" :text="item.label" plain
						v-else></up-tag>
				</view>
			</view>
			<view class="u-m-t-24">
				<up-textarea v-model="form.note" placeholder="备注"></up-textarea>
			</view>
		</view>

		<view style="height: 200px;"></view>

		<!-- 按钮 -->
		<view class="u-p-t-18 u-p-l-30 u-p-r-30 u-p-b-32 fixed-bottom">
			<view class="u-font-28 u-m-b-24 text-center color-999">
				<text>当前共选中</text>
				<text class="color-red font-bold u-font-32 u-m-l-4 u-m-r-4">{{countNumber}}</text>
				<text>份菜品</text>
			</view>
			<my-button box-shadow shape="circle" @tap="confirm">确认退菜</my-button>
			<!-- <view class="u-m-t-10">
				<my-button @tap="onPageClose" shape="circle" bgColor="#fff" type="cancel" box-shadow>取消</my-button>
			</view> -->
		</view>

		<!-- 库存选择弹窗 -->
		<up-modal :show="confirmModal.show" title="提示" @close="confirmModalClose" @cancel="confirmModalClose"
			@confirm="confirmModalConfirm" showCancelButton>
			<view>
				<up-radio-group v-model="confirmModal.selRefundStock">
					<up-radio v-for="(item,index) in confirmModal.refundStocks" :key="index" :label="item.name"
						:name="item.key"></up-radio>
				</up-radio-group>
			</view>
		</up-modal>
	</view>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref
	} from 'vue';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import infoBox from '@/commons/utils/infoBox.js'
	import {
		getProductDetail
	} from '@/http/api/product.js'
	import {
		getCategoryDetail
	} from '@/http/api/cateGory.js'
	import {
		getHistoryOrder,
		refundOrder
	} from '@/http/api/order.js'

	// 订单信息
	const orderInfo = ref({})
	const detailMap = ref({})
	let orderId = ''

	// 弹窗
	const confirmModal = reactive({
		show: false,
		selRefundStock: false,
		refundStocks: [{
				name: '已上菜(仅退菜不退库存)',
				key: false
			},
			{
				name: '未上菜(退菜后退库存)',
				key: true
			}
		]
	})



	// 统一备注
	const form = reactive({
		note: ''
	})

	// 退菜标签
	const tags = ref([{
			label: "点错",
			checked: false
		},
		{
			label: "不想要了",
			checked: false
		},
		{
			label: "食材不足",
			checked: false
		},
		{
			label: "等待时间过长",
			checked: false
		}
	])

	let timer = null

	// ======================
	// 页面加载（适配你的真实数据结构）
	// ======================
	onLoad(async (options) => {
		orderId = options.id
		if (!orderId) {
			uni.showToast({
				title: '订单ID不存在',
				icon: 'none'
			})
			return
		}

		// 直接获取订单数据（你的返回就是完整订单对象）
		const res = await getHistoryOrder({
			orderId
		})
		orderInfo.value = res
		detailMap.value = res.detailMap

		// 给每个商品初始化可退数量
		for (let key in detailMap.value) {
			detailMap.value[key].forEach(item => {
				item.selectNum = item.num - item.returnNum
			})
		}
	})

	// 获取单个商品最大可退数量
	function getMaxNum(item) {
		return item.num - item.returnNum
	}

	// ======================
	// 数量处理
	// ======================
	function parseIntNumber(item, val, isNow) {
		let newval = val * 1
		const max = item.num - item.returnNum
		if (newval > max) newval = max
		if (newval < 0) newval = 0

		if (isNow) {
			item.selectNum = newval
			return
		}
		timer = setTimeout(() => {
			item.selectNum = newval
		}, 100)
	}

	// 标签选择
	function changeTagSel(item) {
		item.checked = !item.checked
	}

	// 关闭页面
	function onPageClose() {
		uni.navigateBack()
	}

	// 关闭库存弹窗
	function confirmModalClose() {
		confirmModal.show = false
		confirmModal.selRefundStock = false
	}

	// ======================
	// 收集所有选中的退菜商品
	// ======================
	function getAllSelectedGoods() {
		let list = []
		for (let groupKey in detailMap.value) {
			detailMap.value[groupKey].forEach(item => {
				if (item.selectNum > 0) {
					list.push({
						id: item.id,
						num: item.selectNum,
						returnAmount: item.selectNum * item.unitPrice,
						productId: item.productId
					})
				}
			})
		}
		return list
	}

	// ======================
	// 执行退菜
	// ======================
	async function refundGoods() {
		const refundDetails = getAllSelectedGoods()
		if (refundDetails.length === 0) {
			return infoBox.showToast('请选择退菜数量')
		}

		const selTag = tags.value.filter(i => i.checked).map(i => i.label).join(',')
		const note = selTag + (form.note ? ',' + form.note : '')

		let totalRefundAmount = 0
		refundDetails.forEach(i => totalRefundAmount += i.returnAmount)

		let par = {
			orderId: orderId,
			refundAmount: totalRefundAmount,
			refundReason: note,
			refundStock: confirmModal.selRefundStock,
			refundDetails
		}

		try {
			const res = await refundOrder(par)
			uni.showToast({
				title: '退菜成功',
				icon: 'success'
			})
			setTimeout(() => uni.navigateBack(), 1500)
		} catch (e) {
			uni.showToast({
				title: '退菜失败',
				icon: 'none'
			})
		}
	}

	// 确认退菜
	async function confirm() {
		const selTag = tags.value.filter(i => i.checked).map(i => i.label).join(',')
		const note = selTag + (form.note ? ',' + form.note : '')
		if (!note) return infoBox.showToast('请选择退菜理由')

		const list = getAllSelectedGoods()
		if (list.length === 0) return infoBox.showToast('请选择退菜数量')

		const shopInfo = uni.getStorageSync('shopInfo')
		let needShowModal = false

		// 判断是否显示库存选择弹窗
		if (shopInfo.refundMode == 1) {
			const res = await getGoodsCategory(list[0])
			if (res?.refundMode === 3) needShowModal = true
		}

		if (shopInfo.refundMode == 2) {
			const res = await getProductDetail(list[0].productId)
			if (res?.refundMode === 3) needShowModal = true
		}

		if (needShowModal) {
			confirmModal.show = true
			return
		}

		refundGoods()
	}

	// 获取商品分类
	async function getGoodsCategory(goods) {
		const res = await getProductDetail(goods.productId)
		if (res) {
			return await getCategoryDetail(res.categoryId)
		}
		return null
	}

	// 弹窗确认
	function confirmModalConfirm() {
		refundGoods()
		confirmModalClose()
	}

	onUnload(() => {
		if (timer) clearTimeout(timer)
	})



	// 计算所有选中商品的数量总和
	const countNumber = computed(() => {
		let total = 0;
		// 遍历所有分组
		for (let key in detailMap.value) {
			// 遍历该分组下的所有商品
			detailMap.value[key].forEach(item => {
				// 累加 selectNum
				total += item.selectNum || 0;
			});
		}
		return total;
	});
</script>

<style lang="scss" scoped>
	.page-container {
		min-height: 100vh;
		padding-bottom: 100rpx;
	}

	.group-wrap {
		background-color: #fff;
		padding: 32rpx 28rpx;
		border-radius: 18rpx;
	}
	.reason{
		background-color: #fff;
		padding: 32rpx 28rpx;
		border-radius: 18rpx;
	}
	.group-title {
		padding-bottom: 24rpx;
		margin-bottom: 24rpx;
		border-bottom: 1px solid #f7f8fa;
	}

	.number-box1 {
		background-color: #f7f8fa;
		padding: 0 10rpx;
		border-radius: 200rpx;
	}

	.number-box-btn {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60rpx;
		height: 60rpx;
		background: #fff;
		border-radius: 8rpx 0rpx 0rpx 8rpx;
		border: 2rpx solid #fff;
		box-shadow: 0 0 5px #eee;
		box-sizing: border-box;
		border-radius: 50%;
		overflow: hidden;
	}

	.input {
		// border: 2rpx solid #F9F9F9;
		width: 70rpx;
	}

	::v-deep .u-input__content__field-wrapper__field {
		height: 84rpx;
	}

	::v-deep .uni-input-input {
		text-align: center;
	}

	.gray {
		.minus::after {
			border-color: #ccc;
		}
	}

	.minus {
		&::after {
			content: '';
			display: block;
			width: 10rpx;
			height: 0rpx;
			border: 1px solid #999999;
		}
	}

	::v-deep .u-number-box {
		width: 100%;
	}
</style>