<template>
  <!-- 底部弹窗遮罩层 -->
  <view v-if="visible" class="picker-layer-mask" @click="close"></view>
  <!-- 弹窗内容区 -->
  <view v-if="visible" class="picker-layer-popup">
    <view class="picker-layer-panel">
      <!-- 可自定义头部 -->
      <view class="picker-layer-header">
        <text class="picker-layer-cancel" @click="close">取消</text>
        <text class="picker-layer-confirm" @click="handleConfirm">确定</text>
      </view>
      <view class="picker-layer-view-mask-top"></view>
      <view class="picker-layer-view-mask-bottom"></view>

      <!-- picker-view 选择器核心 -->
      <picker-view ref="upicker" class="picker-layer-view" mask-style="background: rgb(246, 248, 250); z-index: 0;"
        indicator-style="border-radius: 10px; height: 50px; background:#ffffff; z-index:0" :value="pickerValue"
        :immediate-change="true" @change="bindChange">
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item, key) in areaList.province_list" :key="key">{{ item }}</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item, key) in filteredCityList" :key="key">{{ item }}</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item, key) in filteredCountyList" :key="key">{{ item }}</view>
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { areaList } from '@vant/area-data';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  defaultData: {
    type: Object,
    default: {}
  },
  formData: {
    type: Array,
    default: []
  },
  currentIndex: {
    type: String,
    default: ''
  },
  currentSubIndex: {
    type: String,
    default: ''
  },
  currentFieldIndex: {
    type: String,
    default: ''
  },
})

const emit = defineEmits(['update:visible', 'confirm'])
const upicker = ref(null)
// picker当前选中值
const pickerValue = ref([0, 0, 0])
// 当前选中的省、市、区的code
const selectedProvince = ref('')
const selectedCity = ref('')

// 根据选中的省份过滤城市列表
const filteredCityList = computed(() => {
  if (!selectedProvince.value) {
    // 获取第一个省份的code
    const provinceCodes = Object.keys(areaList.province_list)
    if (provinceCodes.length > 0) {
      selectedProvince.value = provinceCodes[0]
    }
  }
  const result = {}
  for (const code in areaList.city_list) {
    // 城市code的前两位与省份code的前两位相同，则属于该省份
    if (code.substring(0, 2) === selectedProvince.value.substring(0, 2)) {
      result[code] = areaList.city_list[code]
    }
  }
  console.log('更新市----')
  return result
})

// 根据选中的城市过滤区县列表
const filteredCountyList = computed(() => {
  // 如果还没有选中的城市，使用第一个城市
  if (!selectedCity.value) {
    const cityCodes = Object.keys(filteredCityList.value)
    if (cityCodes.length > 0) {
      selectedCity.value = cityCodes[0]
    }
  }

  const result = {}
  for (const code in areaList.county_list) {
    // 区县code的前四位与城市code的前四位相同，则属于该城市
    if (code.substring(0, 4) === selectedCity.value.substring(0, 4)) {
      result[code] = areaList.county_list[code]
    }
  }
  console.log('更新区县----')
  return result
})

// picker值变化事件
const bindChange = (e) => {
  const val = e.detail.value
  const oldVal = [...pickerValue.value]

  // 如果省份值改变，市和区都默认选择第一项
  if (val[0] !== oldVal[0]) {
    val[1] = 0
    val[2] = 0
    console.log('省份值改变')
    // 更新选中的省份
    const provinceCodes = Object.keys(areaList.province_list)
    if (provinceCodes[val[0]]) {
      selectedProvince.value = provinceCodes[val[0]]
    }
    // 由于省份改变，需要重新计算城市列表，所以重置选中的城市
    const newCityCodes = Object.keys(filteredCityList.value)
    if (newCityCodes.length > 0) {
      selectedCity.value = newCityCodes[0]
    }
  } else if (val[1] !== oldVal[1]) {
    // 如果改变市，则区县默认选择第一项
    console.log('市改变')
    val[2] = 0
    // 获取选中的省份
    const provinceCodes = Object.keys(areaList.province_list)
    if (provinceCodes[val[0]]) {
      selectedProvince.value = provinceCodes[val[0]]
    }
    // 获取选中的城市
    const cityCodes = Object.keys(filteredCityList.value)
    if (cityCodes[val[1]]) {
      selectedCity.value = cityCodes[val[1]]
    }
  } else {
    // 如果只改变了区县
    console.log('区县改变')
  }
  pickerValue.value = val
}

// 关闭弹窗
const close = () => {
  emit('update:visible', false)
}

