<template>
	<view class="container">
		<view class="form-card-textarea">
			<view class="form-item">
				<textarea class="input-field-textarea flex-item" placeholder="请输入文本，自动识别姓名、电话和地址"
					placeholder-class="placeholder" v-model="textArea" maxlength="250" />
			</view>

			<view class="form-item">
				<view class="search-btn" v-if='!textArea' @click="handleSearch(1)">
					粘贴并识别
				</view>
				<view class="search-btn" v-else @click="handleSearch(2)">
					识别
				</view>
			</view>
			<text>识别后，请检查拆分地址信息是否准确，如有遗漏请及时补充</text>
		</view>

		<!-- 物品信息 -->
		<view class="form-card" style="margin-top: 20rpx;">
			<!-- 姓名 + 电话 并排 -->
			<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="add-btn-container">
			<view class="submit-btn" @click="onConfirm">确定</view>
		</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,
		getAddressInfo
	} from '@/api/address.js'

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

	const addressList = ref([])

	const textArea = ref('')

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

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


	// 粘贴并识别功能
	const handleSearch = async (type) => {
		try {
			// 1. 读取剪贴板内容
			const clipboardText = await new Promise((resolve, reject) => {
				uni.getClipboardData({
					success: res => resolve(res.data),
					fail: err => reject(err)
				});
			});

			if (type == 1) {
				if (!clipboardText) {
					uni.showToast({
						title: '剪贴板内容为空',
						icon: 'none'
					});
					return;
				}

				// 可选：将剪贴板内容显示到文本域中，方便用户查看
				textArea.value = clipboardText;
			}

			uni.showLoading({
				title: '识别中...',
				mask: true
			});

			// 2. 调用接口解析地址
			const params = {
				param: textArea.value
			}; // 根据后端接口要求调整参数格式
			const res = await getAddressInfo(params);
			uni.hideLoading();

			if (res.code === 200 && res.data?.result?.length > 0) {
				const result = res.data.result[0];

				// 填充姓名
				if (result.name) {
					formData.contactName = result.name;
				}

				// 填充电话（取第一个手机号）
				if (result.mobile && result.mobile.length > 0) {
					formData.contactPhone = result.mobile[0];
				}

				// 填充省市区
				if (result.xzq) {
					// 从 fullName 中拆分省市区
					if (result.xzq.fullName) {
						const parts = result.xzq.fullName.split(',').map(s => s.trim());
						formData.provinceName = parts[0] || '';
						formData.cityName = parts[1] || '';
						formData.countyName = parts[2] || '';
					} else {
						// 兼容旧的字段
						formData.provinceName = result.xzq.province || '';
						formData.cityName = result.xzq.city || '';
						formData.countyName = result.xzq.district || '';
					}

					// 填充详细地址：优先使用 subArea，否则尝试从完整地址中去除省市区前缀
					if (result.xzq.subArea) {
						formData.detailedAddress = result.xzq.subArea;
					} else if (result.address) {
						const fullAddr = result.address;
						const prefix = `${formData.provinceName}${formData.cityName}${formData.countyName}`;
						if (fullAddr.startsWith(prefix)) {
							formData.detailedAddress = fullAddr.substring(prefix.length);
						} else {
							formData.detailedAddress = fullAddr; // 保底
						}
					}
				}

				uni.showToast({
					title: '识别成功,请核对地址信息',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res.message || '识别失败，请重试',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			});
			console.error('粘贴识别错误:', error);
		}
	};

	// 获取地址详情
	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'
			});

			// 如果接口返回了新地址数据，更新到formData（特别是新增时的ID）
			if (!formData.addressId) {
				formData.addressId = res.data
			}
			if (addType.value !== 'sender' && addType.value !== 'receiver') {
				uni.navigateBack() // 返回上一页
				return;
			}
			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 0rpx 30rpx 0rpx;
	}

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

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

		.search-btn {
			width: 204rpx;
			height: 72rpx;
			background: #1B64F0;
			border-radius: 38rpx;
			font-weight: 400;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 72rpx;
			text-align: center;
			font-style: normal;
			position: absolute;
			right: 40rpx;

		}
	}

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

		&.row {
			gap: 20rpx;
		}

		&.column {
			flex-direction: column;
		}

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

	.input-field-textarea {
		height: 150rpx;
		line-height: 48rpx;
		font-size: 28rpx;
		color: #333;
		background: transparent;
		padding: 20rxp 0rpx;

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

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

		.placeholder {
			color: #999;
		line-height: 48rpx;
		}
	}

	/* 输入框通用样式 */
	.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;
		font-weight: bold;
	}

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

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

	.add-btn-container {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		padding: 32rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		box-sizing: border-box;

		/* 确定按钮 */
		.submit-btn {
			height: 88rpx;
			background: #1B64F0;
			border-radius: 44rpx;
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center
		}

	}

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