<template>
  <view class="switch-roles">
    <nav-bar title="添加地址" color="#000"></nav-bar>
    <view class="roles-content">
      <view class="content">
        <!-- 地图选点入口（辅助填充） -->
        <view class="map-selector" @click="openMapSelector">
          <u-icon name="map" size="36rpx" color="#007AFF" marginRight="16rpx"></u-icon>
          <text class="map-text">通过地图选择地址（可选）</text>
        </view>

        <!-- 省/市/区三级联动选择器 -->
        <view class="form-item">
          <view class="item-label">所在省份 <text class="required">*</text></view>
          <picker 
            :range="provinces" 
            :range-key="'name'"
            v-model="provinceIndex" 
            @change="onProvinceChange"
          >
            <view class="picker-view">
              {{ provinceIndex !== null ? provinces[provinceIndex].name : '请选择省份' }}
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <view class="item-label">所在城市 <text class="required">*</text></view>
          <picker 
            :range="cities" 
            :range-key="'name'"
            v-model="cityIndex" 
            @change="onCityChange"
            :disabled="provinceIndex === null"
          >
            <view class="picker-view">
              {{ cityIndex !== null && cities.length > 0 ? cities[cityIndex].name : '请先选择省份' }}
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <view class="item-label">所在区域 <text class="required">*</text></view>
          <picker 
            :range="districts" 
            :range-key="'name'"
            v-model="districtIndex" 
            @change="onDistrictChange"
            :disabled="cityIndex === null || cities.length === 0"
          >
            <view class="picker-view">
              {{ districtIndex !== null && districts.length > 0 ? districts[districtIndex].name : '请先选择城市' }}
            </view>
          </picker>
        </view>
        
        <!-- 详细地址信息 -->
        <view class="form-item">
          <view class="item-label">街道/楼宇 <text class="required">*</text></view>
          <u-input
            placeholder="请输入街道或楼宇名称，例：科技园路1号"
            v-model="address"
            clearable
            class="custom-input"
          >
            <template #prefix>
              <u-icon name="map" size="36rpx" color="#999" marginRight="20rpx"></u-icon>
            </template>
          </u-input>
        </view>
        
        <view class="form-item">
          <view class="item-label">楼层/单元室</view>
          <u-input
            placeholder="例：3层302室（选填）"
            v-model="addressDetail"
            clearable
            class="custom-input"
          >
            <template #prefix>
              <u-icon name="home" size="36rpx" color="#999" marginRight="20rpx"></u-icon>
            </template>
          </u-input>
        </view>
        
        <!-- 地图选点后显示经纬度（可选） -->
        <view class="location-info" v-if="latitude && longitude">
          <text>经纬度：{{ latitude }}, {{ longitude }}</text>
        </view>
      </view>
    </view>
    <view class="submit-btn" @click="confirmAddress">确定</view>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/index.vue";
import addr from "@/utils/addr.json";

