<template>
	<view class="address-edit-container">
		<view class="form-container">
			<view class="form-item">
				<text class="label">收货人</text>
				<input class="input" v-model="formData.name" placeholder="请输入收货人姓名" maxlength="30"
					@input="limitNameInput" placeholder-style="color: #BFBFBF;" />
				<view class="wechat-import" @tap="importFromWechat">
					<image class="wechat-icon" :src="$baseUrl + 'homepage/Q3Res/wechatIcon.png'" mode="aspectFit">
					</image>
				</view>
			</view>

			<view class="form-item">
				<text class="label">手机号码</text>
				<input class="input" :class="{ 'error': phoneError }" v-model="formData.phone" placeholder="请输入手机号码"
					type="number" maxlength="11" @input="validatePhone" placeholder-style="color: #BFBFBF;" />
				<text v-if="phoneError" class="error-text">请输入正确的手机号码</text>
			</view>

			<view class="form-item">
				<text class="label">所在地区</text>
				<view class="region-select" @tap="showRegionPicker">
					<text class="region-text" :class="{ 'placeholder-color': !formData.region }">{{ formData.region ||
						'请选择省/市/区' }}</text>
					<image class="arrow" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFit" />
				</view>
			</view>

			<view class="form-item">
				<text class="label">详细地址</text>
				<input class="textarea" v-model="formData.detailAddress" placeholder="请填写详细地址" maxlength="100"
					@input="limitDetailAddress" placeholder-style="color: #BFBFBF;" />
				<text class="char-count">{{ formData.detailAddress.length }}/100</text>
			</view>

			<view class="form-item">
				<text class="label">门牌号</text>
				<input class="input" v-model="formData.houseNumber" placeholder="街道、门牌号等" maxlength="50"
					@input="limitHouseNumber" placeholder-style="color: #BFBFBF;" />
				<text class="char-count">{{ formData.houseNumber.length }}/50</text>
			</view>

			<view class="default-switch">
				<text class="switch-text">设为默认地址</text>
				<view class="switch" @tap="toggleDefault" :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>

				<!-- 面包屑导航 -->
				<view class="breadcrumb-container">
					<view class="breadcrumb-item" :class="{ 'active': currentLevel === 0 }" @tap="switchToLevel(0)">
						{{ selectedProvince ? selectedProvince.name : '请选择' }}
					</view>
					<view v-if="showCityLevel" class="breadcrumb-item" :class="{ 'active': currentLevel === 1 }"
						@tap="switchToLevel(1)">
						{{ selectedCity ? selectedCity.name : '请选择' }}
					</view>
					<view v-if="showDistrictLevel" class="breadcrumb-item" :class="{ 'active': currentLevel === 2 }"
						@tap="switchToLevel(2)">
						{{ selectedDistrict ? selectedDistrict.name : '请选择' }}
					</view>
					<view v-if="showStreetLevel" class="breadcrumb-item" :class="{ 'active': currentLevel === 3 }"
						@tap="switchToLevel(3)">
						{{ selectedStreet ? selectedStreet.name : '请选择' }}
					</view>
				</view>

				<view v-if="isLoadingRegions" class="loading-container">
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else class="picker-list">
					<view v-for="(item, index) in currentLevelData" :key="index" class="picker-item"
						:class="{ 'selected': isItemSelected(item, index) }" @tap="selectItem(item, index)">
						<text class="item-text">{{ item.name }}</text>
						<text v-if="isItemSelected(item, index)" class="check-icon">✓</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

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

