<template>
  <view class="address-picker">
    <view 
      class="picker-trigger" 
      @click="showPicker = true"
      :class="{ 'placeholder': !selectedText }"
    >
      <text>{{ selectedText || placeholder }}</text>
      <view class="arrow-icon">▼</view>
    </view>

    <view v-if="showPicker" class="picker-mask" @click="showPicker = false"></view>
    <view v-if="showPicker" class="picker-popup">
      <view class="picker-header">
        <view class="header-cancel" @click="showPicker = false">取消</view>
        <view class="header-title">选择地址</view>
        <view class="header-confirm" @click="handleConfirm">确定</view>
      </view>

      <view class="picker-content">
        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="handlePickerChange"
          :indicator-style="indicatorStyle"
		  :style="{ height: pickerHeight }"
        >
          <picker-view-column>
            <view 
              class="picker-item" 
              v-for="(province, index) in filteredProvinces" 
              :key="index"
            >
              {{ province.name }}
            </view>
          </picker-view-column>

          <picker-view-column v-if="level >= 2">
            <view 
              class="picker-item" 
              v-for="(city, index) in filteredCities" 
              :key="index"
            >
              {{ city.name }}
            </view>
          </picker-view-column>

          <picker-view-column v-if="level >= 3">
            <view 
              class="picker-item" 
              v-for="(area, index) in filteredAreas" 
              :key="index"
            >
              {{ area.name }}
            </view>
          </picker-view-column>
		  
		  <picker-view-column v-if="level >= 4">
		    <view 
		      class="picker-item" 
		      v-for="(street, index) in filteredStreets" 
		      :key="index"
		    >
		      {{ street.name }}
		    </view>
		  </picker-view-column>
        </picker-view>
      </view>
    </view>
  </view>
</template>

<script>
// 可替换为自己的地址数据
import addressData from './level4_address.js'

export default {
  name: "AddressPicker",
  props: {
    // 选择层级：1-省，2-省市，3-省市区，4-省市区街道
    level: {
      type: Number,
      default: 4,
      validator: (val) => val >= 1 && val <= 4,
    },
    // 默认选中值（格式：[{code, name}, {code, name}, {code, name}]，长度与level一致）
    defaultValue: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: "请选择地址"
    },
    // 选择器高度
    pickerHeight: {
      type: String,
      default: "400rpx"
    }
  },
  data() {
    return {
      showPicker: false, // 是否显示选择器
      addressData: addressData, // 完整地址数据
      pickerValue: [0, 0, 0, 0], // picker-view的选中索引
      selectedAddress: [], // 已选中的地址
    };
  },
  computed: {
    // 过滤出的省列表
    filteredProvinces() {
      return this.addressData || [];
    },

    // 根据选中的省过滤市列表
    filteredCities() {
      const province = this.filteredProvinces[this.pickerValue[0]];
	  return province?.children || [];
    },

    // 根据选中的市过滤区列表
    filteredAreas() {
      const city = this.filteredCities[this.pickerValue[1]];
	  return city?.children || [];
    },
	
	//根据选中的区过滤街道列表
	filteredStreets() {
	  const area = this.filteredAreas[this.pickerValue[2]];
	  return area?.children || [];
	},

    // 显示的选中文本
    selectedText() {
      if (!this.selectedAddress.length) return '';
      return this.selectedAddress.map(item => item.name).join('/');
    },

    // 指示器样式
    indicatorStyle() {
      return `height: 80rpx;`;
    }
  },
  watch: {
    // 监听默认值变化，初始化选择器
    defaultValue: {
      immediate: true,
      handler(val) {
        if (val && val.length) {
          this.initDefaultValue(val);
        }
      }
    },

    // 监听选择层级变化，重置选择器
    level() {
      this.resetPicker();
    }
  },
  methods: {
    // 初始化默认值
    initDefaultValue(defaultVal) {
		if (!Array.isArray(defaultVal) || defaultVal.length === 0) return;      
        // 省
        const pIndex = this.filteredProvinces.findIndex(p => p.code === defaultVal[0]?.code);
        if (pIndex === -1) return;
        this.pickerValue[0] = pIndex;
      
        if (this.level >= 2 && defaultVal[1]) {
          const cIndex = this.filteredCities.findIndex(c => c.code === defaultVal[1].code);
          this.pickerValue[1] = cIndex > -1 ? cIndex : 0;
        }
      
        if (this.level >= 3 && defaultVal[2]) {
          const aIndex = this.filteredAreas.findIndex(a => a.code === defaultVal[2].code);
          this.pickerValue[2] = aIndex > -1 ? aIndex : 0;
        }
      
        if (this.level >= 4 && defaultVal[3]) {
          const sIndex = this.filteredStreets.findIndex(s => s.code === defaultVal[3].code);
          this.pickerValue[3] = sIndex > -1 ? sIndex : 0;
        }
      
        this.updateSelectedAddress();
    },

    // 重置选择器
    resetPicker() {
      this.pickerValue = [0, 0, 0, 0];
      this.updateSelectedAddress();
    },

    // 选择器值变化时触发
    handlePickerChange(e) {
      this.pickerValue = e.detail.value;
      this.updateSelectedAddress();
    },

    // 更新选中的地址
    updateSelectedAddress() {
		const result = [];
        const provinces = this.filteredProvinces;
        const cities = this.filteredCities;
        const areas = this.filteredAreas;
        const streets = this.filteredStreets;
      
        if (provinces[this.pickerValue[0]]) {
          result.push({
            code: provinces[this.pickerValue[0]].code,
            name: provinces[this.pickerValue[0]].name
          });
        }
      
        if (this.level >= 2 && cities[this.pickerValue[1]]) {
          result.push({
            code: cities[this.pickerValue[1]].code,
            name: cities[this.pickerValue[1]].name
          });
        }
      
        if (this.level >= 3 && areas[this.pickerValue[2]]) {
          result.push({
            code: areas[this.pickerValue[2]].code,
            name: areas[this.pickerValue[2]].name
          });
        }
      
        if (this.level >= 4 && streets[this.pickerValue[3]]) {
          result.push({
            code: streets[this.pickerValue[3]].code,
            name: streets[this.pickerValue[3]].name
          });
        }
      
        this.selectedAddress = result;
    },

    handleConfirm() {
      this.showPicker = false;
      this.$emit('confirm', this.selectedAddress);
    }
  }
};
</script>

<style scoped>
.picker-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 24rpx 30rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1px solid #eee;
  box-sizing: border-box;
}

.picker-trigger.placeholder text {
  color: #999;
}

.arrow-icon {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 998;
}

.picker-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 999;
}

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

.header-cancel, .header-confirm {
  font-size: 32rpx;
  color: #666;
  padding: 10rpx 20rpx;
}

.header-confirm {
  color: #007aff;
  font-weight: 500;
}

.header-title {
  font-size: 34rpx;
  color: #333;
  font-weight: 500;
}

.picker-content {
  width: 100%;
}

.picker-view {
  width: 100%;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
}

::v-deep .uni-picker-view-indicator {
  position: relative;
}

::v-deep .uni-picker-view-indicator::before,
::v-deep .uni-picker-view-indicator::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #eee;
}

::v-deep .uni-picker-view-indicator::before {
  top: 0;
}

::v-deep .uni-picker-view-indicator::after {
  bottom: 0;
}
</style>