<template>
  <div class="countryDrawerBox">
    <!-- direction="btt" -->
    <el-drawer
      v-model="countryDrawer"
      :before-close="handleBeforeClose"
      class="countryBox"
      size="50%"
    >
      <template #header>
        <h2>国家/地区</h2>
      </template>
      <template #default>
        <div class="countryContent">
          <el-row>
            <!-- 左侧 -->
            <el-col :sm="20" :lg="21" class="content-col">
              <el-row>
                <el-col :span="24">
                  <div class="searchBox">
                    <el-input
                      class="searchInput"
                      v-model="searchValue"
                      placeholder="请输入国家/地区名称"
                      @change="searchCountry"
                    />
                    <el-icon class="searchIcon"><Search /></el-icon>
                  </div>
                </el-col>
              </el-row>
              <div class="hotCountryBox" ref="containerRef">
                <div v-if="!searchValue">
                  <div class="title">热门国家/地区</div>
                  <div class="hotCountryList">
                    <el-row :gutter="20">
                      <template v-for="(item, index1) in hotCountriesList" :key="item.name">
                        <el-col :sm="12" :lg="8" @click="handleCountryClick(item)">
                          <div class="hotCountryItem">
                            <span>{{ item.name }}</span>
                            <span>{{ item.areaCode }}</span>
                          </div>
                        </el-col>
                      </template>
                    </el-row>
                  </div>
                  <div class="hotCountryList">
                    <template v-for="item in countryList" :key="item.areaCode">
                      <el-row>
                        <el-col :sm="24" :lg="24" style="margin: 5px 0">{{ item.title }}</el-col>
                      </el-row>
                      <el-row :gutter="20" :id="`${item.title}`">
                        <template v-for="(data, index2) in item.data" :key="item.name">
                          <el-col :span="24" @click="handleCountryClick(data)">
                            <div class="hotCountryItem">
                              <span>{{ data.name }}</span>
                              <span>{{ data.areaCode }}</span>
                            </div>
                          </el-col>
                        </template>
                      </el-row>
                    </template>
                  </div>
                </div>
                <div v-if="searchValue">
                  <div class="hotCountryList">
                    <el-row :gutter="20">
                      <template v-for="item in searchList" :key="item.name">
                        <el-col :sm="24" :lg="24" @click="handleCountryClick(item)">
                          <div class="hotCountryItem">
                            <span>{{ item.name }}</span>
                            <span>{{ item.areaCode }}</span>
                          </div>
                        </el-col>
                      </template>
                    </el-row>
                  </div>
                </div>
              </div>
            </el-col>
            <!-- 右侧锚点 -->
            <el-col :sm="4" :lg="3">
              <div class="anchor-wrapper">
                <el-anchor
                  :container="containerRef"
                  direction="vertical"
                  type="default"
                  :offset="30"
                  @click="handleAnchorClick"
                >
                  <el-anchor-link
                    v-for="item in anchorList"
                    :href="'#' + item.title"
                    :title="item.title"
                  />
                </el-anchor>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { watch, ref } from 'vue'
