<template>
  <view class="region-selector" @tap="openSelector">
    <text v-if="displayText" class="region-text">{{ displayText }}</text>
    <text v-else class="region-placeholder">{{ placeholder }}</text>
    <text class="region-arrow">▾</text>
  </view>

  <!-- 遮罩层 -->
  <view v-if="visible" class="mask" @tap="closeSelector"></view>

  <!-- 底部弹窗 -->
  <view :class="['popup-panel', { show: visible }]">
    <view class="panel-header">
      <text class="panel-title">选择地区</text>
      <text class="panel-close" @tap="closeSelector">✕</text>
    </view>
    <view class="panel-tabs">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', { active: activeTab === index }]"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.label }}</text>
        <view v-if="activeTab === index" class="tab-line"></view>
      </view>
    </view>
    <scroll-view class="panel-content" scroll-y :scroll-top="0">
      <view class="list-wrapper">
        <view
          v-for="item in currentList"
          :key="item.code"
          :class="['list-item', { selected: isItemSelected(item) }]"
          @tap="selectItem(item)"
        >
          <text class="item-name">{{ item.name }}</text>
          <text v-if="isItemSelected(item)" class="item-check">✓</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

interface RegionItem {
  code: string;
  name: string;
}

const props = withDefaults(
  defineProps<{
    province?: string;
    city?: string;
    district?: string;
    placeholder?: string;
  }>(),
  {
    province: '',
    city: '',
    district: '',
    placeholder: '请选择省/市/区',
  }
);

const emit = defineEmits<{
  (e: 'change', value: { province: string; city: string; district: string }): void;
}>();

const visible = ref(false);
const activeTab = ref(0);

const selectedProvince = ref<RegionItem | null>(null);
const selectedCity = ref<RegionItem | null>(null);
const selectedDistrict = ref<RegionItem | null>(null);

const tabs = computed(() => [
  { label: selectedProvince.value?.name || '请选择' },
  { label: selectedCity.value?.name || '请选择' },
  { label: selectedDistrict.value?.name || '请选择' },
]);

const displayText = computed(() => {
  const parts: string[] = [];
  if (selectedProvince.value) parts.push(selectedProvince.value.name);
  if (selectedCity.value) parts.push(selectedCity.value.name);
  if (selectedDistrict.value) parts.push(selectedDistrict.value.name);
  return parts.join(' ');
});

const provinceList = ref<RegionItem[]>([
  { code: '11', name: '北京市' },
  { code: '12', name: '天津市' },
  { code: '13', name: '河北省' },
  { code: '14', name: '山西省' },
  { code: '15', name: '内蒙古自治区' },
  { code: '21', name: '辽宁省' },
  { code: '22', name: '吉林省' },
  { code: '23', name: '黑龙江省' },
  { code: '31', name: '上海市' },
  { code: '32', name: '江苏省' },
  { code: '33', name: '浙江省' },
  { code: '34', name: '安徽省' },
  { code: '35', name: '福建省' },
  { code: '36', name: '江西省' },
  { code: '37', name: '山东省' },
  { code: '41', name: '河南省' },
  { code: '42', name: '湖北省' },
  { code: '43', name: '湖南省' },
  { code: '44', name: '广东省' },
  { code: '45', name: '广西壮族自治区' },
  { code: '46', name: '海南省' },
  { code: '50', name: '重庆市' },
  { code: '51', name: '四川省' },
  { code: '52', name: '贵州省' },
  { code: '53', name: '云南省' },
  { code: '54', name: '西藏自治区' },
  { code: '61', name: '陕西省' },
  { code: '62', name: '甘肃省' },
  { code: '63', name: '青海省' },
  { code: '64', name: '宁夏回族自治区' },
  { code: '65', name: '新疆维吾尔自治区' },
  { code: '71', name: '台湾省' },
  { code: '81', name: '香港特别行政区' },
  { code: '82', name: '澳门特别行政区' },
]);

const cityData: Record<string, RegionItem[]> = {
  '11': [{ code: '1101', name: '北京市' }],
  '12': [{ code: '1201', name: '天津市' }],
  '31': [{ code: '3101', name: '上海市' }],
  '50': [{ code: '5001', name: '重庆市' }],
  '32': [
    { code: '3201', name: '南京市' },
    { code: '3202', name: '无锡市' },
    { code: '3203', name: '徐州市' },
    { code: '3204', name: '常州市' },
    { code: '3205', name: '苏州市' },
    { code: '3206', name: '南通市' },
    { code: '3207', name: '连云港市' },
  ],
  '33': [
    { code: '3301', name: '杭州市' },
    { code: '3302', name: '宁波市' },
    { code: '3303', name: '温州市' },
    { code: '3304', name: '嘉兴市' },
    { code: '3305', name: '湖州市' },
    { code: '3306', name: '绍兴市' },
    { code: '3307', name: '金华市' },
  ],
  '44': [
    { code: '4401', name: '广州市' },
    { code: '4402', name: '韶关市' },
    { code: '4403', name: '深圳市' },
    { code: '4404', name: '珠海市' },
    { code: '4405', name: '汕头市' },
    { code: '4406', name: '佛山市' },
    { code: '4407', name: '江门市' },
  ],
};