export default {
  data() {
    return {
      // 三级联动数据
      provinces: [],       // 所有省份
      cities: [],          // 选中省份对应的城市
      districts: [],       // 选中城市对应的区域
      
      // 选中索引
      provinceIndex: null, // 选中的省份索引
      cityIndex: null,     // 选中的城市索引
      districtIndex: null, // 选中的区域索引
      
      // 地址信息
      address: "",        // 街道/楼宇（必填）
      addressDetail: '',  // 楼层/单元室（选填）
      latitude: '',       // 纬度（地图选点获取）
      longitude: ''       // 经度（地图选点获取）
    };
  },
  components: {
    navBar,
  },
  // created() {
  //   // 初始化省份数据
  //   this.provinces = addr;
  // },
  onLoad(options) {
	 this.provinces = addr;
    // 回显上一页传递的地址信息
    if (options.address) this.address = decodeURIComponent(options.address);
    if (options.addressDetail) this.addressDetail = decodeURIComponent(options.addressDetail);
    if (options.latitude) this.latitude = options.latitude;
    if (options.longitude) this.longitude = options.longitude;
    
    // 如果有省市区信息，进行回显
    if (options.province && options.city && options.district) {
      this.setAddressValue(
        decodeURIComponent(options.province),
        decodeURIComponent(options.city),
        decodeURIComponent(options.district)
      );
    }
	

  },
  methods: {
    // 省份选择改变
    onProvinceChange(e) {
      const index = e.detail.value;
      this.provinceIndex = index;
      
      // 重置城市和区域选择
      this.cityIndex = null;
      this.districtIndex = null;
      
      // 加载对应省份的城市
      this.cities = this.provinces[index].children || [];
      
      // 如果有城市数据，自动加载第一个城市的区域
      if (this.cities.length > 0) {
        this.districts = this.cities[0].children || [];
      } else {
        this.districts = [];
      }
    },
    
    // 城市选择改变
    onCityChange(e) {
      const index = e.detail.value;
      this.cityIndex = index;
      
      // 重置区域选择
      this.districtIndex = null;
      
      // 加载对应城市的区域
      this.districts = this.cities[index].children || [];
    },
    
    // 区域选择改变
    onDistrictChange(e) {
      this.districtIndex = e.detail.value;
    },
    
    // 根据省市区名称设置选择器值（用于回显）
    setAddressValue(provinceName, cityName, districtName) {
      // 查找省份索引
      const provinceIndex = this.provinces.findIndex(item => item.name === provinceName);
      if (provinceIndex !== -1) {
        this.provinceIndex = provinceIndex;
        this.cities = this.provinces[provinceIndex].children || [];
        
        // 查找城市索引
        const cityIndex = this.cities.findIndex(item => item.name === cityName);
        if (cityIndex !== -1) {
          this.cityIndex = cityIndex;
          this.districts = this.cities[cityIndex].children || [];
          
          // 查找区域索引
          const districtIndex = this.districts.findIndex(item => item.name === districtName);
          if (districtIndex !== -1) {
            this.districtIndex = districtIndex;
          }
        }
      }
    },
    
    // 打开地图选择地址
    openMapSelector() {
      uni.chooseLocation({
        success: (res) => {
          this.address = res.name || res.address;
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          
          uni.showToast({
            title: '请确认并补充省/市/区信息',
            icon: 'none',
            duration: 2000
          });
        },
        fail: (err) => {
          console.error('地图选择失败：', err);
          if (err.errMsg.includes('auth')) {
            uni.showToast({ title: '请开启位置权限', icon: 'none' });
          }
        }
      });
    },
    
    // 确认地址并回传
    confirmAddress() {
      // 获取选中的省市区信息
      const province = this.provinceIndex !== null ? this.provinces[this.provinceIndex].name : '';
      const city = this.cityIndex !== null && this.cities.length > 0 ? this.cities[this.cityIndex].name : '';
      const district = this.districtIndex !== null && this.districts.length > 0 ? this.districts[this.districtIndex].name : '';

      // 验证必填项
      if (!province) {
        return uni.showToast({ title: '请选择省份', icon: 'none' });
      }
      if (!city) {
        return uni.showToast({ title: '请选择城市', icon: 'none' });
      }
      if (!district) {
        return uni.showToast({ title: '请选择区域', icon: 'none' });
      }
      if (!this.address.trim()) {
        return uni.showToast({ title: '请输入街道或楼宇名称', icon: 'none' });
      }

      // 合并完整地址信息
      const fullAddress = {
        province,
        city,
        district,
        address: this.address.trim(),
        addressDetail: this.addressDetail.trim(),
        latitude: this.latitude || '',
        longitude: this.longitude || '',
        fullText: `${province}${city}${district}${this.address.trim()}${this.addressDetail.trim() ? ' ' + this.addressDetail.trim() : ''}`
      };

      // 回传上一页
      uni.$emit('addressData', fullAddress);
      uni.navigateBack();
    }
  }
};
</script>

<style lang="scss" scoped>
/* 原有样式保持不变，添加以下选择器样式 */
.picker-view {
  box-sizing: border-box;
  width: 100%;
  border: 2rpx solid #9ea1a8;
  border-radius: 100rpx;
  padding: 8rpx 36rpx;
  height: 96rpx;
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

picker {
  width: 100%;
}

/* 禁用状态样式 */
picker:disabled .picker-view {
  color: #999;
  background-color: #f5f5f5;
}

/* 其他原有样式保持不变 */
.switch-roles {
  background-color: #fff;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  
  .roles-content {
    width: 100%;
    flex: 1;
    overflow-y: auto;
    
    .content {
      padding: 40rpx;
      box-sizing: border-box;
      
      .map-selector {
        display: flex;
        align-items: center;
        padding: 20rpx 24rpx;
        background-color: #f5f7fa;
        border-radius: 16rpx;
        margin-bottom: 30rpx;
        color: #007AFF;
        font-size: 28rpx;
        cursor: pointer;
        transition: background-color 0.2s;
        
        &:active {
          background-color: #e8ebf0;
        }
      }
      
      .location-info {
        margin-top: 10rpx;
        font-size: 24rpx;
        color: #999;
        padding: 10rpx 0;
      }
      
      .required {
        color: #ff4d4f; /* 红色必填标记 */
        font-size: 32rpx;
        margin-left: 4rpx;
      }
    }
  }
  
  .submit-btn {
    margin: 60rpx 20rpx;
    height: 96rpx;
    border-radius: 999px;
    background: linear-gradient(90deg, #0d27f7, #13c1ea);
    color: #fff;
    font-size: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s ease;
    
    &:active {
      transform: scale(0.98);
      opacity: 0.9;
    }
  }
}

.custom-input {
  box-sizing: border-box;
  border: 2rpx solid #9ea1a8;
  border-radius: 100rpx;
  padding: 8rpx 36rpx; 
  height: 96rpx;
}

::v-deep .u-input__prefix {
  margin-right: 24rpx !important;
}

::v-deep .u-input input {
  padding-left: 32rpx;
}

.form-item {
  margin-bottom: 26rpx;
  width: 100%;
}

.item-label {
  color: #121a2c;
  font-size: 32rpx;
  padding: 10rpx 0;
  display: flex;
  align-items: center;
}

::v-deep .u-input input:focus {
  border-color: #007AFF !important;
  outline: none;
}

::v-deep .u-input {
  text-align: left !important;
}
</style>