<template>
	<view class="express-form-container">
		<!-- 订单摘要卡片 -->
		<view class="order-summary-card" v-if="orderInfo.orderNo">
			<view class="summary-row">
				<view class="label">订单号</view>
				<view class="value">{{ orderInfo.orderNo }}</view>
			</view>
			<view class="summary-row" v-if="orderInfo.deviceNo">
				<view class="label">设备号</view>
				<view class="value">{{ orderInfo.deviceNo }}</view>
			</view>
			<view class="summary-row" v-if="orderInfo.startTime">
				<view class="label">开放时间</view>
				<view class="value">{{ orderInfo.startTime }}</view>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<view class="form-title">填写快递归还信息</view>
			
			<view class="input-wrapper">
				<view class="input-label">联系电话</view>
				<input class="input-field" type="number" v-model="phone" maxlength="20" />
			</view>
			
			<view class="input-wrapper">
				<view class="input-label">快递单号</view>
				<input class="input-field" type="text" v-model="trackingNumber"
					:placeholder="isFillMode ? '请输入需要补填的快递单号' : '请输入快递单号（可先留空）'" maxlength="40" />
			</view>
			
			<view class="tips" v-if="tipsText">{{ tipsText }}</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" :class="{ disabled: submitting }" @click="!submitting && handleSubmit()">
			{{ isFillMode ? '确认补填' : '提交信息' }}
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		queryById
	} from '@/config/api/order.js'
	import {
		applyExpressReturn,
		getExpressReturnByOrder,
		getExpressReturnDetail,
		fillExpressTrackingNumber
	} from '@/config/api/expressReturn.js'

	const orderId = ref('')
	const recordId = ref('')
	const isFillMode = ref(false)
	const orderInfo = reactive({
		orderNo: '',
		deviceNo: '',
		startTime: ''
	})

	const phone = ref('')
	const trackingNumber = ref('')
	const tipsText = ref('')
	const submitting = ref(false)

	onLoad(async (options) => {
		orderId.value = options?.orderId || ''
		recordId.value = options?.id || ''
		isFillMode.value = !!recordId.value

		if (isFillMode.value) {
			await loadRecordAndOrderByRecord()
			return
		}

		if (!orderId.value) {
			uni.showToast({
				title: '缺少订单号',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1200)
			return
		}
		await loadOrder()
		await checkExistingExpressReturn()
	})

	const loadOrder = async () => {
		try {
			uni.showLoading({
				title: '加载中'
			})
			const res = await queryById(orderId.value)
			if (res?.code === 200 && res.data) {
				orderInfo.orderNo = res.data.orderNo || res.data.orderId || ''
				orderInfo.deviceNo = res.data.deviceNo || ''
				orderInfo.startTime = res.data.startTime || res.data.createTime || ''
				// 默认联系电话可回填订单上的手机号（若有）
				if (res.data.phone && !phone.value) phone.value = res.data.phone
			} else {
				throw new Error(res?.msg || '获取订单失败')
			}
		} catch (e) {
			uni.showToast({
				title: e.message || '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const loadRecordAndOrderByRecord = async () => {
		try {
			uni.showLoading({
				title: '加载中'
			})
			const res = await getExpressReturnDetail(recordId.value)
			if (res?.code === 200 && res.data) {
				if (res.data.orderId) {
					orderId.value = res.data.orderId
					await loadOrder()
				}
				if (res.data.userPhone && !phone.value) phone.value = res.data.userPhone
			} else {
				throw new Error(res?.msg || '获取记录失败')
			}
		} catch (e) {
			uni.showToast({
				title: e.message || '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const checkExistingExpressReturn = async () => {
		try {
			const res = await getExpressReturnByOrder(orderId.value)
			if (res && res.code === 200 && res.data) {
				const rec = res.data
				if (rec.status === 0) {
					recordId.value = rec.id
					uni.showModal({
						title: '提示',
						content: '已存在快递归还申请，是否前往补填快递单号？',
						confirmText: '去补填',
						cancelText: '取消',
						success: (r) => {
							if (r.confirm) {
								uni.redirectTo({
									url: `/pages/expressReturn/addExpressReturn?id=${rec.id}`
								})
							}
						}
					})
					return
				} else {
					uni.showToast({
						title: '已有归还记录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.redirectTo({
							url: `/pages/expressReturn/detail?id=${rec.id}`
						})
					}, 800)
				}
			}
		} catch (e) {
			// 无记录则忽略
		}
	}

	const validate = () => {
		// 简单手机检查（兼容座机/国际号，放宽到至少 5 位数字）
		const digits = (phone.value || '').replace(/\D/g, '')
		if (!digits || digits.length < 5) {
			uni.showToast({
				title: '请填写有效联系电话',
				icon: 'none'
			})
			return false
		}
		if (isFillMode.value && !trackingNumber.value) {
			uni.showToast({
				title: '请填写快递单号',
				icon: 'none'
			})
			return false
		}
		return true
	}

	const handleSubmit = async () => {
		if (!validate() || submitting.value) return
		submitting.value = true
		try {
			uni.showLoading({
				title: isFillMode.value ? '补填中' : '提交中'
			})
			let res
			if (isFillMode.value) {
				res = await fillExpressTrackingNumber({
					id: Number(recordId.value),
					logisticsTrackingNumber: trackingNumber.value
				})
			} else {
				res = await applyExpressReturn({
					orderId: orderId.value,
					logisticsTrackingNumber: trackingNumber.value,
					remark: ''
				})
			}
			if (res && res.code === 200) {
				uni.showToast({
					title: isFillMode.value ? '补填成功' : '提交成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 800)
			} else {
				throw new Error(res?.msg || (isFillMode.value ? '补填失败' : '提交失败'))
			}
		} catch (e) {
			uni.showToast({
				title: e.message || (isFillMode.value ? '补填失败' : '提交失败'),
				icon: 'none'
			})
		} finally {
			submitting.value = false
			uni.hideLoading()
		}
	}
</script>

<style lang="scss" scoped>
	.express-form-container {
		min-height: 100vh;
		background: #f5f5f5;
		padding: 40rpx 32rpx 180rpx;
	}

	/* 订单摘要卡片 - 淡绿色背景 */
	.order-summary-card {
		background: linear-gradient(135deg, #d4f4dd 0%, #e8f8ed 100%);
		border-radius: 24rpx;
		padding: 40rpx 32rpx;
		margin-bottom: 40rpx;

		.summary-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;

			.label {
				font-size: 28rpx;
				color: #333333;
				font-weight: 400;
			}

			.value {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
			}
		}
	}

	/* 表单区域 */
	.form-section {
		background: transparent;
		margin-bottom: 40rpx;

		.form-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333333;
			margin-bottom: 32rpx;
		}

		.input-wrapper {
			position: relative;
			margin-bottom: 32rpx;

			.input-label {
				position: absolute;
				top: -14rpx;
				left: 32rpx;
				font-size: 24rpx;
				color: #666666;
				background: #ffffff;
				padding: 0 12rpx;
				z-index: 1;
			}

			.input-field {
				width: 100%;
				height: 100rpx;
				background: #ffffff;
				border: 2rpx solid #333333;
				border-radius: 48rpx;
				padding: 0 32rpx;
				font-size: 28rpx;
				color: #333333;
				line-height: 100rpx;
				box-sizing: border-box;
			}

			.input-field::placeholder {
				color: #cccccc;
			}
		}

		.tips {
			margin-top: 16rpx;
			padding: 0 16rpx;
			font-size: 24rpx;
			color: #999999;
		}
	}

	/* 提交按钮 */
	.submit-btn {
		position: fixed;
		left: 32rpx;
		right: 32rpx;
		bottom: 60rpx;
		bottom: calc(60rpx + env(safe-area-inset-bottom));
		height: 96rpx;
		background: linear-gradient(135deg, #7cd89f 0%, #6bc98c 100%);
		border-radius: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 600;
		color: #ffffff;
		box-shadow: 0 8rpx 24rpx rgba(124, 216, 159, 0.3);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 4rpx 16rpx rgba(124, 216, 159, 0.2);
		}

		&.disabled {
			opacity: 0.5;
			pointer-events: none;
		}
	}
</style>