<template>
  <view v-if="visible" class="popup-mask" @tap="close">
    <view class="city-picker" @tap.stop>
      <!-- 头部 -->
      <view class="picker-header">
        <text class="picker-title">选择城市</text>
        <text class="picker-close" @tap="close">✕</text>
      </view>

      <!-- 定位城市 -->
      <view class="locate-section">
        <view class="locate-label">
          <u-icon name="map-fill" :size="20" color="#FF6B35" />
          <text class="locate-text">当前定位</text>
        </view>
        <view class="locate-city" @tap="selectLocatedCity">
          <text class="city-text">{{ locatedCity || '定位中...' }}</text>
        </view>
      </view>

      <!-- 热门城市 -->
      <view class="hot-section">
        <text class="section-title">热门城市</text>
        <view class="city-grid">
          <view
            v-for="item in hotCities"
            :key="item"
            :class="['city-tag', { active: selectedCity === item }]"
            @tap="selectCity(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 城市列表 -->
      <scroll-view
        scroll-y
        class="city-list"
        :scroll-top="scrollTop"
        scroll-with-animation
      >
        <view v-for="(group, index) in cityGroups" :key="group.letter" class="city-group" :data-index="index">
          <text class="group-letter">{{ group.letter }}</text>
          <view
            v-for="city in group.cities"
            :key="city"
            :class="['city-item', { active: selectedCity === city }]"
            @tap="selectCity(city)"
          >
            {{ city }}
          </view>
        </view>
      </scroll-view>

      <!-- 字母索引 -->
      <view class="letter-index">
        <view
          v-for="group in cityGroups"
          :key="group.letter"
          :class="['letter-item', { active: currentLetter === group.letter }]"
          @tap="scrollToLetter(group.letter)"
        >
          {{ group.letter }}
        </view>
      </view>
    </view>
  </view>
</template>

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

const props = defineProps<{
  city?: string;
}>();

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

const visible = ref(false);
const selectedCity = ref(props.city || '上海');
const locatedCity = ref('');
const scrollTop = ref(0);
const currentLetter = ref('');

// 监听 props.city 变化
watch(() => props.city, (newCity) => {
  if (newCity) {
    selectedCity.value = newCity;
  }
});

const hotCities = [
  '上海', '北京', '广州', '深圳',
  '杭州', '成都', '重庆', '西安',
  '三亚', '厦门', '南京', '武汉',
];

