<template>
	<view class="address-edit-container">
		<view class="page-header">
			<view class="back-btn" @tap="goBack">
				<image src="/assets/images/back-btn.png" mode="aspectFit" class="back-icon"></image>
			</view>
			<view class="page-title">填写收货地址</view>
			<view v-if="isEditMode" class="delete-btn" @tap="deleteAddress">删除</view>
			<view v-else class="placeholder"></view>
		</view>

		<view class="form-container">
			<view class="form-item">
				<text class="label">收货人</text>
				<input class="input" v-model="formData.name" placeholder="请输入收货人姓名" />
				<view class="wechat-import" @tap="importFromWechat">
					<text class="wechat-icon">💚</text>
					<text class="wechat-text">微信导入</text>
				</view>
			</view>

			<view class="form-item">
				<text class="label">手机号码</text>
				<input class="input" v-model="formData.phone" placeholder="请输入手机号码" type="number" maxlength="11" />
			</view>

			<view class="form-item">
				<text class="label">所在地区</text>
				<view class="region-select" @tap="showRegionPicker">
					<text class="region-text">{{ formData.region || '请选择省/市/区' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<view class="form-item">
				<text class="label">详细地址</text>
				<input class="textarea" v-model="formData.detailAddress" placeholder="请填写详细地址" auto-height />
			</view>

			<view class="form-item">
				<text class="label">门牌号</text>
				<input class="input" v-model="formData.houseNumber" placeholder="街道、门牌号等" />
			</view>

			<view class="default-switch" @tap="toggleDefault">
				<text class="switch-text">设为默认地址</text>
				<view class="switch" :class="{ 'active': formData.isDefault }">
					<view class="switch-dot" :class="{ 'active': formData.isDefault }"></view>
				</view>
			</view>
		</view>

		<view class="save-btn" @tap="handleSave" :class="{ 'disabled': !canSave }">保存</view>

		<!-- 省市区选择器 -->
		<view v-if="showPicker" class="picker-overlay" @tap="hideRegionPicker">
			<view class="picker-container" @tap.stop>
				<view class="picker-header">
					<view class="picker-cancel" @tap="hideRegionPicker">取消</view>
					<view class="picker-title">选择地区</view>
					<view class="picker-confirm" @tap="confirmRegion">确定</view>
				</view>
				<picker-view class="picker" :value="pickerValue" @change="onPickerChange">
					<picker-view-column>
						<view v-for="(item, index) in provinces" :key="index">{{ item }}</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in cities" :key="index">{{ item }}</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in districts" :key="index">{{ item }}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>
</template>

<script>
import { getAddressDetail, saveAddress, updateAddress, deleteAddress } from '@/api/address.js';

export default {
	data() {
		return {
			isEditMode: false,
			addressId: '',
			isLoading: false,
			formData: {
				name: '',
				phone: '',
				region: '',
				province: '',
				city: '',
				district: '',
				detailAddress: '',
				houseNumber: '',
				isDefault: false,
				email: '',
				postalCode: ''
			},
			showPicker: false,
			pickerValue: [0, 0, 0],
			provinces: ['浙江省', '江苏省', '广东省'],
			cities: ['杭州市', '南京市', '广州市'],
			districts: ['西湖区', '上城区', '江干区']
		}
	},
	computed: {
		canSave() {
			return this.formData.name && this.formData.phone &&
				this.formData.region && this.formData.detailAddress;
		}
	},
	onLoad(options) {
		// 判断是否为编辑模式
		this.isEditMode = !!options.id;
		this.addressId = options.id || '';

		// 如果是编辑模式，加载地址详情
		if (this.isEditMode) {
			this.loadAddressDetail();
		}
	},
	methods: {
		// 加载地址详情
		async loadAddressDetail() {
			if (!this.addressId) return;

			this.isLoading = true;
			try {
				const response = await getAddressDetail({ id: this.addressId });
				console.log('地址详情接口返回:', response);

				if (response.ok && response.data) {
					const addressData = response.data;

					// 填充表单数据
					this.formData = {
						name: addressData.name || '',
						phone: addressData.mobile || '',
						email: addressData.email || '',
						province: addressData.province || '',
						city: addressData.city || '',
						district: addressData.area || '',
						region: this.buildRegionString(addressData),
						detailAddress: addressData.detail || '',
						houseNumber: addressData.floorNo || '',
						postalCode: addressData.postalCode || '',
						isDefault: addressData.current || false
					};

					console.log('填充后的表单数据:', this.formData);
				} else {
					uni.showToast({
						title: response.msg || '获取地址详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取地址详情失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 构建地区字符串
		buildRegionString(addressData) {
			const parts = [];
			if (addressData.province) parts.push(addressData.province);
			if (addressData.city) parts.push(addressData.city);
			if (addressData.area) parts.push(addressData.area);
			return parts.join('/');
		},

		// 返回上一页
		goBack() {
			uni.navigateBack();
		},

		// 显示地区选择器
		showRegionPicker() {
			this.showPicker = true;
		},

		// 隐藏地区选择器
		hideRegionPicker() {
			this.showPicker = false;
		},

		// 选择器值变化
		onPickerChange(e) {
			this.pickerValue = e.detail.value;
			// 这里可以根据省份变化更新城市和区县列表
		},

		// 确认地区选择
		confirmRegion() {
			const [provinceIndex, cityIndex, districtIndex] = this.pickerValue;
			this.formData.province = this.provinces[provinceIndex];
			this.formData.city = this.cities[cityIndex];
			this.formData.district = this.districts[districtIndex];
			this.formData.region = `${this.formData.province}/${this.formData.city}/${this.formData.district}`;
			this.showPicker = false;
		},

		// 切换默认地址
		toggleDefault() {
			this.formData.isDefault = !this.formData.isDefault;
		},

		// 表单验证
		validateForm() {
			if (!this.formData.name.trim()) {
				uni.showToast({ title: '请输入收货人姓名', icon: 'none' });
				return false;
			}
			if (!this.formData.phone.trim()) {
				uni.showToast({ title: '请输入手机号码', icon: 'none' });
				return false;
			}
			if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
				uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
				return false;
			}
			if (!this.formData.region) {
				uni.showToast({ title: '请选择所在地区', icon: 'none' });
				return false;
			}
			if (!this.formData.detailAddress.trim()) {
				uni.showToast({ title: '请输入详细地址', icon: 'none' });
				return false;
			}
			return true;
		},

		// 处理保存操作
		handleSave() {
			if (!this.validateForm()) return;

			// 构建完整地址
			const addressInfo = {
				...this.formData,
				address: `${this.formData.region} ${this.formData.detailAddress} ${this.formData.houseNumber}`
			};

			// 根据模式调用不同的保存方法
			if (this.isEditMode) {
				this.updateAddress(addressInfo);
			} else {
				this.saveAddress(addressInfo);
			}
		},

		// 保存地址（新增）
		async saveAddress(addressInfo) {
			this.isLoading = true;
			try {
				// 构建API请求参数
				const apiData = {
					name: addressInfo.name,
					mobile: addressInfo.phone,
					email: addressInfo.email || '',
					province: addressInfo.province,
					city: addressInfo.city,
					area: addressInfo.district,
					detail: addressInfo.detailAddress,
					floorNo: addressInfo.houseNumber,
					postalCode: addressInfo.postalCode || '',
					current: addressInfo.isDefault
				};

				const response = await saveAddress(apiData);
				console.log('保存地址接口返回:', response);

				if (response.ok && response.success) {
					uni.showToast({
						title: '添加成功',
						icon: 'success',
						success: () => {
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}
					});
				} else {
					uni.showToast({
						title: response.msg || '保存失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('保存地址失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 更新地址（编辑）
		async updateAddress(addressInfo) {
			this.isLoading = true;
			try {
				// 构建API请求参数
				const apiData = {
					id: this.addressId,
					name: addressInfo.name,
					mobile: addressInfo.phone,
					email: addressInfo.email || '',
					province: addressInfo.province,
					city: addressInfo.city,
					area: addressInfo.district,
					detail: addressInfo.detailAddress,
					floorNo: addressInfo.houseNumber,
					postalCode: addressInfo.postalCode || '',
					current: addressInfo.isDefault
				};

				const response = await updateAddress(apiData);
				console.log('更新地址接口返回:', response);

				if (response.ok && response.success) {
					uni.showToast({
						title: '更新成功',
						icon: 'success',
						success: () => {
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}
					});
				} else {
					uni.showToast({
						title: response.msg || '更新失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('更新地址失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 删除地址
		deleteAddress() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个地址吗？',
				confirmText: '确定',
				cancelText: '取消',
				success: async (res) => {
					if (res.confirm) {
						this.isLoading = true;
						try {
							const response = await deleteAddress({ id: this.addressId });
							console.log('删除地址接口返回:', response);

							if (response.ok && response.success) {
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									success: () => {
										setTimeout(() => {
											uni.navigateBack();
										}, 1500);
									}
								});
							} else {
								uni.showToast({
									title: response.msg || '删除失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除地址失败:', error);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						} finally {
							this.isLoading = false;
						}
					}
				}
			});
		},

		// 返回上一页
		goBack() {
			uni.navigateBack();
		},

		// 微信导入功能
		importFromWechat() {
			// 实际项目中这里应该调用微信API导入地址
			uni.showToast({
				title: '微信导入功能待实现',
				icon: 'none'
			});
		}
	}
}
</script>

<style scoped>
.address-edit-container {
	padding-bottom: 200rpx;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background-color: #ffffff;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
}

.back-btn {
	width: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	width: 24rpx;
	height: 42rpx;
}

.delete-btn {
	box-sizing: border-box;
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	border: 1px solid #E34D59;
	border-radius: 12rpx;
	width: 106rpx;
	height: 38rpx;
	font-size: 28rpx;
	color: #E34D59;
}

.placeholder {
	width: 60rpx;
}

.page-title {
	font-size: 34rpx;
	font-weight: 600;
	color: #333333;
	flex: 1;
	text-align: center;
}

.form-container {
	margin-top: 120rpx;
	padding: 0;
}

.form-item {
	display: flex;
	align-items: center;
	margin-bottom: 0;
	padding: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	width: 100%;
	box-sizing: border-box;
}

.label {
	font-size: 30rpx;
	color: #333333;
	width: 120rpx;
	flex-shrink: 0;
	margin-right: 20rpx;
}

.input {
	flex: 1;
	font-size: 30rpx;
	padding: 0;
	border: none;
	outline: none;
}

.wechat-import {
	display: flex;
	align-items: center;
	margin-left: 20rpx;
}

.wechat-icon {
	font-size: 32rpx;
	margin-right: 5rpx;
}

.wechat-text {
	color: #09BB07;
	font-size: 28rpx;
}

.textarea {
	flex: 1;
	font-size: 30rpx;
	min-height: 80rpx;
	padding: 0;
	resize: none;
	align-items: center;
	justify-content: center;
	line-height: 1.5;
	border: none;
	outline: none;
}

.region-select {
	flex: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
}

.region-text {
	font-size: 30rpx;
	color: #999999;
}

.arrow {
	font-size: 36rpx;
	color: #999999;
}

.default-switch {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	width: 100%;
	box-sizing: border-box;
}

.switch-text {
	font-size: 30rpx;
	color: #333333;
}

.switch {
	width: 80rpx;
	height: 48rpx;
	background-color: #D3A458;
	border-radius: 48rpx;
	position: relative;
}

.switch-dot {
	width: 42rpx;
	height: 42rpx;
	background-color: #ffffff;
	border-radius: 50%;
	position: absolute;
	top: 3rpx;
	right: 3rpx;
}

.save-btn {
	margin: 30rpx auto;
	width: 680rpx;
	height: 100rpx;
	line-height: 100rpx;
	background-color: #D3A458;
	color: #ffffff;
	text-align: center;
	font-size: 32rpx;
	border-radius: 66rpx;
	position: fixed;
	bottom: 30rpx;
	left: 50%;
	transform: translateX(-50%);
	font-weight: 500;
	font-family: PingFang SC;
	padding: 0;
}

.save-btn.disabled {
	background-color: #cccccc;
	color: #ffffff;
}

.picker-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 200;
	display: flex;
	justify-content: flex-end;
}

.picker-container {
	background-color: #ffffff;
	width: 100%;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 30rpx;
	border-bottom: 1rpx solid #e0e0e0;
}

.picker-cancel,
.picker-confirm {
	font-size: 32rpx;
	color: #666666;
}

.picker-confirm {
	color: #D3A458;
}

.picker-title {
	font-size: 34rpx;
	font-weight: bold;
}

.picker {
	height: 500rpx;
}
</style>