// 确认选择
const handleConfirm = () => {
  // 获取选中的值
  const provinceCodes = Object.keys(areaList.province_list)
  const cityCodes = Object.keys(filteredCityList.value)
  const countyCodes = Object.keys(filteredCountyList.value)

  const selected = {
    provinceId: provinceCodes[pickerValue.value[0]],
    provinceName: areaList.province_list[provinceCodes[pickerValue.value[0]]],
    cityId: cityCodes[pickerValue.value[1]],
    cityName: filteredCityList.value[cityCodes[pickerValue.value[1]]],
    regionId: countyCodes[pickerValue.value[2]],
    regionName: filteredCountyList.value[countyCodes[pickerValue.value[2]]],
  }
  emit('confirm', {currentIndex: props.currentIndex, currentSubIndex: props.currentSubIndex, currentFieldIndex: props.currentFieldIndex,selected})
}

const open=()=> {
	const { currentIndex, currentSubIndex, currentFieldIndex, formData } = props
	if(currentIndex !=='' && currentFieldIndex !== ''){
		console.log(currentIndex, currentSubIndex, currentFieldIndex, formData,'123open--')
		let obj={}
		if (currentSubIndex !== '') {
			obj = formData[currentIndex].subFormList[currentSubIndex].formComponentList[currentFieldIndex].fieldValue
		} else {
			obj = formData[currentIndex].formComponentList[currentFieldIndex].fieldValue
		}
		//如果props.defaultData有默认值，如何处理弹窗的默认值
		// if (props.defaultData && props.defaultData.provinceId && props.defaultData.cityId && props.defaultData.regionId) {
		if (obj?.provinceId && obj?.cityId && obj?.regionId) {
		  // 根据默认值查找对应的索引位置
		  const provinceCodes = Object.keys(areaList.province_list)
		  const provinceIndex = provinceCodes.findIndex(code => code === obj.provinceId)
		  // 更新选中的省份
		  if (provinceIndex !== -1) {
			selectedProvince.value = obj.provinceId
		
			// 查找城市索引
			const cityCodes = Object.keys(filteredCityList.value)
			const cityIndex = cityCodes.findIndex(code => code === obj.cityId)
		
			// 更新选中的城市
			if (cityIndex !== -1) {
			  selectedCity.value = obj.cityId
		
			  // 查找区域索引
			  const countyCodes = Object.keys(filteredCountyList.value)
			  const countyIndex = countyCodes.findIndex(code => code === obj.regionId)
		
			  // 设置picker的值
			  pickerValue.value = [
				provinceIndex,
				cityIndex,
				countyIndex !== -1 ? countyIndex : 0
			  ]
			} else {
			  // 城市未找到，默认选择第一个城市
			  pickerValue.value = [
				provinceIndex,
				0,
				0
			  ]
			}
		  }
		}
	}
}
defineExpose({
	open
})
</script>

<style lang="less" scoped>
/* 保持原有样式不变 */
.picker-layer-mask {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 3999;
}

.picker-layer-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 4000;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: picker-layer-up 0.3s;
}

@keyframes picker-layer-up {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

.picker-layer-panel {
  width: 100vw;
  height: 50vh;
  background: #f6f8fa;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.picker-layer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 140rpx;
  box-sizing: border-box;
  background: #f6f8fa;
  padding: 0 32rpx;

  .picker-layer-cancel {
    color: #6f6d67;
    font-size: 30rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #ffffff;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .picker-layer-confirm {
    color: #ffffff;
    font-size: 30rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #d3a358;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .picker-layer-title {
    color: #222;
    font-size: 30rpx;
    font-weight: bold;
  }
}

.picker-layer-view {
  flex: 1;
  width: 100%;
  height: 100%;
}

.picker-layer-item {
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  color: #1d1e25;
}

.picker-layer-view-mask-top {
  position: absolute;
  top: 140rpx;
  left: 0;
  width: 100%;
  height: calc(50% - 100rpx);
  z-index: 1;
  background: linear-gradient(to bottom,
      rgb(246, 248, 250) 0%,
      rgba(255, 255, 255, 0.5) 100%);
  pointer-events: none;
}

.picker-layer-view-mask-bottom {
  position: absolute;
  bottom: 0rpx;
  left: 0;
  width: 100%;
  height: calc(50% - 100rpx);
  z-index: 1;
  background: linear-gradient(to top,
      rgb(246, 248, 250) 0%,
      rgba(255, 255, 255, 0.5) 100%);
  pointer-events: none;
}
</style>