const cityGroups = [
  { letter: 'A', cities: ['阿坝', '阿克苏', '阿拉善', '阿勒泰', '安康', '安庆', '安顺', '安阳', '鞍山'] },
  { letter: 'B', cities: ['白城', '白山', '白银', '百色', '蚌埠', '包头', '宝鸡', '保定', '保山', '北海', '北京', '本溪', '毕节', '滨州', '博尔塔拉'] },
  { letter: 'C', cities: ['沧州', '昌都', '昌吉', '长春', '长沙', '长治', '常德', '常州', '巢湖', '朝阳', '潮州', '郴州', '成都', '承德', '池州', '赤峰', '崇左', '滁州', '楚雄'] },
  { letter: 'D', cities: ['达州', '大连', '大庆', '大同', '大兴安岭', '丹东', '德宏', '德阳', '德州', '迪庆', '定西', '东莞', '东营', '鄂尔多斯', '鄂州', '恩施'] },
  { letter: 'E', cities: ['鄂尔多斯', '鄂州', '恩施'] },
  { letter: 'F', cities: ['防城港', '佛山', '福州', '抚顺', '抚州', '阜新', '阜阳'] },
  { letter: 'G', cities: ['甘南', '甘孜', '赣州', '固原', '广安', '广元', '广州', '贵港', '贵阳', '桂林', '果洛'] },
  { letter: 'H', cities: ['哈尔滨', '哈密', '海北', '海东', '海口', '海南', '海西', '邯郸', '汉中', '杭州', '毫州', '合肥', '河池', '河源', '菏泽', '贺州', '鹤壁', '鹤岗', '黑河', '衡水', '衡阳', '红河', '呼和浩特', '呼伦贝尔', '湖州', '葫芦岛', '怀化', '淮安', '淮北', '淮南', '黄冈', '黄南', '黄山', '黄石', '惠州'] },
  { letter: 'J', cities: ['鸡西', '吉安', '吉林', '济南', '济宁', '济源', '佳木斯', '嘉兴', '嘉峪关', '江门', '焦作', '揭阳', '金昌', '金华', '锦州', '晋城', '晋中', '荆门', '荆州', '景德镇', '九江', '酒泉'] },
  { letter: 'K', cities: ['开封', '喀什', '克拉玛依', '克孜勒苏', '昆明'] },
  { letter: 'L', cities: ['来宾', '莱芜', '兰州', '廊坊', '乐山', '丽江', '丽水', '连云港', '凉山', '辽阳', '辽源', '聊城', '临沧', '临汾', '临夏', '临沂', '林芝', '柳州', '六安', '六盘水', '龙岩', '陇南', '娄底', '泸州', '吕梁', '洛阳', '漯河', '泸州'] },
  { letter: 'M', cities: ['马鞍山', '茂名', '眉山', '梅州', '绵阳', '牡丹江'] },
  { letter: 'N', cities: ['那曲', '南昌', '南充', '南京', '南宁', '南平', '南通', '南阳', '内江', '宁波', '宁德', '怒江'] },
  { letter: 'P', cities: ['盘锦', '攀枝花', '平顶山', '平凉', '萍乡', '莆田', '濮阳', '普洱'] },
  { letter: 'Q', cities: ['七台河', '齐齐哈尔', '黔东南', '黔南', '黔西南', '钦州', '秦皇岛', '青岛', '清远', '庆阳', '曲靖', '衢州', '泉州'] },
  { letter: 'R', cities: ['日喀则', '日照', '荣成'] },
  { letter: 'S', cities: ['三门峡', '三明', '三亚', '山南', '汕头', '汕尾', '商洛', '商丘', '上海', '上饶', '韶关', '邵阳', '绍兴', '深圳', '神农架', '沈阳', '十堰', '石家庄', '石嘴山', '双鸭山', '朔州', '四平', '松原', '苏州', '宿迁', '宿州', '绥化', '随州', '遂宁'] },
  { letter: 'T', cities: ['台州', '太原', '泰安', '泰州', '唐山', '天津', '天水', '铁岭', '通化', '通辽', '铜川', '铜陵', '铜仁', '吐鲁番', '图木舒克'] },
  { letter: 'W', cities: ['威海', '潍坊', '渭南', '温州', '文山', '乌海', '乌兰察布', '乌鲁木齐', '无锡', '吴忠', '芜湖', '梧州', '武汉', '武威'] },
  { letter: 'X', cities: ['西安', '西宁', '西双版纳', '锡林郭勒', '厦门', '咸宁', '咸阳', '湘潭', '湘西', '襄阳', '孝感', '忻州', '新乡', '新余', '信阳', '兴安', '邢台', '徐州', '许昌', '宣城', 'xuancheng'] },
  { letter: 'Y', cities: ['雅安', '烟台', '延安', '延边', '盐城', '扬州', '阳江', '阳泉', '伊春', '伊犁', '宜宾', '宜昌', '宜春', '益阳', '银川', '鹰潭', '营口', '永州', '榆林', '玉林', '玉树', '玉溪', '岳阳', '云浮', '运城'] },
  { letter: 'Z', cities: ['枣庄', '湛江', '张家界', '张家口', '张掖', '漳州', '昭通', '肇庆', '镇江', '郑州', '中山', '中卫', '舟山', '周口', '株洲', '珠海', '驻马店', '资阳', '淄博', '自贡', '遵义'] },
];

function open() {
  visible.value = true;
  selectedCity.value = props.city || '上海';
}

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

function selectCity(city: string) {
  selectedCity.value = city;
  emit('change', city);
  close();
}

function selectLocatedCity() {
  if (locatedCity.value && locatedCity.value !== '定位失败' && locatedCity.value !== '定位中...') {
    selectCity(locatedCity.value);
  }
}