export default {
	data() {
		return {
			isEditMode: false,
			addressId: '',
			isLoading: false,
			isSubmitting: false, // 用于防连点
			phoneError: false,
			formData: {
				name: '',
				phone: '',
				region: '',
				province: '',
				city: '',
				district: '',
				detailAddress: '',
				houseNumber: '',
				isDefault: false,
				email: '',
				postalCode: ''
			},
			showPicker: false,
			pickerValue: [0, 0, 0, 0],
			provinces: [],
			cities: [],
			districts: [],
			streets: [],
			selectedProvince: null,
			selectedCity: null,
			selectedDistrict: null,
			selectedStreet: null,
			isLoadingRegions: false,
			currentLevel: 0, // 当前选择的级别 0:省份 1:城市 2:区县 3:街道
			currentLevelData: [] // 当前级别显示的数据
		}
	},
	computed: {
		canSave() {
			// 除默认按钮外，所有必填项都必须填写且格式正确
			return this.formData.name.trim() &&
				this.formData.phone.trim() &&
				!this.phoneError &&
				this.formData.region &&
				this.formData.detailAddress.trim();
		},

		// 控制各级别面包屑的显示
		showCityLevel() {
			return this.selectedProvince && this.cities.length > 0;
		},

		showDistrictLevel() {
			return this.selectedCity && this.districts.length > 0;
		},

		showStreetLevel() {
			return this.selectedDistrict && this.streets.length > 0;
		}
	},
	onLoad(options) {
		// 判断是否为编辑模式
		this.isEditMode = !!options.id;
		this.addressId = options.id || '';
		// 检查是否从结算页面跳转过来
		this.fromSettlement = options.from === 'settlement';
		console.log('是否从结算页面跳转过来:', this.fromSettlement);

		// 如果是编辑模式，加载地址详情
		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();
		},

		// 显示地区选择器
		async showRegionPicker() {
			this.showPicker = true;
			this.currentLevel = 0;
			// 如果省份列表为空，先加载省份数据
			if (this.provinces.length === 0) {
				await this.loadProvinces();
			}
			this.updateCurrentLevelData();
		},

		// 更新当前级别数据
		updateCurrentLevelData() {
			switch (this.currentLevel) {
				case 0:
					this.currentLevelData = this.provinces;
					break;
				case 1:
					this.currentLevelData = this.cities;
					break;
				case 2:
					this.currentLevelData = this.districts;
					break;
				case 3:
					this.currentLevelData = this.streets;
					break;
				default:
					this.currentLevelData = [];
			}
		},

		// 切换到指定级别
		switchToLevel(level) {
			// 检查级别是否有效
			if (level === 0) {
				// 省份级别总是有效的
				this.currentLevel = level;
			} else if (level === 1 && this.showCityLevel) {
				// 城市级别只有在有城市数据时才有效
				this.currentLevel = level;
			} else if (level === 2 && this.showDistrictLevel) {
				// 区县级别只有在有区县数据时才有效
				this.currentLevel = level;
			} else if (level === 3 && this.showStreetLevel) {
				// 街道级别只有在有街道数据时才有效
				this.currentLevel = level;
			} else {
				console.log('无效的级别切换:', level);
				return;
			}

			this.updateCurrentLevelData();
		},

		// 选择项目
		async selectItem(item, index) {
			console.log('选择项目:', item, '级别:', this.currentLevel);

			// 检查item和item.code是否存在
			if (!item || !item.code) {
				console.error('选择项目数据无效:', item);
				uni.showToast({
					title: '选择失败，请重试',
					icon: 'none'
				});
				return;
			}

			switch (this.currentLevel) {
				case 0: // 选择省份
					this.selectedProvince = item;
					this.selectedCity = null;
					this.selectedDistrict = null;
					this.selectedStreet = null;
					console.log('准备加载城市，省份ID:', item.code);
					await this.loadCities(item.code);

					// 如果城市数据为空，直接确认选择
					if (this.cities.length === 0) {
						console.log('城市数据为空，直接确认省份选择');
						this.confirmRegion();
						return;
					}
					this.currentLevel = 1;
					break;

				case 1: // 选择城市
					this.selectedCity = item;
					this.selectedDistrict = null;
					this.selectedStreet = null;
					console.log('准备加载区县，城市ID:', item.code);
					await this.loadDistricts(item.code);

					// 如果区县数据为空，直接确认选择
					if (this.districts.length === 0) {
						console.log('区县数据为空，直接确认城市选择');
						this.confirmRegion();
						return;
					}
					this.currentLevel = 2;
					break;

				case 2: // 选择区县
					this.selectedDistrict = item;
					this.selectedStreet = null;
					console.log('准备加载街道，区县ID:', item.code);
					await this.loadStreets(item.code);

					// 如果街道数据为空，直接确认选择
					if (this.streets.length === 0) {
						console.log('街道数据为空，直接确认区县选择');
						this.confirmRegion();
						return;
					}
					this.currentLevel = 3;
					break;

				case 3: // 选择街道
					this.selectedStreet = item;
					// 街道是最后一级，直接确认选择
					this.confirmRegion();
					return;
			}

			this.updateCurrentLevelData();
		},

		// 判断项目是否被选中
		isItemSelected(item, index) {
			switch (this.currentLevel) {
				case 0:
					return this.selectedProvince && this.selectedProvince.code === item.code;
				case 1:
					return this.selectedCity && this.selectedCity.code === item.code;
				case 2:
					return this.selectedDistrict && this.selectedDistrict.code === item.code;
				case 3:
					return this.selectedStreet && this.selectedStreet.code === item.code;
				default:
					return false;
			}
		},

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

		// 选择器值变化
		async onPickerChange(e) {
			const [provinceIndex, cityIndex, districtIndex, streetIndex] = e.detail.value;
			const oldPickerValue = [...this.pickerValue];

			console.log('选择器变化:', {
				old: oldPickerValue,
				new: e.detail.value,
				provinceIndex,
				cityIndex,
				districtIndex,
				streetIndex
			});

			// 省份变化
			if (provinceIndex !== oldPickerValue[0] && this.provinces.length > 0) {
				console.log('省份变化:', this.provinces[provinceIndex]);
				this.selectedProvince = this.provinces[provinceIndex];
				this.selectedCity = null;
				this.selectedDistrict = null;
				this.selectedStreet = null;
				this.cities = [];
				this.districts = [];
				this.streets = [];

				// 更新picker值并加载城市，使用code而不是id
				this.pickerValue = [provinceIndex, 0, 0, 0];
				await this.loadCities(this.selectedProvince.code);
			}

			// 城市变化
			if (cityIndex !== oldPickerValue[1] && this.cities.length > 0) {
				console.log('城市变化:', this.cities[cityIndex]);
				this.selectedCity = this.cities[cityIndex];
				this.selectedDistrict = null;
				this.selectedStreet = null;
				this.districts = [];
				this.streets = [];

				// 更新picker值并加载区县，使用code而不是id
				this.pickerValue = [provinceIndex, cityIndex, 0, 0];
				await this.loadDistricts(this.selectedCity.code);
			}

			// 区县变化
			if (districtIndex !== oldPickerValue[2] && this.districts.length > 0) {
				console.log('区县变化:', this.districts[districtIndex]);
				this.selectedDistrict = this.districts[districtIndex];
				this.selectedStreet = null;
				this.streets = [];

				// 更新picker值并加载街道，使用code而不是id
				this.pickerValue = [provinceIndex, cityIndex, districtIndex, 0];
				await this.loadStreets(this.selectedDistrict.code);
			}

			// 街道变化
			if (streetIndex !== oldPickerValue[3] && this.streets.length > 0) {
				console.log('街道变化:', this.streets[streetIndex]);
				this.selectedStreet = this.streets[streetIndex];
			}
		},

		// 确认地区选择
		confirmRegion() {
			// 至少需要选择省份
			if (!this.selectedProvince) {
				uni.showToast({
					title: '请选择省份',
					icon: 'none'
				});
				return;
			}

			// 构建地区字符串
			let regionParts = [this.selectedProvince.name];

			// 如果选择了城市，添加到地区字符串
			if (this.selectedCity) {
				regionParts.push(this.selectedCity.name);
			}

			// 如果选择了区县，添加到地区字符串
			if (this.selectedDistrict) {
				regionParts.push(this.selectedDistrict.name);
			}

			// 如果选择了街道，添加到地区字符串
			if (this.selectedStreet) {
				regionParts.push(this.selectedStreet.name);
			}

			// 设置表单数据
			this.formData.province = this.selectedProvince.name;
			this.formData.city = this.selectedCity ? this.selectedCity.name : '';
			this.formData.district = this.selectedDistrict ? this.selectedDistrict.name : '';
			this.formData.region = regionParts.join('/');

			console.log('确认地区选择:', this.formData.region);
			this.showPicker = false;
		},

		// 加载省份数据
		async loadProvinces() {
			this.isLoadingRegions = true;
			try {
				console.log('开始加载省份数据');
				const response = await getRegionList({ id: 0 });
				console.log('省份数据API响应:', response);

				if (response.ok && response.data && response.data.length > 0) {
					this.provinces = response.data;
					this.cities = []; // 清空城市数据
					this.districts = []; // 清空区县数据
					this.streets = []; // 清空街道数据
					console.log('省份数据加载成功:', this.provinces);
					console.log('第一个省份数据结构:', this.provinces[0]);

					// 更新当前级别数据
					this.updateCurrentLevelData();
				} else {
					this.provinces = [];
					console.log('省份数据为空或加载失败');
				}
			} catch (error) {
				console.error('加载省份数据失败:', error);
				this.provinces = [];
			} finally {
				this.isLoadingRegions = false;
			}
		},

		// 加载城市数据
		async loadCities(provinceId) {
			this.isLoadingRegions = true;
			try {
				console.log('开始加载城市数据，省份ID:', provinceId);
				console.log('省份ID类型:', typeof provinceId);

				// 检查provinceId是否有效
				if (!provinceId && provinceId !== 0) {
					console.error('省份ID无效:', provinceId);
					uni.showToast({
						title: '省份ID无效',
						icon: 'none'
					});
					return;
				}

				const response = await getRegionList({ id: provinceId });
				console.log('城市数据API响应:', response);

				if (response.ok && response.data && response.data.length > 0) {
					this.cities = response.data;
					this.districts = []; // 清空区县数据
					this.streets = []; // 清空街道数据
					console.log('城市数据加载成功:', this.cities);
					console.log('第一个城市数据结构:', this.cities[0]);

					// 更新当前级别数据
					this.updateCurrentLevelData();
				} else {
					this.cities = [];
					console.log('城市数据为空或加载失败');
				}
			} catch (error) {
				console.error('加载城市数据失败:', error);
				this.cities = [];
			} finally {
				this.isLoadingRegions = false;
			}
		},

		// 加载区县数据
		async loadDistricts(cityId) {
			this.isLoadingRegions = true;
			try {
				console.log('开始加载区县数据，城市ID:', cityId);
				const response = await getRegionList({ id: cityId });
				console.log('区县数据API响应:', response);

				if (response.ok && response.data && response.data.length > 0) {
					this.districts = response.data;
					this.streets = []; // 清空街道数据
					console.log('区县数据加载成功:', this.districts);

					// 更新当前级别数据
					this.updateCurrentLevelData();
				} else {
					this.districts = [];
					console.log('区县数据为空或加载失败');
				}
			} catch (error) {
				console.error('加载区县数据失败:', error);
				this.districts = [];
			} finally {
				this.isLoadingRegions = false;
			}
		},

		// 加载街道数据
		async loadStreets(districtId) {
			this.isLoadingRegions = true;
			try {
				console.log('开始加载街道数据，区县ID:', districtId);
				const response = await getRegionList({ id: districtId });
				console.log('街道数据API响应:', response);

				if (response.ok && response.data && response.data.length > 0) {
					this.streets = response.data;
					console.log('街道数据加载成功:', this.streets);

					// 更新当前级别数据
					this.updateCurrentLevelData();
				} else {
					this.streets = [];
					console.log('街道数据为空或加载失败');
				}
			} catch (error) {
				console.error('加载街道数据失败:', error);
				this.streets = [];
			} finally {
				this.isLoadingRegions = false;
			}
		},

		// 手机号码实时验证
		validatePhone() {
			const phone = this.formData.phone;
			if (phone.length === 0) {
				this.phoneError = false;
				return;
			}

			// 手机号码格式验证：1开头，第二位3-9，总共11位数字
			const phoneRegex = /^1[3-9]\d{9}$/;
			this.phoneError = !phoneRegex.test(phone);
		},

		// 限制详细地址字符数
		limitDetailAddress(e) {
			const value = e.detail.value;
			if (value.length > 100) {
				this.formData.detailAddress = value.substring(0, 100);
				uni.showToast({
					title: '详细地址最多100个字符',
					icon: 'none'
				});
			}
		},

		// 限制门牌号字符数
		limitHouseNumber(e) {
			const value = e.detail.value;
			if (value.length > 50) {
				this.formData.houseNumber = value.substring(0, 50);
				uni.showToast({
					title: '门牌号最多50个字符',
					icon: 'none'
				});
			}
		},

		// 限制收货人字符数（最多30个字符，超过不可输入）
		limitNameInput(e) {
			const value = e.detail.value;
			if (value.length > 30) {
				// 超过30个字符时，截取前30个字符
				this.formData.name = value.substring(0, 30);
				uni.showToast({
					title: '收货人最多30个字符',
					icon: 'none'
				});
			}
		},

		// 切换默认地址
		toggleDefault() {
			// 如果当前要设为默认，需要先取消其他默认地址
			if (!this.formData.isDefault) {
				this.setAsDefault();
			} else {
				// 取消默认
				this.formData.isDefault = false;
			}
		},

		// 设置为默认地址
		async setAsDefault() {
			// 防连点检查

			try {
				// 先获取当前地址列表，检查是否已有默认地址
				const response = await getAddressList();
				if (response.ok && response.data) {
					// 查找当前默认地址
					const currentDefault = response.data.find(addr => addr.current);

					if (currentDefault && currentDefault.id !== this.addressId) {
						// 如果存在其他默认地址且不是当前编辑的地址，先取消其默认状态
						await setDefaultAddress({ id: currentDefault.id });
					}
				}

				// 设置当前地址为默认
				this.formData.isDefault = true;

				uni.showToast({
					title: '已设为默认地址',
					icon: 'none'
				});
			} catch (error) {
				console.error('设置默认地址失败:', error);
				uni.showToast({
					title: '设置失败，请重试',
					icon: 'none'
				});
			} finally {

			}
		},

		// 表单验证
		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 (this.phoneError) {
				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.isSubmitting) return;
			this.isSubmitting = true
			console.warn("保存")
			if (!this.validateForm()) {
				this.isSubmitting = false
				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 {
				// 如果要设为默认地址，先处理其他默认地址
				if (addressInfo.isDefault) {
					await this.handleDefaultAddress();
				}

				// 构建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) {
				// 创建要返回的地址数据对象
				const addressData = {
					id: response.data?.id || '',
					name: addressInfo.name,
					mobile: addressInfo.phone,
					province: addressInfo.province,
					city: addressInfo.city,
					area: addressInfo.district,
					detail: addressInfo.detailAddress,
					current: addressInfo.isDefault || false
				};
				
				// 如果是从结算页面过来的，存储地址信息
				if (this.fromSettlement) {
					uni.setStorageSync('selectedAddressForSettlement', addressData);
					console.log('存储新增的地址信息:', addressData);
				}
				
				uni.showToast({
					title: '添加成功',
					icon: 'none',
					success: () => {
						setTimeout(() => {
							this.isSubmitting = false;
							uni.navigateBack();
						}, 1500);
					}
				});
			} else {
					uni.showToast({
						title: response.message || '保存失败',
						icon: 'none'
					});
					this.isSubmitting = false;
				}
			} catch (error) {
				console.error('保存地址失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
				this.isSubmitting = false;
			} finally {
				this.isLoading = false;

			}
		},

		// 更新地址（编辑）
		async updateAddress(addressInfo) {
			// 防连点检查

			this.isLoading = true;
			try {
				// 如果要设为默认地址，先处理其他默认地址
				if (addressInfo.isDefault) {
					await this.handleDefaultAddress();
				}

				// 构建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) {
				// 创建要返回的地址数据对象
				const addressData = {
					id: this.addressId,
					name: addressInfo.name,
					mobile: addressInfo.phone,
					province: addressInfo.province,
					city: addressInfo.city,
					area: addressInfo.district,
					detail: addressInfo.detailAddress,
					current: addressInfo.isDefault || false
				};
				
				// 如果是从结算页面过来的，存储地址信息
				if (this.fromSettlement) {
					uni.setStorageSync('selectedAddressForSettlement', addressData);
					console.log('存储更新的地址信息:', addressData);
				}
				
				uni.showToast({
					title: '更新成功',
					icon: 'none',
					success: () => {
						setTimeout(() => {
							this.isSubmitting = false;
							uni.navigateBack();
						}, 1500);
					}
				});
			} else {
					uni.showToast({
						title: response.message || '更新失败',
						icon: 'none'
					});
					this.isSubmitting = false;
				}
			} catch (error) {
				console.error('更新地址失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
				this.isSubmitting = false;
			} finally {
				this.isLoading = false;
			}
		},

		// 处理默认地址的唯一性
		async handleDefaultAddress() {
			try {
				const response = await getAddressList();
				if (response.ok && response.data) {
					// 查找当前默认地址
					const currentDefault = response.data.find(addr => addr.current);

					if (currentDefault && currentDefault.id !== this.addressId) {
						// 如果存在其他默认地址且不是当前编辑的地址，先取消其默认状态
						await setDefaultAddress({ id: currentDefault.id });
					}
				}
			} catch (error) {
				console.error('处理默认地址失败:', error);
			}
		},



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

		// 微信导入功能
		importFromWechat() {
			// 防连点检查
			if (this.isSubmitting) return;
			this.isSubmitting = true;
			wx.chooseAddress({
				success: (res) => {
					console.log('微信地址导入成功:', res);

					// 填充表单数据
					this.formData.name = res.userName || '';
					this.formData.phone = res.telNumber || '';
					this.formData.postalCode = res.postalCode || '';
					this.formData.province = res.provinceName || '';
					this.formData.city = res.cityName || '';
					this.formData.district = res.countyName || '';
					this.formData.detailAddress = res.detailInfo || '';

					// 构建地区字符串
					this.formData.region = this.buildRegionString({
						province: res.provinceName,
						city: res.cityName,
						area: res.countyName
					});

					// 导入后验证手机号格式
					this.validatePhone();

					uni.showToast({
						title: '地址导入成功',
						icon: 'none'
					});
				},
				fail: (err) => {
					console.error('微信地址导入失败:', err);

					// 根据错误类型给出不同提示
					if (err.errMsg && err.errMsg.includes('requiredPrivateInfos')) {
						uni.showModal({
							title: '权限提示',
							content: '请在微信开发者工具中重新编译项目，或联系开发者检查权限配置',
							showCancel: false,
							confirmText: '我知道了'
						});
					}
				},
				complete: () => {
					// 无论成功失败，都重置防连点状态
					this.isSubmitting = false;
				}
			});
		}
	}
}
</script>

