<template>
	<view class="refund-step-two">
		<view class="warning-tip">
			<text>确认退款信息后提交，提交后不可再次退款。</text>
		</view>

		<!-- 遍历每个选中的商品 -->
		<view class="card" v-for="(item, index) in localGoods" :key="index">
			<view class="goods-item mb-30">
				<image :src="item.cover" mode="aspectFill" class="goods-cover"></image>
				<view class="goods-info">
					<view class="goods-name u-line-2">{{ item.bookName }}</view>
					<view class="price-box mt-10">
						<text class="price">¥{{ item.payPrice || item.price }}</text>
						<view v-if="item.canModifyNum == 1" class="num-box">
							<u-number-box v-model="item.refundNum" :min="1" :max="item.canRefundNum" @change="calculateRefundMoney(index)"></u-number-box>
						</view>
						<text v-else class="num">x{{ item.refundNum }}</text>
					</view>
				</view>
			</view>

			<u-cell-group :border="false">
				<u-cell-item v-if="refundType === '1'" title="货物状态" :value="item.shopStatusText" @click="openStatusPicker(index)"></u-cell-item>
				<u-cell-item title="退款原因" :value="item.refundReasonText" @click="openReasonPicker(index)"></u-cell-item>
				
				<view class="money-cell">
					<view class="cell-left">
						<text class="label">退款金额</text>
					</view>
					<view class="cell-right">
						<view class="edit-btn" v-if="item.canModifyMoney == 1" @click="openMoneyEdit(index)">
							<u-icon name="edit-pen" size="28"></u-icon>
							<text>修改</text>
						</view>
						<text class="money-text ml-20">¥{{ item.refundMoney }}</text>
					</view>
				</view>
				
				<u-cell-item title="上传描述和凭证" :value="getUploadStatusText(item)" 
					@click="openUploadPopup(index)" :border-bottom="false"></u-cell-item>
			</u-cell-group>
		</view>
		
		<!-- 如果是退货退款，还需要选择退货方式和地址？
		 原申请页面有退货方式，但图 3 并没有显示这部分，可能是在其它地方或者不需要？
		 我们根据原有的退货方式逻辑，在最底部或者顶部加入 -->
		<view class="card" v-if="refundType === '1'">
			<u-cell-group :border="false">
				<u-cell-item title="退货方式" :value="returnMethodText || '请选择'" @click="showReturnMethodPicker = true" required></u-cell-item>
			</u-cell-group>
			
			<view class="address-section" v-if="returnMethod === '1'" @click="chooseAddress">
				<view class="flex-a flex-j-b" v-if="address && address.name">
					<view class="address-label">取件地址</view>
					<view class="flex-d flex-1 ml-24" style="margin-right: 20rpx">
						<view class="flex-a flex-j-b mb-10">
							<view class="address-text">{{ address.name }}</view>
							<view class="address-text">{{ address.mobile }}</view>
						</view>
						<view class="address-text">{{ address.fullAddress }}</view>
					</view>
					<u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
				</view>
				<view class="flex-a flex-j-b" v-else>
					<view class="flex-a">
						<u-icon name="plus-circle-fill" :size="48" color="#38C148" top="2"></u-icon>
						<view class="ml-10 font-30 address-text">选择取件地址</view>
					</view>
					<u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
				</view>
			</view>
		</view>

		<view style="height: 140rpx;"></view>

		<!-- 底部操作栏 -->
		<view class="footer-bar">
			<view class="footer-left">
				<text class="total-label">共退款</text>
				<text class="total-money">¥{{ totalRefundMoney }}</text>
				<text class="total-num">共{{ totalRefundNum }}件</text>
			</view>
			<view class="footer-right">
				<view class="btn-wrap" style="margin-left: 30rpx;">
					<u-button shape="circle" :custom-style="cancelBtnStyle" @click="$emit('back')">上一步</u-button>
				</view>
				<view class="btn-wrap">
					<u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="submit">提交申请</u-button>
				</view>
			</view>
		</view>

		<!-- 修改退款金额弹窗 -->
		<u-popup v-model="showMoneyPopup" mode="bottom" border-radius="24">
			<view class="popup-container">
				<view class="popup-header">
					<text class="title">修改退款金额</text>
					<u-icon name="close" size="32" color="#999" @click="showMoneyPopup = false"></u-icon>
				</view>
				<view class="popup-content">
					<view class="input-row">
						<text>退款金额：</text>
						<u-input v-model="tempMoney" type="digit" placeholder="请输入退款金额" class="money-input" />
					</view>
					<view class="max-hint">最大可退金额: ¥{{ maxMoneyForCurrent }}</view>
				</view>
				<view class="popup-footer">
					<u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="confirmMoney">确认</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 上传描述和凭证弹窗 -->
		<u-popup v-model="showUploadPopup" mode="bottom" border-radius="24" height="800">
			<view class="popup-container full-height">
				<view class="popup-header">
					<text class="title">上传描述和凭证</text>
					<u-icon name="close" size="32" color="#999" @click="showUploadPopup = false"></u-icon>
				</view>
				<view class="popup-content flex-1">
					<view class="upload-textarea-box">
						<u-input v-model="tempDesc" type="textarea" placeholder="补充描述，有助于平台更好的处理售后问题" :height="100" maxlength="200" />
					</view>
					<view class="upload-area mt-20">
						<common-image-upload v-model="tempFileList" :max-count="5" code="shopRefund" width="160" height="160">
						</common-image-upload>
					</view>
				</view>
				<view class="popup-footer">
					<u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="confirmUpload">完成</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 退货方式弹窗 -->
		<u-select v-model="showReturnMethodPicker" :list="returnMethodList" @confirm="confirmReturnMethod"></u-select>
		
		<!-- 退款原因弹窗 -->
		<u-select v-model="showReasonPicker" :list="reasonList" @confirm="confirmReason"></u-select>
		
		<!-- 货物状态弹窗 -->
		<u-select v-model="showStatusPicker" :list="statusList" @confirm="confirmStatus"></u-select>
	</view>