function scrollToLetter(letter: string) {
  currentLetter.value = letter;

  // 计算目标字母的索引
  const index = cityGroups.findIndex(group => group.letter === letter);
  if (index === -1) return;

  // 计算滚动位置
  // 每个分组的高度 = 标题高度(约60rpx) + 城市数量 * 城市项高度(约80rpx)
  let scrollPosition = 0;
  for (let i = 0; i < index; i++) {
    const group = cityGroups[i];
    // 标题高度 + 城市列表高度
    scrollPosition += 60 + (group.cities.length * 80);
  }

  // 转换 rpx 到 px (假设 1rpx = 0.5px，实际根据设备不同)
  scrollTop.value = scrollPosition * 0.5;

  console.log(`滚动到字母 ${letter}, 索引 ${index}, 位置 ${scrollTop.value}px`);
}

// 逆地理编码：将经纬度转换为城市名（调用后端接口）
function reverseGeocode(latitude: number, longitude: number) {
  uni.request({
    url: `${import.meta.env?.VITE_MP_API_BASE_URL || 'http://localhost:3000'}/api/app/location/geocode`,
    method: 'GET',
    data: {
      latitude,
      longitude,
    },
    success: (res: any) => {
      if (res.statusCode === 200 && res.data?.data?.city) {
        const city = res.data.data.city;
        locatedCity.value = city;

        // 自动更新首页城市
        emit('change', city);
      } else {
        locatedCity.value = '定位失败';
      }
    },
    fail: () => {
      locatedCity.value = '定位失败';
    },
  });
}

function getLocation() {
  locatedCity.value = '定位中...';

  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      // 获取到经纬度后，调用后端接口进行逆地理编码
      reverseGeocode(res.latitude, res.longitude);
    },
    fail: (err) => {
      console.error('定位失败:', err);
      locatedCity.value = '定位失败';

      // 提示用户授权
      if (err.errMsg && err.errMsg.includes('auth')) {
        uni.showModal({
          title: '需要定位权限',
          content: '请在设置中开启定位权限以获取当前城市',
          confirmText: '去设置',
          success: (modalRes) => {
            if (modalRes.confirm) {
              uni.openSetting();
            }
          },
        });
      }
    },
  });
}

onMounted(() => {
  getLocation();
});

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.city-picker {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
  padding-bottom: env(safe-area-inset-bottom);
  position: relative;
  overflow: hidden;
}

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

.picker-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
}

.picker-close {
  font-size: 36rpx;
  color: #999;
  padding: 8rpx;
}

.locate-section {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-shrink: 0;
  gap: 24rpx;
}

.locate-label {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-shrink: 0;
}

.locate-text {
  font-size: 26rpx;
  color: #999;
}

.locate-city {
  background: #fff1eb;
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  flex: 0 0 auto;
  max-width: 400rpx;
}

.locate-city .city-text {
  font-size: 28rpx;
  color: #FF6B35;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.hot-section {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  flex-shrink: 0;
}

.section-title {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 20rpx;
  display: block;
}

.city-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.city-tag {
  padding: 14rpx 28rpx;
  font-size: 28rpx;
  color: #333;
  background: #f5f7fa;
  border-radius: 8rpx;

  &.active {
    color: #FF6B35;
    background: #fff1eb;
    font-weight: 500;
  }
}

.city-list {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.city-group {
  padding: 0 32rpx;
}

.group-letter {
  font-size: 26rpx;
  color: #999;
  padding: 16rpx 0;
  display: block;
  border-bottom: 1rpx solid #f5f5f5;
}

.city-item {
  padding: 24rpx 0;
  font-size: 30rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;

  &.active {
    color: #FF6B35;
    font-weight: 500;
  }
}

.letter-index {
  position: absolute;
  right: 8rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2rpx;
  z-index: 10;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 20rpx;
  padding: 8rpx 4rpx;
  max-height: 80%;
  overflow-y: auto;
}

.letter-item {
  font-size: 20rpx;
  color: #999;
  padding: 2rpx 6rpx;
  font-weight: 500;
  line-height: 1.2;
  min-width: 32rpx;
  text-align: center;
  transition: all 0.2s ease;

  &.active {
    color: #FF6B35;
    background: #fff1eb;
    border-radius: 4rpx;
    transform: scale(1.1);
  }

  &:active {
    color: #FF6B35;
    background: #fff1eb;
    border-radius: 4rpx;
  }
}
</style>
