<template>
	<view class="container">

		<!-- 物品信息 -->
		<view class="form-card">

			<!-- 姓名 + 电话 并排 -->
			<view class="form-item row">
				<input class="input-field flex-item" placeholder="姓名" placeholder-class="placeholder" maxlength="20"
					v-model="formData.contactName" />
				<input class="input-field flex-item" placeholder="电话" placeholder-class="placeholder" maxlength="11"
					v-model="formData.contactPhone" />
			</view>

			<!-- 省市区选择 -->
			<picker mode="region" @change="changeAddress">
				<view class="form-item">
					<text :class="['address-text', formData.provinceName ? '' : 'placeholder']">
						{{ formData.provinceName ? formData.provinceName + ' ' + formData.cityName + ' ' + formData.countyName : '省市区' }}
					</text>
					<u-icon class="arrow" name='arrow-right' size="18"></u-icon>
				</view>
			</picker>

			<!-- 详细地址 -->
			<view class="form-item">
				<input class="input-field full-width" placeholder="详细地址" placeholder-class="placeholder"
					v-model="formData.detailedAddress" />
			</view>

			<!-- 设置默认和清空 -->
			<view class="form-item actions">
				<view class="action-left">
					<switch :checked="formData.defaultFlag == 1" color="#007AFF" @change="onDefaultChange" />
					<text class="action-text">设为默认寄件地址</text>
				</view>
				<view class="action-right" @click="clearForm">
					<text class="clear-text">清空</text>
				</view>
			</view>
		</view>

		<view class="section-title"  v-if="addressList.length > 0">最近使用地址</view>

		<!-- 最近使用地址 -->
		<view class="recent-address"  v-if="addressList.length > 0">
			<view class="address-item" v-for="(item, index) in addressList" :key="item.id"
			 @click="onSelectAddress(item)">
				<AddressInfo :address="item" />
			</view>
		</view>

		<!-- 确定按钮 -->
		<view class="submit-btn" @click="onConfirm">确定</view>

		<!-- 安全区域占位 -->
		<view class="safe-area"></view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import AddressInfo from '@/components/AddressInfo.vue'
	import {
		addBook,
		updateBook,
		getBook,getLastAddress
	} from '@/api/address.js'

	const addType = ref('') // 'sender' 或 'receiver'，表示从下单页面哪个字段进入
	
	const addressList = ref([])

	// 表单数据
	const formData = reactive({
		addressId:undefined,
		contactName: '',
		contactPhone: '',
		provinceName: '',
		cityName: '',
		countyName: '',
		addressId: null,
		detailedAddress: '',
		defaultFlag: 0
	})

	onLoad((option) => {
		if (option.id) {
			formData.addressId = option.id;
			getAddress();
			uni.setNavigationBarTitle({
				title: '编辑地址'
			});
		}
		addType.value = option.addType || '';
		getAddressList()
	});

	// 获取地址详情
	const getAddress = async () => {
		let res = await getBook(formData.addressId);
		let {
			addressId,
			contactName,
			contactPhone,
			countyName,
			defaultFlag,
			detailedAddress,
			provinceName,
			cityName
		} = res.data;
		Object.assign(formData, {
			addressId,
			contactName,
			contactPhone,
			cityName,
			countyName,
			defaultFlag,
			detailedAddress,
			provinceName
		});
	};

	// 选择省市区
	const changeAddress = (e) => {
		formData.provinceName = e.detail.value[0];
		formData.cityName = e.detail.value[1];
		formData.countyName = e.detail.value[2];
	};

	// 默认地址切换
	const onDefaultChange = (e) => {
		formData.defaultFlag = e.detail.value ? 1 : 0;
	};

	// 清空表单
	const clearForm = () => {
		formData.contactName = '';
		formData.contactPhone = '';
		formData.provinceName = '';
		formData.cityName = '';
		formData.countyName = '';
		formData.detailedAddress = '';
		formData.defaultFlag = 0;
		formData.addressId = null; // 清空ID，避免残留
	};

	// 校验手机号
	const isValidPhone = (phone) => /^1[3-9]\d{9}$/.test(phone);

	// 提交
	const onConfirm = async () => {
		// 姓名校验
		if (!formData.contactName || formData.contactName.trim() === '') {
			return uni.showToast({ title: '请输入姓名', icon: 'none' });
		}
		if (formData.contactName.length > 20) {
			return uni.showToast({ title: '姓名不能超过20个字符', icon: 'none' });
		}

		// 电话校验
		if (!formData.contactPhone) {
			return uni.showToast({ title: '请输入联系电话', icon: 'none' });
		}
		if (!isValidPhone(formData.contactPhone)) {
			return uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
		}

		// 省市区校验
		if (!formData.provinceName) {
			return uni.showToast({ title: '请选择省市区', icon: 'none' });
		}

		// 详细地址校验
		if (!formData.detailedAddress || formData.detailedAddress.trim() === '') {
			return uni.showToast({ title: '请输入详细地址', icon: 'none' });
		}
		if (formData.detailedAddress.length > 100) {
			return uni.showToast({ title: '详细地址不能超过100个字符', icon: 'none' });
		}
		uni.showLoading({
			title:'正在保存',
			mask: true
		})

		// 提交
		let api = formData.addressId ? updateBook(formData) : addBook(formData);
		let res = await api;

		if (res.code === 200) {
			uni.showToast({ title: '保存成功', icon: 'success' });
			debugger
			// 如果接口返回了新地址数据，更新到formData（特别是新增时的ID）
			if (!formData.addressId) {
				formData.addressId = res.data
			}
			debugger
			onSelectAddress(formData);
			uni.hideLoading()
		} else {
			uni.hideLoading()
			uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
		}
	};

	// 选择地址（用于返回数据给上一页）
	const onSelectAddress = (address) => {
		if (addType.value !== 'sender' && addType.value !== 'receiver') {
			return;
		}
		uni.$emit('addressSelected', {
			type: addType.value,
			address
		});
		
		uni.navigateBack() // 返回上一页
	};
	
	// 获取地址列表
	const getAddressList = () => {
		getLastAddress().then(res => {
			addressList.value = res.data
		}, err => {
		})
	}
	
