<!-- @/components/RegionCascader/index.vue -->
<template>
  <el-cascader
      ref="cascaderRef"
      v-model="selectedCodes"
      :options="areaOptions"
      :props="cascaderProps"
      :placeholder="placeholder"
      :clearable="clearable"
      :disabled="isDisabled"
      :filterable="filterable"
      :show-all-levels="showAllLevels"
      :separator="separator"
      :size="size"
      style="width: 100%"
      @change="handleChange"
  />
</template>

<script setup name="RegionCascader">
import { ref, computed, defineProps, defineEmits, watch, onMounted } from 'vue'
// 导入本地 JSON 数据
import { areaData } from '@/utils/area-data.js'

const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: () => []
  },
  placeholder: {
    type: String,
    default: '请选择省市区'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  filterable: {
    type: Boolean,
    default: false
  },
  showAllLevels: {
    type: Boolean,
    default: true
  },
  separator: {
    type: String,
    default: '/'
  },
  size: {
    type: String,
    default: 'default',
    validator: (value) => ['large', 'default', 'small'].includes(value)
  },
  // 新增：是否只读模式
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const cascaderRef = ref(null)
const selectedCodes = ref([])

// 计算禁用状态
const isDisabled = computed(() => {
  return props.disabled || props.readonly
})

// 级联选择器配置
const cascaderProps = {
  expandTrigger: 'hover',
  checkStrictly: false,
  emitPath: true,
  lazy: false,
  value: 'code',
  label: 'name',
  children: 'children',
  disabled: 'disabled' // 允许数据中有disabled字段控制禁用
}

// 根据 code 获取地区信息
const getAreaByCode = (code) => {
  return areaData.find(item => item.code === code)
}

// 根据 parent_code 获取子级地区
const getChildrenByParentCode = (parentCode) => {
  return areaData.filter(item => item.parent_code === parentCode)
}

// 处理地区数据，构建树形结构
const areaOptions = computed(() => {
  try {
    // 获取所有省份 (type === 0)
    const provinces = areaData.filter(item => item.type === 0)

    // 为每个省份添加子级（城市）
    const treeData = provinces.map(province => {
      // 获取该省份下的城市
      const cities = areaData.filter(item =>
          item.parent_code === province.code && item.type === 1
      )

      // 为每个城市添加子级（区县）
      const cityChildren = cities.map(city => {
        // 获取该城市下的区县
        const districts = areaData.filter(item =>
            item.parent_code === city.code && item.type === 2
        )

        return {
          code: city.code,
          name: city.name,
          children: districts.map(district => ({
            code: district.code,
            name: district.name
          }))
        }
      })

      return {
        code: province.code,
        name: province.name,
        children: cityChildren
      }
    })

    console.log('地区数据构建完成，省份数量:', treeData.length)
    return treeData
  } catch (error) {
    console.error('构建地区数据失败:', error)
    return []
  }
})

// 处理变化事件
const handleChange = (codes) => {
  // 如果禁用或只读，阻止选择
  if (isDisabled.value) {
    // 恢复原来的值
    selectedCodes.value = props.modelValue || []
    return
  }

  selectedCodes.value = codes

  // 构建完整的地区信息
  const areaInfo = buildAreaInfo(codes)

  emit('update:modelValue', codes)
  emit('change', areaInfo)
}

// 构建地区信息对象
const buildAreaInfo = (codes) => {
  if (!codes || codes.length === 0) {
    return {
      provinceCode: '',
      cityCode: '',
      districtCode: '',
      provinceName: '',
      cityName: '',
      districtName: '',
      fullName: '',
      fullAddress: ''
    }
  }

  const provinceCode = codes[0] || ''
  const cityCode = codes[1] || ''
  const districtCode = codes[2] || ''

  const provinceName = provinceCode ? getAreaNameByCode(provinceCode) : ''
  const cityName = cityCode ? getAreaNameByCode(cityCode) : ''
  const districtName = districtCode ? getAreaNameByCode(districtCode) : ''

  const names = [provinceName, cityName, districtName].filter(Boolean)

  return {
    provinceCode,
    cityCode,
    districtCode,
    provinceName,
    cityName,
    districtName,
    codes: [...codes],
    names,
    fullName: names.join(props.separator),
    fullAddress: names.join('')
  }
}

const getAreaNameByCode = (code) => {
  if (!code) return ''
  const area = areaData.find(item => item.code === code)
  return area ? area.name : ''
}

// 处理初始值，支持字符串形式的code（如"110000"）或数组形式
const initSelectedCodes = () => {
  const value = props.modelValue

  if (!value || value.length === 0) {
    selectedCodes.value = []
    return
  }

  // 如果是字符串，尝试转换为数组
  if (typeof value === 'string') {
    // 如果是逗号分隔的字符串
    if (value.includes(',')) {
      selectedCodes.value = value.split(',').map(item => item.trim())
    } else {
      // 单个code，但级联选择器需要数组格式
      selectedCodes.value = [value]
    }
  } else if (Array.isArray(value)) {
    selectedCodes.value = [...value]
  } else {
    selectedCodes.value = []
  }
}

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  if (JSON.stringify(selectedCodes.value) !== JSON.stringify(newVal || [])) {
    initSelectedCodes()
  }
}, { immediate: true, deep: true })

// 监听disabled状态变化
watch(() => props.disabled, (newVal) => {
  console.log('RegionCascader disabled状态变化:', newVal)
  if (cascaderRef.value && newVal) {
    // 确保级联选择器被正确禁用
    cascaderRef.value.blur()
  }
})

// 组件挂载时初始化
onMounted(() => {
  initSelectedCodes()
  console.log('RegionCascader组件已加载，省份数量:', areaOptions.value.length)
  console.log('RegionCascader disabled状态:', props.disabled)
  console.log('RegionCascader readonly状态:', props.readonly)
})

// 暴露方法给父组件
defineExpose({
  getSelectedCodes: () => selectedCodes.value,
  clearSelection: () => {
    selectedCodes.value = []
    emit('update:modelValue', [])
    emit('change', buildAreaInfo([]))
  },
  setDisabled: (disabled) => {
    // 这个方法可以通过ref调用
    console.log('设置禁用状态:', disabled)
  }
})
</script>