<template>
	<page-container title="编辑地址" :showBack="true">
		<view class="address-form">
			<view class="form-item">
				<view class="form-label required">收货人</view>
				<input class="form-input" type="text" v-model="addressData.receiver_name" placeholder="收货人姓名" />
			</view>

			<view class="form-item">
				<view class="form-label required">电话</view>
				<input class="form-input" type="number" v-model="addressData.receiver_phone" placeholder="收货人电话"
					maxlength="11" />
			</view>

			<view class="form-item address-item">
				<view class="form-label required address-label">详细地址</view>
				<textarea class="form-textarea" v-model="addressData.detailed_address" placeholder="请填写详细地址"
					auto-height />
			</view>

			<view class="form-item switch-item">
				<view class="form-label">设为默认</view>
				<switch :checked="addressData.is_default === 1" @change="switchChange" color="#1296db" />
			</view>
		</view>

		<view class="btn-save" @click="saveAddress">
			<text>保存</text>
		</view>

		<view class="btn-delete" v-if="isEdit" @click="showDeleteConfirm">
			<text>删除</text>
		</view>
	</page-container>
</template>

<script>
import PageContainer from '@/components/page-container/page-container.vue'
import { addAddress, updateAddress, deleteAddress, getAddressDetail } from '@/common/server/userAddress.js'

export default {
	components: {
		PageContainer
	},
	data() {
		return {
			isEdit: false,
			addressId: null,
			addressData: {
				receiver_name: '',
				receiver_phone: '',
				detailed_address: '',
				is_default: 0
			},
			eventChannel: null
		}
	},
	onLoad(options) {
		this.eventChannel = this.getOpenerEventChannel();

		// 判断是编辑还是新增
		if (options && options.id) {
			this.isEdit = true;
			this.addressId = options.id;
			// 获取地址详情
			this.getAddressDetail();
		}
	},
	methods: {
		// 获取地址详情（编辑模式）
		async getAddressDetail() {
			try {
				uni.showLoading({
					title: '加载中...'
				});

				const res = await getAddressDetail(this.addressId);

				uni.hideLoading();

				if (res.status === 1 && res.data) {
					// 将API返回的数据映射到表单数据
					this.addressData = {
						receiver_name: res.data.receiver_name,
						receiver_phone: res.data.receiver_phone,
						detailed_address: res.data.detailed_address,
						is_default: res.data.is_default === 1 ? 1 : 0
					};
				} else {
					uni.showToast({
						title: res.msg || '获取地址详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('获取地址详情失败', error);
				uni.showToast({
					title: '网络异常，请稍后再试',
					icon: 'none'
				});
			}
		},

		// 开关状态改变
		switchChange(e) {
			this.addressData.is_default = e.detail.value ? 1 : 0;
		},

		// 保存地址
		async saveAddress() {
			// 表单验证
			if (!this.addressData.receiver_name) {
				return uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				});
			}

			if (!this.addressData.receiver_phone) {
				return uni.showToast({
					title: '请输入联系电话',
					icon: 'none'
				});
			}

			// 手机号格式验证
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!phoneReg.test(this.addressData.receiver_phone)) {
				return uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
			}

			if (!this.addressData.detailed_address) {
				return uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				});
			}

			try {
				uni.showLoading({
					title: '保存中...'
				});

				let res;
				if (this.isEdit) {
					// 编辑模式，调用更新接口
					res = await updateAddress({
						...this.addressData,
						id: this.addressId
					});
				} else {
					// 新增模式，调用添加接口
					res = await addAddress(this.addressData);
				}

				uni.hideLoading();

				if (res.status === 1) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});

					// 返回上一页并刷新地址列表
					setTimeout(() => {
						// 返回并通知上一页刷新
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						if (prevPage && prevPage.$vm) {
							// 确保上一页面有load方法
							prevPage.$vm.load && prevPage.$vm.load();
						}
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '保存失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('保存地址失败', error);
				uni.showToast({
					title: '网络异常，请稍后再试',
					icon: 'none'
				});
			}
		},

		// 显示删除确认
		showDeleteConfirm() {
			uni.showModal({
				title: '提示',
				content: '确定要删除该收货地址吗？',
				success: async (res) => {
					if (res.confirm) {
						await this.deleteAddress();
					}
				}
			});
		},

		// 删除地址
		async deleteAddress() {
			try {
				uni.showLoading({
					title: '删除中...'
				});

				const res = await deleteAddress({
					id: this.addressId
				});

				uni.hideLoading();

				if (res.code === 200) {
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});

					// 返回上一页并刷新地址列表
					setTimeout(() => {
						// 返回并通知上一页刷新
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						if (prevPage && prevPage.$vm) {
							// 确保上一页面有load方法
							prevPage.$vm.load && prevPage.$vm.load();
						}
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '删除失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('删除地址失败', error);
				uni.showToast({
					title: '网络异常，请稍后再试',
					icon: 'none'
				});
			}
		}
	}
}
</script>

<style lang="scss">
.address-form {
	background-color: #fff;
	padding: 0 30rpx;

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

		.form-label {
			width: 180rpx;
			font-size: 30rpx;
			color: #333;

			&.required::before {
				content: '*';
				color: #ff4d4f;
				margin-right: 4rpx;
			}
		}

		.form-input {
			flex: 1;
			height: 100rpx;
			font-size: 30rpx;
		}

		.form-textarea {
			flex: 1;
			width: 100%;
			min-height: 100rpx;
			font-size: 30rpx;
			padding: 20rpx 0;
		}

		.form-value {
			flex: 1;
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx;
			font-size: 30rpx;

			.placeholder {
				color: #999;
			}

			.arrow {
				color: #ccc;
				margin-left: 10rpx;
			}
		}

		&.switch-item {
			justify-content: space-between;
		}

		&.address-item {
			flex-direction: column;
			align-items: flex-start;

			.address-label {
				margin-top: 20rpx;
				margin-bottom: 10rpx;
			}

			.form-textarea {
				width: 100%;
				margin-top: 10rpx;
			}
		}
	}
}

.btn-save {
	position: fixed;
	bottom: 140rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 90%;
	height: 90rpx;
	background-color: #1296db;
	color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	font-weight: bold;
	border-radius: 45rpx;
}

.btn-delete {
	position: fixed;
	bottom: 30rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 90%;
	height: 90rpx;
	background-color: #fff;
	color: #666;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	border-radius: 45rpx;
	border: 1px solid #ddd;
}
</style>