import { getCountryInfo, getSearchCountry } from '@/api/common'
const props = defineProps({
  showCountryDrawer: {
    type: Boolean,
    default: null
  },
  drawerInfo: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const emit = defineEmits(['close', 'confirmCountry'])
const countryDrawer = ref(false)
const countryList = ref([])
const originalData = ref([])
const hotCountriesList = ref([])
const containerRef = ref(null)
const anchorList = ref([])
const searchValue = ref('')
const searchList = ref([])
const isSearchLoading = ref(false)
const searchCountry = () => {
  isSearchLoading.value = true
  if (searchValue.value.trim()) {
    getSearchCountry(searchValue.value.trim()).then(res => {
      if (res.code === 200) {
        res.data.countryList.forEach(d => {
          d.areaCode = `+${d.areaCode}`
        })
        searchList.value = res.data.countryList
        isSearchLoading.value = false
      }
    })
  }
}
const handleCountryClick = item => {
  emit('confirmCountry', item)
  countryDrawer.value = false
  resetSearch()
}

// 锚点事件
const handleAnchorClick = e => {
  e.preventDefault()
}
// 处理抽屉关闭前的事件
const handleBeforeClose = done => {
  emit('close')
  countryDrawer.value = false
  resetSearch()
  done()
}
// 生成A-Z的分组结构
const generateGroups = () => {
  const groups = []
  // 生成26个字母的分组
  for (let i = 0; i < 26; i++) {
    const letter = String.fromCharCode(65 + i)
    groups.push({
      title: letter,
      data: []
    })
  }

  // 将国家数据分配到对应分组
  originalData.value.forEach(country => {
    const firstLetter = country.group.toUpperCase()
    const group = groups.find(g => g.title === firstLetter)
    if (group) {
      group.data.push(country)
    }
  })

  // 按国家名称排序每个分组内的数据
  groups.forEach(group => {
    group.data.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
  })

  return groups.filter(group => group.data.length > 0)
}
// 获取国家信息
const getCountry = () => {
  getCountryInfo().then(res => {
    if (res.code === 200) {
      originalData.value = res.data.groupCountries

      const result = generateGroups()
      result.forEach(item => {
        anchorList.value.push({ title: item.title })
        item.data.forEach(d => {
          d.areaCode = `+${d.areaCode}`
        })
      })
      res.data.hotCountries.forEach(item => {
        item.areaCode = `+${item.areaCode}`
      })
      hotCountriesList.value = res.data.hotCountries
      countryList.value = result
    }
  })
}
const resetSearch = () => {
  searchValue.value = ''
  searchList.value = []
  isSearchLoading.value = false
}
watch(searchValue, val => {
  if (!val) {
    searchList.value = []
    isSearchLoading.value = false
  }
})
watch(
  () => props.showCountryDrawer,
  val => {
    countryDrawer.value = val
    if (countryDrawer.value) {
      getCountry()
    }
  }
)
watch(countryDrawer, val => {
  if (!val) {
    resetSearch()
    emit('close', false)
  }
})
</script>
<style lang="scss" scoped>
::v-deep .el-drawer__header {
  margin-bottom: 0 !important;
}
.searchInput ::v-deep .el-input__wrapper {
  box-shadow: none !important;
  background-color: #fafbfd !important;
}
.searchInput ::v-deep .el-input__inner::placeholder {
  text-align: left !important;
}
.searchInput ::v-deep .el-input__inner {
  text-align: left !important;
}
.countryContent {
  box-sizing: border-box;
  .searchBox {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    background-color: #fafbfd;
    width: 100%;
    border-radius: 10px;
    padding: 4px 10px;
    .el-input {
      width: 80%;
    }
    .searchIcon {
      font-size: 20px;
      color: #1d2129;
    }
  }
  .hotCountryBox {
    overflow: hidden;
    height: calc(100vh - 100px);
    overflow-y: auto;
    box-sizing: border-box;
    width: 100%;
    scrollbar-width: none;
    -ms-overflow-style: none;
    .title {
      box-sizing: border-box;
      font-size: 18px;
      border-left: 4px solid #165dff;
      padding-left: 5px;
      margin-bottom: 10px;
    }
    .hotCountryList {
      box-sizing: border-box;
      width: 100%;
      .hotCountryItem {
        box-sizing: border-box;
        height: 40px;
        padding: 5px;
        border: 1px solid #e5e6e8;
        border-radius: 7px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 13px;
        color: #595959;
      }
      .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px 0;
      }
      .loading-text {
        margin-top: 10px;
        color: #909399;
      }
      .empty-state {
        text-align: center;
        padding: 40px 0;
        color: #909399;
      }
    }
  }
  .hotCountryBox::-webkit-scrollbar {
    display: none;
  }
  .anchor-wrapper {
    box-sizing: border-box;
    margin-left: 20px;
    border-left: 2px solid #d8ebff;
    ::v-deep(.el-anchor) {
      .el-anchor__link {
        padding: 4px 0;

        .el-anchor__link-title {
          font-size: 16px;
          color: #1d2129;

          &.is-active {
            color: #165dff;
            font-weight: 500;
          }
        }
      }
    }
    ::v-deep(.el-anchor__marker) {
      height: 10px !important;
      left: -6px !important;
      border-radius: 50% !important;
      width: 10px !important;
      border: 1px solid #409eff !important;
      background-color: transparent !important;
    }
  }
}
</style>