const districtData: Record<string, RegionItem[]> = {
  '1101': [
    { code: '110101', name: '东城区' },
    { code: '110102', name: '西城区' },
    { code: '110105', name: '朝阳区' },
    { code: '110106', name: '丰台区' },
    { code: '110107', name: '石景山区' },
    { code: '110108', name: '海淀区' },
  ],
  '3101': [
    { code: '310101', name: '黄浦区' },
    { code: '310104', name: '徐汇区' },
    { code: '310105', name: '长宁区' },
    { code: '310106', name: '静安区' },
    { code: '310107', name: '普陀区' },
    { code: '310112', name: '闵行区' },
  ],
  '3201': [
    { code: '320102', name: '玄武区' },
    { code: '320104', name: '秦淮区' },
    { code: '320105', name: '建邺区' },
    { code: '320106', name: '鼓楼区' },
    { code: '320111', name: '浦口区' },
  ],
  '3301': [
    { code: '330102', name: '上城区' },
    { code: '330103', name: '下城区' },
    { code: '330104', name: '江干区' },
    { code: '330105', name: '拱墅区' },
    { code: '330106', name: '西湖区' },
  ],
  '4401': [
    { code: '440103', name: '荔湾区' },
    { code: '440104', name: '越秀区' },
    { code: '440105', name: '海珠区' },
    { code: '440106', name: '天河区' },
    { code: '440111', name: '白云区' },
  ],
  '4403': [
    { code: '440303', name: '罗湖区' },
    { code: '440304', name: '福田区' },
    { code: '440305', name: '南山区' },
    { code: '440306', name: '宝安区' },
    { code: '440307', name: '龙岗区' },
  ],
};

const currentList = computed(() => {
  if (activeTab.value === 0) {
    return provinceList.value;
  } else if (activeTab.value === 1) {
    if (!selectedProvince.value) return [];
    return cityData[selectedProvince.value.code] || [
      { code: selectedProvince.value.code + '01', name: selectedProvince.value.name.replace(/省$|自治区$|特别行政区$|壮族|维吾尔|回族/g, '') + '市辖区' },
    ];
  } else {
    if (!selectedCity.value) return [];
    return districtData[selectedCity.value.code] || [
      { code: selectedCity.value.code + '01', name: '市辖区' },
    ];
  }
});

function isItemSelected(item: RegionItem): boolean {
  if (activeTab.value === 0) return selectedProvince.value?.code === item.code;
  if (activeTab.value === 1) return selectedCity.value?.code === item.code;
  return selectedDistrict.value?.code === item.code;
}

function openSelector() {
  activeTab.value = 0;
  visible.value = true;
}

function closeSelector() {
  visible.value = false;
}

function switchTab(index: number) {
  if (index === 0) {
    activeTab.value = 0;
  } else if (index === 1 && selectedProvince.value) {
    activeTab.value = 1;
  } else if (index === 2 && selectedCity.value) {
    activeTab.value = 2;
  }
}

function selectItem(item: RegionItem) {
  if (activeTab.value === 0) {
    selectedProvince.value = item;
    selectedCity.value = null;
    selectedDistrict.value = null;
    activeTab.value = 1;
  } else if (activeTab.value === 1) {
    selectedCity.value = item;
    selectedDistrict.value = null;
    activeTab.value = 2;
  } else {
    selectedDistrict.value = item;
    emitChange();
    closeSelector();
  }
}

function emitChange() {
  emit('change', {
    province: selectedProvince.value?.name || '',
    city: selectedCity.value?.name || '',
    district: selectedDistrict.value?.name || '',
  });
}

watch(
  () => [props.province, props.city, props.district],
  () => {
    if (props.province) {
      const province = provinceList.value.find((p) => p.name === props.province);
      if (province) {
        selectedProvince.value = province;
        if (props.city) {
          const cities = cityData[province.code] || [];
          const city = cities.find((c) => c.name === props.city);
          if (city) {
            selectedCity.value = city;
            if (props.district) {
              const districts = districtData[city.code] || [];
              const district = districts.find((d) => d.name === props.district);
              if (district) {
                selectedDistrict.value = district;
              }
            }
          }
        }
      }
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.region-selector {
  display: flex;
  align-items: center;
  height: 88rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 24rpx;
}

.region-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.region-placeholder {
  flex: 1;
  font-size: 30rpx;
  color: #999;
}

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

/* 遮罩 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

/* 底部弹窗 */
.popup-panel {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 70vh;
  padding-bottom: env(safe-area-inset-bottom);
  transform: translateY(100%);
  transition: transform 0.3s ease;

  &.show {
    transform: translateY(0);
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #eee;
}

.panel-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.panel-close {
  font-size: 32rpx;
  color: #999;
  padding: 8rpx;
}

.panel-tabs {
  display: flex;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  padding: 20rpx 24rpx;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #FF6B35;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #FF6B35;
  border-radius: 2rpx;
}

.panel-content {
  height: 400rpx;
}

.list-wrapper {
  min-height: 400rpx;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &.selected {
    background: #fff8f5;
  }
}

.item-name {
  font-size: 30rpx;
  color: #333;
}

.list-item.selected .item-name {
  color: #FF6B35;
  font-weight: 600;
}

.item-check {
  font-size: 28rpx;
  color: #FF6B35;
}
</style>
