<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
		</view>

		<!-- 地址表单 -->
		<view class="form-container">
			<!-- 收件人信息 -->
			<view class="form-section">
				<view class="section-title">收件人信息</view>
				<view class="form-item">
					<text class="form-label">收件人姓名</text>
					<input class="form-input" 
						   type="text" 
						   v-model="formData.consignee_name" 
						   placeholder="请输入收件人姓名"
						   maxlength="20">
				</view>
				<view class="form-item">
					<text class="form-label">手机号码</text>
					<input class="form-input" 
						   type="number" 
						   v-model="formData.consignee_phone" 
						   placeholder="请输入手机号码"
						   maxlength="11">
				</view>
			</view>

			<!-- 收货地址 -->
			<view class="form-section">
				<view class="section-title">收货地址</view>
				<view class="form-item">
					<text class="form-label">所在地区</text>
					<view class="region-container">
						<Region 
							:width="420" 
							:height="92" 
							:showAllDistrict="false"
							:isRevise="hasSelectedRegion"
							:previnceId="provinceId"
							:cityId="cityId"
							:countyId="countyId"
							@region="onRegionChange"
						/>
					</view>
				</view>
				<view class="form-item">
					<text class="form-label">详细地址</text>
					<textarea class="form-textarea" 
							  v-model="formData.detail_address" 
							  placeholder="请输入详细地址，如道路、门牌号、小区、楼栋号等"
							  maxlength="200"
							  auto-height>
					</textarea>
				</view>
				<view class="form-item">
					<text class="form-label">邮政编码</text>
					<input class="form-input" 
						   type="text" 
						   v-model="formData.postal_code" 
						   placeholder="请输入邮政编码（可选）"
						   maxlength="6">
				</view>
			</view>

			<!-- 默认地址设置 -->
			<view class="form-section">
				<view class="form-item no-border">
					<text class="form-label">设为默认地址</text>
					<switch :checked="formData.is_default === 1" @change="onDefaultChange"></switch>
				</view>
			</view>
		</view>

		<!-- 保存按钮 -->
		<view class="save-section">
			<button class="save-btn" @tap="saveAddress" :disabled="saving">
				<text v-if="saving">保存中...</text>
				<text v-else>{{ isEdit ? '保存修改' : '保存地址' }}</text>
			</button>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request.js'
	import Region from '@/components/k-region.vue'
	export default {
		components:{
		            Region
		        },
		data() {
			return {
				isEdit: false,
				addressId: null,
				formData: {
					consignee_name: '',
					consignee_phone: '',
					province: '',
					city: '',
					district: '',
					detail_address: '',
					postal_code: '',
					is_default: 0
				},
				saving: false,
				// k-region组件需要的数据
				provinceId: 11,      // 默认北京
				cityId: 1101,        // 默认北京市
				countyId: 110101     // 默认东城区
			}
		},
		computed: {
			regionText() {
				if (this.formData.province && this.formData.city && this.formData.district) {
					return `${this.formData.province} ${this.formData.city} ${this.formData.district}`
				}
				return ''
			},
			hasSelectedRegion() {
				return !!(this.formData.province && this.formData.city && this.formData.district)
			}
		},
		onLoad(options) {
			// 检查登录状态
			const token = uni.getStorageSync('token')
			if (!token) {
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return
			}

			// 判断是编辑还是新增
			if (options.id) {
				this.isEdit = true
				this.addressId = options.id
				this.loadAddressDetail()
			}
		},
		methods: {
			// 加载地址详情
			async loadAddressDetail() {
				try {
					const res = await request.get(`/back/user/addresses/${this.addressId}`)
					if (res.success) {
						this.formData = res.data
						// 转换地区名称为代码（这里需要添加映射逻辑，暂时使用默认值）
						this.updateRegionCodes()
					}
				} catch (error) {
					console.error('加载地址详情失败：', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
			},

			// 更新地区代码（根据地区名称）
			updateRegionCodes() {
				// 这里可以添加地区名称到代码的映射逻辑
				// 暂时使用默认值，实际应用中需要完整的地区代码映射表
				if (this.formData.province && this.formData.city && this.formData.district) {
					// 如果有具体的映射需求，可以在这里添加
					// 例如：this.provinceId = getProvinceCodeByName(this.formData.province)
				}
			},

			// k-region组件回调
			onRegionChange(regionArray) {
				console.log('选择的地区:', regionArray)
				this.formData.province = regionArray[0] || ''
				this.formData.city = regionArray[1] || ''
				this.formData.district = regionArray[2] || ''
			},

			// 默认地址开关变化
			onDefaultChange(e) {
				this.formData.is_default = e.detail.value ? 1 : 0
			},

			// 表单验证
			validateForm() {
				if (!this.formData.consignee_name.trim()) {
					uni.showToast({
						title: '请输入收件人姓名',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.consignee_phone.trim()) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					})
					return false
				}
				
				const phoneReg = /^1[3-9]\d{9}$/
				if (!phoneReg.test(this.formData.consignee_phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.province || !this.formData.city || !this.formData.district) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.detail_address.trim()) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					})
					return false
				}
				
				return true
			},

			// 保存地址
			async saveAddress() {
				if (!this.validateForm()) {
					return
				}

				this.saving = true
				try {
					let res
					if (this.isEdit) {
						res = await request.put(`/back/user/addresses/${this.addressId}`, this.formData)
					} else {
						res = await request.post('/back/user/addresses', this.formData)
					}

					if (res.success) {
						uni.showToast({
							title: this.isEdit ? '修改成功' : '添加成功',
							icon: 'success'
						})
						
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						throw new Error(res.message || '保存失败')
					}
				} catch (error) {
					console.error('保存地址失败：', error)
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				} finally {
					this.saving = false
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.page-header {
		background: white;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #eee;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.form-container {
		padding: 20rpx;
	}

	.form-section {
		background: white;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
	}

	.section-title {
		padding: 30rpx;
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.form-item.no-border {
		border-bottom: none;
	}

	.form-label {
		width: 200rpx;
		font-size: 28rpx;
		color: #333;
		flex-shrink: 0;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		margin-left: 20rpx;
	}

	.form-textarea {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		margin-left: 20rpx;
		min-height: 100rpx;
	}

	.region-picker {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-left: 20rpx;
		padding: 20rpx 0;
	}

	.region-container {
		flex: 1;
		margin-left: 20rpx;
	}

	.region-text {
		font-size: 28rpx;
		color: #333;
	}

	.region-placeholder {
		font-size: 28rpx;
		color: #999;
	}

	.save-section {
		padding: 40rpx 20rpx;
	}

	.save-btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
		border: none;
		border-radius: 45rpx;
		color: white;
		font-size: 32rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.save-btn:disabled {
		background: #ccc;
	}

	
	
</style>