</template>

<script>
	import CommonImageUpload from "@/components/image-upload.vue";

	export default {
		name: 'RefundStepTwo',
		components: {
			CommonImageUpload
		},
		props: {
			selectedGoods: {
				type: Array,
				default: () => []
			},
			refundType: {
				type: String,
				default: '1'
			},
			defaultAddress: {
				type: Object,
				default: () => null
			},
			reasonList: {
				type: Array,
				default: () => []
			},
			statusList: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				localGoods: [],
				
				showMoneyPopup: false,
				showUploadPopup: false,
				showReasonPicker: false,
				showStatusPicker: false,
				currentIndex: -1,
				
				tempMoney: '',
				maxMoneyForCurrent: '0.00',
				
				tempDesc: '',
				tempFileList: [],

				returnMethod: '3',
				returnMethodText: '自行寄回',
				showReturnMethodPicker: false,
				returnMethodList: [
					{ value: '1', label: '上门取件' },
					{ value: '2', label: '寄件点自寄' },
					{ value: '3', label: '自行寄回' }
				],
				
				address: null,

				submitBtnStyle: {
					height: '70rpx',
					fontSize: '28rpx',
					backgroundColor: '#38C148',
					color: '#ffffff',
					border: 'none',
					padding: '0'
				},
				cancelBtnStyle: {
					height: '70rpx',
					fontSize: '28rpx',
					backgroundColor: '#ffffff',
					color: '#333',
					border: '1px solid #ccc',
					padding: '0'
				}
			};
		},
		watch: {
			selectedGoods: {
				handler(val) {
					this.localGoods = JSON.parse(JSON.stringify(val));
				},
				deep: true,
				immediate: true
			},
			defaultAddress: {
				handler(val) {
					if (val) this.address = { ...val };
				},
				deep: true,
				immediate: true
			}
		},
		computed: {
			totalRefundMoney() {
				let total = 0;
				this.localGoods.forEach(item => {
					total += Number(item.refundMoney || 0);
				});
				return total.toFixed(2);
			},
			totalRefundNum() {
				let total = 0;
				this.localGoods.forEach(item => {
					total += Number(item.refundNum || 0);
				});
				return total;
			}
		},
		methods: {
			calculateRefundMoney(index) {
				const item = this.localGoods[index];
				// 简单按比例或单价计算最大可退金额和当前退款金额
				// 此处以单价 * 数量计算作为基准。如果后台返回了具体的单件金额或算法，可以进一步优化。
				const unitPrice = Number(item.payPrice || item.price || 0);
				const newMoney = (unitPrice * item.refundNum).toFixed(2);
				
				// 同步更新 canRefundMoney (如果有的话) 和 refundMoney
				this.$set(item, 'refundMoney', newMoney);
				this.$set(item, 'canRefundMoney', newMoney);
			},
			getUploadStatusText(item) {
				if ((item.description && item.description.trim().length > 0) || (item.fileUrlList && item.fileUrlList.length > 0)) {
					return '已补充';
				}
				return '上传有助处理退款';
			},
			openMoneyEdit(index) {
				this.currentIndex = index;
				const item = this.localGoods[index];
				this.tempMoney = String(item.refundMoney);
				this.maxMoneyForCurrent = String(item.canRefundMoney || 0);
				this.showMoneyPopup = true;
			},
			confirmMoney() {
				let val = Number(this.tempMoney);
				let max = Number(this.maxMoneyForCurrent);
				if (val < 0) val = 0;
				if (val > max) val = max;
				
				this.$set(this.localGoods[this.currentIndex], 'refundMoney', val.toFixed(2));
				this.showMoneyPopup = false;
			},
			openUploadPopup(index) {
				this.currentIndex = index;
				const item = this.localGoods[index];
				this.tempDesc = item.description || '';
				this.tempFileList = item.fileUrlList ? [...item.fileUrlList] : [];
				this.showUploadPopup = true;
			},
			confirmUpload() {
				const item = this.localGoods[this.currentIndex];
				this.$set(item, 'description', this.tempDesc);
				this.$set(item, 'fileUrlList', [...this.tempFileList]);
				this.showUploadPopup = false;
			},
			openStatusPicker(index) {
				this.currentIndex = index;
				this.showStatusPicker = true;
			},
			openReasonPicker(index) {
				this.currentIndex = index;
				this.showReasonPicker = true;
			},
			confirmStatus(e) {
				const item = this.localGoods[this.currentIndex];
				this.$set(item, 'shopStatus', e[0].value);
				this.$set(item, 'shopStatusText', e[0].label);
			},
			confirmReason(e) {
				const item = this.localGoods[this.currentIndex];
				this.$set(item, 'refundReason', e[0].value);
				this.$set(item, 'refundReasonText', e[0].label);
			},
			confirmReturnMethod(e) {
				this.returnMethod = e[0].value;
				this.returnMethodText = e[0].label;
			},
			chooseAddress() {
				uni.navigateTo({
					url: `/pages-mine/pages/address/list?id=${this.address ? this.address.id : ''}&isSelect=1`
				});
			},
			updateAddress(addr) {
				this.address = addr;
			},
			submit() {
				if (this.refundType === '1') {
					if (!this.returnMethod) {
						this.$u.toast('请选择退货方式');
						return;
					}
					if (this.returnMethod === '1' && (!this.address || !this.address.name)) {
						this.$u.toast('请选择取件地址');
						return;
					}
				}
				
				this.$emit('submit', {
					goodsList: this.localGoods,
					returnMethod: this.returnMethod,
					address: this.address
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.refund-step-two {
		padding-bottom: 140rpx;
	}

	.warning-tip {
		padding: 20rpx 30rpx;
		color: #38C148;
		font-size: 24rpx;
		background-color: #d1f2d8;
		margin-bottom: 20rpx;
	}

	.card {
		background-color: #fff;
		border-radius: 16rpx;
		margin: 0 20rpx 20rpx;
	}

	.goods-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		padding-bottom: 0;
		.goods-cover {
			width: 120rpx;
			height: 120rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
		}
		.goods-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			.goods-name {
				font-size: 28rpx;
				color: #333;
				line-height: 1.4;
			}
			.price-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				.price {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
				.num {
					font-size: 26rpx;
					color: #999;
				}
			}
		}
	}

	.mb-30 {
		margin-bottom: 30rpx;
	}
	.mt-10 {
		margin-top: 10rpx;
	}
	.ml-20 {
		margin-left: 20rpx;
	}

	.money-cell {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 26rpx 32rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #f5f5f5;

		.cell-left {
			.label {
				font-size: 28rpx;
				color: #333;
			}
		}

		.cell-right {
			display: flex;
			align-items: center;

			.edit-btn {
				display: flex;
				align-items: center;
				color: #666;
				font-size: 24rpx;
				margin-right: 10rpx;
				text {
					margin-left: 4rpx;
				}
			}

			.money-text {
				font-size: 32rpx;
				color: #38C148;
				font-weight: bold;
			}
		}
	}

	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 30rpx;
		padding-bottom: 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 100;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.footer-left {
			display: flex;
			align-items: baseline;
			.total-label {
				font-size: 28rpx;
				color: #38C148;
				font-weight: bold;
			}
			.total-money {
				font-size: 36rpx;
				color: #38C148;
				font-weight: bold;
				margin: 0 10rpx;
			}
			.total-num {
				font-size: 24rpx;
				color: #999;
			}
		}

		.footer-right {
			display: flex;
			align-items: center;
			flex: 1;
			justify-content: flex-end;
			gap: 40rpx;
			.btn-wrap {
				flex: 1;
				max-width: 200rpx;
			}
		}
	}

	.popup-container {
		padding: 30rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;

		&.full-height {
			height: 100%;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;
			flex-shrink: 0;

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

		.popup-content {
			margin-bottom: 40rpx;
			
			&.flex-1 {
				flex: 1;
				overflow-y: auto;
			}

			.input-row {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				font-size: 30rpx;

				.money-input {
					flex: 1;
					text-align: right;
				}
			}

			.max-hint {
				font-size: 24rpx;
				color: #999;
				text-align: right;
			}

			.upload-textarea-box {
				background-color: #f9f9f9;
				padding: 20rpx;
				border-radius: 12rpx;
			}
		}

		.popup-footer {
			flex-shrink: 0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}
	
	.address-section {
		padding: 26rpx 0;
		border-top: 1rpx solid #f5f5f5;
	}

	.address-text {
		color: #333333;
		font-family: PingFang SC;
		font-weight: 400;
	}

	.address-label {
		font-size: 28rpx;
		color: #909399;
		margin-right: 20rpx;
		width: 140rpx;
	}
	
	.mt-20 {
		margin-top: 20rpx;
	}
	.flex-1 {
		flex: 1;
	}
</style>