</script>

<style scoped lang="less">
	.container {
		background-color: #F5F7FA;
		min-height: 100vh;
		padding: 20rpx 20rpx 30rpx 20rpx;
	}

	.form-card {
		background-color: #fff;
		border-radius: 32rpx;
		padding: 0 20rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		min-height: 100rpx;
		border-bottom: 1rpx solid #F1F3F8;
		padding: 0 0;

		&.row {
			gap: 20rpx;
		}

		&:last-child {
			border-bottom: none;
		}
	}

	/* 输入框通用样式 */
	.input-field {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 28rpx;
		color: #333;
		background: transparent;
		padding: 0;

		&.flex-item {
			flex: 1;
			width: auto;
			min-width: 0; // 防止溢出
		}

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

		.placeholder {
			color: #999;
		}
	}

	/* 省市区文字样式 */
	.address-text {
		flex: 1;
		font-size: 28rpx;
		line-height: 100rpx;
		color: #333;

		&.placeholder {
			color: #999;
		}
	}

	.arrow {
		margin-left: 16rpx;
		color: #999;
		font-size: 28rpx;
	}

	/* 操作按钮行 */
	.actions {
		justify-content: space-between;
		padding: 20rpx 0;
	}

	.action-left {
		display: flex;
		align-items: center;
	}

	.action-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 10rpx;
	}

	.clear-text {
		font-size: 28rpx;
		color: #1B64F0;
		line-height: 44rpx;
	}

	/* 最近地址（隐藏） */
	.section-title {
		height: 48rpx;
		font-size: 32rpx;
		color: #333333;
		line-height: 48rpx;
		margin: 20rpx 0;
		font-weight: bold;
	}

	.recent-address {
		background-color: #fff;
		padding: 0 30rpx;
	}

	.address-item {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	/* 确定按钮 */
	.submit-btn {
		position: fixed;
		bottom: 40rpx;
		left: 30rpx;
		right: 30rpx;
		width: 686rpx;
		height: 88rpx;
		background: #1B64F0;
		border-radius: 44rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 88rpx;
		z-index: 10;
	}

	.safe-area {
		height: 140rpx;
	}
</style>