<template>
  <div class="region-selector">
    <div class="selection-container">
      <!-- 省份选择 -->
      <div class="select-group">
        <select 
          v-model="selectedProvince"
          @change="handleProvinceChange"
          class="select-control"
        >
          <option value="">请选择省份</option>
          <option 
            v-for="province in provinces" 
            :key="province.code" 
            :value="province.code"
          >
            {{ province.name }}
          </option>
        </select>
      </div>

      <!-- 城市选择及区县容器 -->
      <div class="city-district-container">
        <!-- 城市选择 -->
        <div class="select-group">
          <select 
            v-model="selectedCity" 
            :disabled="!selectedProvince"
            @change="handleCityChange"
            class="select-control"
          >
            <option value="">请选择城市</option>
            <option 
              v-for="city in filteredCities" 
              :key="city.code" 
              :value="city.code"
            >
              {{ city.name }}
            </option>
          </select>
        </div>

        <!-- 横向区县多选 -->
        <div class="districts-wrap" v-if="hasDistricts">
          <label
            v-for="district in filteredDistricts"
            :key="district.code"
            class="district-item"
            :class="{ selected: isSelected(district.code) }"
          >
            <input
              type="checkbox"
              :value="district.code"
              v-model="selectedDistricts"
              class="checkbox-input"
            >
            <span class="item-content">
              {{ district.name }}
              <span class="checkmark"></span>
            </span>
          </label>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, defineEmits, defineExpose } from 'vue'
import rawData from '@/assets/area-data.json'

// 响应式状态
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistricts = ref([])

// 计算属性
const provinces = computed(() => 
  rawData.map(p => ({
    code: String(p.code),
    name: p.province
  }))
)

const cities = computed(() => 
  rawData.flatMap(p => 
    p.citys.map(c => ({
      code: String(c.code),
      name: c.city,
      provinceCode: String(p.code)
    }))
  )
)

const districts = computed(() => 
  rawData.flatMap(p =>
    p.citys.flatMap(c =>
      (c.areas || []).map(a => ({
        code: String(a.code),
        name: a.area,
        cityCode: String(c.code)
      }))
    )
  )
)

const filteredCities = computed(() => 
  cities.value.filter(c => c.provinceCode === selectedProvince.value)
)

const filteredDistricts = computed(() => 
  districts.value.filter(d => d.cityCode === selectedCity.value)
)

const hasDistricts = computed(() => 
  filteredDistricts.value.length > 0
)

// 事件处理
const handleProvinceChange = () => {
  selectedCity.value = ''
  selectedDistricts.value = []
}

const handleCityChange = () => {
  selectedDistricts.value = []
}

// 监听与暴露
watch([selectedProvince, selectedCity], () => {
  selectedDistricts.value = []
})

const emit = defineEmits(['region-change'])

watch(selectedDistricts, newVal => {
  const names = filteredDistricts.value
    .filter(d => newVal.includes(d.code))
    .map(d => d.name)
  emit('region-change', names)
}, { deep: true })

defineExpose({
  getSelection: () => ({
    province: selectedProvince.value,
    city: selectedCity.value,
    districts: selectedDistricts.value
  }),
  reset: () => {
    selectedProvince.value = ''
    selectedCity.value = ''
    selectedDistricts.value = []
  }
})

defineOptions({ name: 'RegionSelector' })

// 辅助方法
const isSelected = code => selectedDistricts.value.includes(code)
</script>

<style scoped>
.region-selector {
  --primary: #3b82f6;
  --border: #e5e7eb;
  --hover-bg: #f3f4f6;
  --radius: 8px;
  --checkmark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z'/%3E%3C/svg%3E");
}

.selection-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  flex-wrap: nowrap;
}

.city-district-container {
  flex: 1;
  display: flex;
  gap: 8px;
  min-width: 400px;
}

.select-group {
  flex: 0 0 auto;
  min-width: 120px;
}

.select-control {
  height: 36px;
  padding: 0 12px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  font-size: 14px;
  appearance: none;
  background: white;
  transition: all 0.2s;
  
  &:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
  }
}

.districts-wrap {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 4px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  background: white;
  min-height: 36px;
}

.district-item {
  position: relative;
  cursor: pointer;
  
  .item-content {
    display: inline-flex;
    align-items: center;
    padding: 4px 28px 4px 12px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-size: 14px;
    position: relative;
    transition: all 0.2s;
  }

  .checkmark {
    position: absolute;
    right: 6px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    opacity: 0;
    background: var(--primary) var(--checkmark) no-repeat center;
    border-radius: 3px;
    transition: all 0.2s;
  }

  &:hover {
    .item-content {
      border-color: var(--primary);
      background: var(--hover-bg);
    }
  }

  &.selected {
    .item-content {
      background: var(--primary);
      border-color: var(--primary);
      color: white;
      padding-right: 12px;
    }
    .checkmark {
      opacity: 1;
      right: 8px;
    }
  }
}

.checkbox-input {
  position: absolute;
  opacity: 0;
}

@media (max-width: 768px) {
  .selection-container {
    flex-wrap: wrap;
  }
  
  .city-district-container {
    flex: 1 1 100%;
    min-width: auto;
    flex-direction: column;
    gap: 6px;
  }
  
  .districts-wrap {
    min-height: auto;
  }
  
  .district-item .item-content {
    font-size: 13px;
    padding: 3px 24px 3px 8px;
  }
}
</style>