<style scoped>
.address-edit-container {
	background: var(--B10, #FAFAFA);
	top: 0;
	height: 100vh;
}


.form-container {
	background: var(--B10, #FAFAFA);
	overflow: hidden;
}

.input.error {
	color: #ff4444;
	border-color: #ff4444;
}

.error-text {
	font-size: 24rpx;
	color: #ff4444;
	margin-left: 20rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999999;
	margin-left: 20rpx;
	margin-right: 40rpx;
}

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

.label {
	font-size: 26rpx;
	color: #000;
	width: 120rpx;
	flex-shrink: 0;
	margin-left: 54rpx;
	margin-right: 80rpx;
	font-weight: 400;
}

.input {
	flex: 1;
	font-size: 24rpx;
	color: #000;
	padding: 0;
	border: none;
	outline: none;
}

/* 占位符样式已通过placeholder-style属性设置 */


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

.wechat-icon {
	width: 194rpx;
	height: 38rpx;
	margin-right: 5rpx;
}



.textarea {
	flex: 1;
	font-size: 24rpx;
	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: 24rpx;
	color: #000;
}

.region-text.placeholder-color {
	color: #BFBFBF;
}

.arrow {
	width: 14rpx;
	height: 23rpx;
	margin-right: 40rpx;
}

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

.switch-text {
	font-size: 26rpx;
	color: #000;
	margin-left: 54rpx;
}

.switch {
	width: 80rpx;
	height: 48rpx;
	background-color: #E5E5E5;
	border-radius: 48rpx;
	position: relative;
	margin-right: 40rpx;
	transition: background-color 0.3s ease;
}

.switch.active {
	background-color: #D3A458;
}

.switch-dot {
	width: 42rpx;
	height: 42rpx;
	background-color: #ffffff;
	border-radius: 50%;
	position: absolute;
	top: 3rpx;
	left: 3rpx;
	transition: transform 0.3s ease;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.switch-dot.active {
	transform: translateX(32rpx);
}

.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: center;
	align-items: flex-end;
}

.picker-container {
	background-color: #ffffff;
	width: 100%;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	height: 80vh;
	display: flex;
	flex-direction: column;
	animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}

	to {
		transform: translateY(0);
	}
}

.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: #D3A458;
}

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

/* 面包屑导航样式 */
.breadcrumb-container {
	display: flex;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	gap: 20rpx;
}

.breadcrumb-item {
	font-size: 28rpx;
	color: #666666;
	padding: 10rpx 0;
	position: relative;
	cursor: pointer;
}

.breadcrumb-item.active {
	color: #D3A458;
	font-weight: 500;
}

.breadcrumb-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 2rpx;
	background-color: #D3A458;
}

/* 选择列表样式 */
.picker-list {
	flex: 1;
	overflow-y: auto;
}

.picker-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	cursor: pointer;
}

.picker-item:last-child {
	border-bottom: none;
}

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

.picker-item.selected .item-text {
	color: #D3A458;
	font-weight: 500;
}

.check-icon {
	font-size: 32rpx;
	color: #D3A458;
	font-weight: bold;
}

.loading-container {
	height: 400rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.loading-text {
	font-size: 28rpx;
	color: #999999;
}
</style>