<template>
	<view class="apply-refund-page">
		<refund-step-one 
			v-if="currentStep === 1"
			:goods-list="mergedGoods"
			:refund-type.sync="refundType"
			:reason-list="reasonList"
			:status-list="statusList"
			@next="handleStepOneNext"
		/>
		
		<refund-step-two
			v-if="currentStep === 2"
			:selected-goods="selectedGoods"
			:refund-type="refundType"
			:default-address="address"
			:reason-list="reasonList"
			:status-list="statusList"
			@back="currentStep = 1"
			@submit="handleSubmit"
		/>
	</view>
</template>

<script>
	import RefundStepOne from '../components/refund-step-one.vue';
	import RefundStepTwo from '../components/refund-step-two.vue';

	export default {
		components: {
			RefundStepOne,
			RefundStepTwo
		},
		data() {
			return {
				orderId: '',
				targetDetailOrderId: '',
				isModify: false,
				refundOrderId: '',
				
				orderInfo: null,
				mergedGoods: [], // 合并了 applyRefundPre 返回的字段
				selectedGoods: [], // Step1 选中的商品及其状态/原因
				
				refundType: '1', // 1: 退货退款, 2: 仅退款
				currentStep: 1,
				
				reasonList: [],
				statusList: [
					{ value: '1', label: '未收到货' },
					{ value: '2', label: '已收到货' }
				],
				
				address: {} // 默认取件地址
			};
		},
		onLoad(options) {
			this.getRefundReasons();
			if (options.isModify == '1' && options.refundOrderId) {
				this.isModify = true;
				this.refundOrderId = options.refundOrderId;
				// 修改模式暂且保留老逻辑的兼容，由于需求只给了正常流程，先重点处理正常流程
				this.loadRefundDetail();
			} else if (options.orderId) {
				this.orderId = options.orderId;
				if (options.detailOrderId) {
					this.targetDetailOrderId = options.detailOrderId;
				}
				this.loadOrderDetail();
			}
		},
		onShow() {
			// 如果在第二步去了地址选择页，返回后更新地址
			let selectAddr = uni.getStorageSync("selectAddr");
			if (selectAddr) {
				this.address = selectAddr;
				uni.removeStorageSync("selectAddr");
			}
		},
		watch: {
			refundType(newVal) {
				// 切换退款类型时重新拉取预览数据
				if (this.orderInfo && !this.isModify) {
					this.fetchPreRefundData();
				}
			}
		},
		methods: {
			getRefundReasons() {
				uni.$u.http.get("/token/common/getDictOptions?type=shop_order_complaints_options").then(res => {
					if (res.code === 200) {
						this.reasonList = res.data.map(item => ({
							value: item.dictValue || item.dictLabel,
							label: item.dictLabel
						}));
					}
				});
			},
			loadOrderDetail() {
				this.$u.api.getShopOrderDetailAjax({ orderId: this.orderId }).then(res => {
					if (res.code === 200) {
						this.orderInfo = res.data;
						
						// 根据订单状态设置默认售后类型
						// status <= 3: 仅退款；status > 3: 退货退款
						if (this.orderInfo.status <= 3) {
							this.refundType = '2'; // 仅退款
						} else {
							this.refundType = '1'; // 退货退款
						}

						this.address = {
							id: this.orderInfo.receiverAddressId,
							name: this.orderInfo.receiverName,
							mobile: this.orderInfo.receiverMobile,
							fullAddress: this.orderInfo.receiverAddress,
						};
						
						this.fetchPreRefundData();
					}
				});
			},
			fetchPreRefundData() {
				if (!this.orderInfo || !this.orderInfo.detailVoList) return;
				
				// 此时全量传入后端进行校验
				const detailOrderIdList = this.orderInfo.detailVoList.map(item => item.detailOrderId || item.id);
				
				if (detailOrderIdList.length === 0) {
					this.buildMergedGoods({});
					return;
				}

				this.$u.api.applyRefundPreAjax({
					orderId: this.orderId,
					detailOrderIdList: detailOrderIdList,
					refundType: this.refundType
				}).then(res => {
					if (res.code === 200) {
						const preDataMap = {};
						res.data.forEach(item => {
							preDataMap[item.detailOrderId] = item;
						});
						this.buildMergedGoods(preDataMap);
					}
				});
			},
			buildMergedGoods(preDataMap) {
				// 保留已选中的状态，如果是第一次则按 targetDetailOrderId 选中
				const isFirst = this.mergedGoods.length === 0;
				
				this.mergedGoods = this.orderInfo.detailVoList.map(item => {
					const id = item.detailOrderId || item.id;
					const preData = preDataMap[id] || {};
					
					// 查找是否已经存在
					const existing = this.mergedGoods.find(m => (m.detailOrderId || m.id) === id);
					
					// 根据后端返回的字段和当前退款类型判断是否可选
					let isDisabled = false;
					if (this.refundType === '1') {
						// 退货退款
						isDisabled = preData.canRefund === 0;
					} else if (this.refundType === '2') {
						// 仅退款
						isDisabled = preData.canRefundOnlyMoney === 0;
					}
					
					let checked = true;
					if (isDisabled) {
						checked = false;
					} else if (isFirst && this.targetDetailOrderId) {
						checked = (String(id) === String(this.targetDetailOrderId));
					} else if (existing) {
						checked = existing.checked;
					}
					
					return {
						...item,
						...preData, // 合并新接口的字段：canRefundNum, canRefundMoney, canModifyNum, canModifyMoney
						disabled: isDisabled,
						checked: checked,
						refundNum: preData.canRefundNum || item.num,
						refundMoney: preData.canRefundMoney || 0,
						shopStatus: existing ? existing.shopStatus : '',
						shopStatusText: existing ? existing.shopStatusText : '',
						refundReason: existing ? existing.refundReason : '',
						refundReasonText: existing ? existing.refundReasonText : '',
						description: existing ? existing.description : '',
						fileUrlList: existing ? existing.fileUrlList : []
					};
				});
			},
			loadRefundDetail() {
				// 修改模式的兼容逻辑（如果需要的话，按原有代码逻辑映射到新组件数据结构）
				this.$u.api.getNewRefundOrderDetailAjax({
					refundOrderId: this.refundOrderId
				}).then(res => {
					if (res.code === 200) {
						const data = res.data;
						this.orderId = data.originOrderId;
						this.refundType = String(data.refundType);
						
						this.mergedGoods = [{
							...data,
							id: data.detailOrderId,
							checked: true,
							refundNum: data.refundNum || 1,
							refundMoney: data.refundMoney || 0,
							shopStatus: String(data.shopStatus),
							shopStatusText: String(data.shopStatus) === '1' ? '未收到货' : '已收到货',
							refundReason: data.refundReason,
							refundReasonText: data.refundReason,
							description: data.description || '',
							fileUrlList: data.fileUrlList || [],
							// 假装可以修改，修改模式后端未返回canModify，暂设1
							canModifyMoney: 1, 
							canModifyNum: 1,
							canRefundMoney: data.refundMoney || 0,
							canRefundNum: data.refundNum || 1
						}];
						
						this.address = {
							id: data.sendAddressId,
							name: data.sendName,
							mobile: data.sendMobile,
							fullAddress: data.sendAddress,
						};
					}
				});
			},
			handleStepOneNext(payload) {
				this.selectedGoods = payload.selectedGoods;
				this.currentStep = 2;
			},
			handleSubmit(payload) {
				const { goodsList, returnMethod, address } = payload;
				
				let params = {};
				
				if (this.isModify) {
					// 修改申请，只针对单件商品，取选中的第一件商品数据
					const item = goodsList[0];
					params = {
						orderId: this.orderId,
						refundOrderId: this.refundOrderId,
						refundType: this.refundType,
						sendType: returnMethod || '',
						addressId: (address && address.id) ? address.id : '',
						refundNum: item.refundNum,
						refundMoney: item.refundMoney,
						shopStatus: item.shopStatus,
						refundReason: item.refundReason,
						description: item.description,
						fileUrlList: item.fileUrlList || []
					};
				} else {
					// 正常申请售后，可能是多件商品
					const refundDetailList = goodsList.map(item => ({
						detailOrderId: item.detailOrderId || item.id,
						num: item.refundNum,
						refundMoney: item.refundMoney,
						shopStatus: item.shopStatus,
						refundReason: item.refundReason,
						description: item.description,
						fileUrlList: item.fileUrlList || []
					}));
					
					params = {
						orderId: this.orderId,
						refundDetailList: refundDetailList,
						refundType: this.refundType,
						sendType: returnMethod || '',
						addressId: (address && address.id) ? address.id : ''
					};
				}
				
				// 如果是退货退款(1) 并且是上门取件(1)，传递地址对象(兼容旧逻辑)
				if (this.refundType === '1' && returnMethod === '1' && address) {
					params.address = address;
				}

				const api = this.isModify ? this.$u.api.refundApplyModifyAjax : this.$u.api.applyRefundAjax;
				
				uni.showLoading({ title: '提交中' });
				api(params).then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						this.$u.toast(this.isModify ? '修改成功' : '提交成功');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						this.$u.toast(res.msg || (this.isModify ? '修改失败' : '提交失败'));
					}
				}).catch(() => {
					uni.hideLoading();
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.apply-refund-page {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
</style>
