<template>
  <div>
    <div v-if="filterList.length" class="sticky top-50 z-50 bg-white w-full">
      <van-dropdown-menu active-color="#FF9300" ref="dropDownMenuRef">
        <van-dropdown-item @closed="onAreaFilterClose" :title="areaFilterTitle" ref="itemRef">
          <van-tree-select
            @click-nav="handleAreaClick"
            @click-item="handleFilterClick"
            v-model:active-id="activeId"
            v-model:main-active-index="areaIndex"
            :items="filterList"
          />
        </van-dropdown-item>
        <van-dropdown-item
          :title="writeTypeText"
          v-model="travelWriteType"
          :options="writeTypeList"
        ></van-dropdown-item>
      </van-dropdown-menu>
    </div>
    <div  class="px-10 pt-20">
      <div v-if="recomendList.length" class="scrollbar w-full" style="overflow-x: auto">
        <div class="flex ">
          <NuxtLink :to="'/t/'+item.id" v-for="(item,index) in recomendList" :key="index" class="w-[110px] border rounded overflow-hidden shrink-0 mr-[12px]">
            <div class="w-full h-[76px] bg-[#dedede]">
              <img v-if="Array.isArray(item?.tourismUrlsAfterConvert)" :src="item?.tourismUrlsAfterConvert[0]" class="w-full h-full object-cover" alt="">
            </div>
            <div class="text-clip overflow-hidden text-[13px] text-[13px] px-5 h-[40px] w-full mt-5 overflow-ellipsis"
              style="line-height:18px;height:36px">
              {{ item.projectTitle }}
            </div>
            <div class="flex justify-end text-[#FF476A] text-[14px] font-semibold pr-10">
              {{ item.priceUnit }}{{ item.price }}
            </div>
          </NuxtLink>
        </div>
      </div>
      <van-list v-if="dataList.length" v-model:loading="loading" :immediate-check="false" :finished="finished"
        loading-text="加载中..." error-text="获取失败" @load="loadMore">
        <template v-for="itemData in dataList">
          <NuxtLink class="group flex relative cursor-pointer bg-white pb-10 mt-20" :to="`/yj/${itemData.id}`">
            <div class="aspect-[120/80] h-80 shrink-0 rounded overflow-hidden bg-[#ddd]">
              <img v-if="Array.isArray(itemData?.tourismUrlsAfterConvert)" :src="itemData?.tourismUrlsAfterConvert[0]"
                class="w-full h-full rounded object-cover" alt="" srcset="" />
            </div>
            <div
              class="h-80 pl-[8px] flex flex-col text-[#FD9A00] justify-between w-[calc(100%-120px)]"
            >
              <div class="truncate w-full text-[14px] font-bold">
                <img
                  v-if="itemData.isOriginal == 1"
                  src="~/assets/img/yuanchuang.png"
                  class="mt-3 w-[30px] h-[16px]"
                  alt=""
                  style="float: left"
                />
                {{ itemData.projectTitle }}
              </div>
              <div class="w-full overflow-x-auto scrollbar" v-if="itemData.noteLabel">
                <div class="flex flex-nowrap">
                  <div
                    v-for="tag in convertTag(itemData.noteLabel)"
                    class="rounded-full text-[#666] border-[#666] text-[10px] pr-6 pl-6 float-left mr-10 shrink-0"
                    style="border: 0.5px solid #666666"
                  >
                    {{ tag }}
                  </div>
                </div>
              </div>
              <div class="flex justify-end items-center text-[12px] text-[#999]">
                <div class="flex items-center mr-10">
                  <van-icon name="eye-o" class="mr-5" />
                  {{ transferCount(itemData.pageViewCount) }}
                </div>
                <div class="flex items-center mr-10">
                  <van-icon name="good-job-o" class="mr-5" />
                  {{ transferCount(itemData.likeCount) }}
                </div>
              </div>
            </div>
            <div class="w-full h-10 absolute top-[100%] left-0 flex items-center justify-between">
              <div
                v-for="item in 40"
                class="w-[3%] h-[1px] border border-[#ddd]"
                style="transform: scale(0.5)"
              ></div>
            </div>
          </NuxtLink>
        </template>
      </van-list>
      <Empty v-if="!dataList.length && !loading" />
    </div>
  </div>
</template>

<script setup>
const route = useRoute()
const router = useRouter()

// 推荐项目
const { data } = await useMyFetch(
  `website/tourism/project/list?isHotspot=1&pageNum=1&pageSize=10`
)

const recomendList = ref([])


const AREA_TEXT = '地域'

const areaId = useRouteParam('area')

const filterList = ref([]) //地域列表

const curFilter = ref({}) //当前筛选条件(国家)

const areaIndex = ref(0) //地域索引

const areaFilterTitle = ref(AREA_TEXT)

const activeId = computed(() => curFilter.value.id)

const activeIndex = ref('')

const dropDownMenuRef = ref(null)
// 获取筛选列表
async function getFilters() {
  const { data } = await request(`/website/tourism/projectTravelNotes/travelNotesDirectoryList`).finally(() => { closeToast() })

  if (!Array.isArray(data)) return getList()
  let country = null;
  data.map((item, index) => {
    data[index].id = item.areaId
    data[index].text = item.areaName
    if (Array.isArray(item.children)) {
      data[index].children.unshift({ countryName: '全部', countryId: item.areaId+',all' })
      item.children.map((item2, index2) => {
        data[index].children[index2].id = item2.countryId
        data[index].children[index2].text = item2.countryName
        data[index].children[index2].areaId = item.areaId
        data[index].children[index2].areaName = item.areaName
      })
    }
    
    if(route.query.area && item.areaId == route.query.area){
      curFilter.value.areaId = route.query.area
      document.title = item.areaName
      areaIndex.value = index + 1
      areaFilterTitle.value = item.areaName
    }

    if(route.query.country){
      const con = item.children.filter(c=>c.countryId == route.query.country)[0]
      if(con){
        country = con
      }
    }
  })
  if(country){
    curFilter.value.countryId = route.query.country
    curFilter.value.id = route.query.country
    areaFilterTitle.value = country.areaName +'-'+country.countryName
  }else{
    if(curFilter.value.areaId){
      curFilter.value.countryId = curFilter.value.areaId + ',all'
      curFilter.value.id = curFilter.value.areaId + ',all'
    }
  }
  if(route.query.country && !route.query.area){
    data.map((item,index)=>{
      item.children.map(subItem=>{
        if(subItem.id == route.query.country){
          areaIndex.value = index + 1
        }
      })
    })
  }
  filterList.value = [{ id: 0, text: '全部', children: [{ id: 0, text: '全部' }] }, ...data]
  getList()
  getRecommend()
}

// 监听地域筛选框收起
function onAreaFilterClose() {
  areaIndex.value = activeIndex.value
}

const pageNum = ref(1)
const pageSize = ref(10)
const dataList = ref([])
const loading = ref(true)
const finished = ref(false)
// 是否原创 0 全部 1 原创
const travelWriteType = ref(0)
const writeTypeList = ref([
  { text: '全部', value: 0 },
  { text: '原创', value: 1 }
])
const writeTypeText = computed(() =>
  writeTypeList.value[travelWriteType.value].value ? '原创' : '是否原创'
)
watch(travelWriteType, () => {
  pageNum.value = 1
  dataList.value = []
  getList()
})

// 获取游记列表
async function getList() {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  const param = {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }

  if (curFilter.value.areaId) param.areaId = curFilter.value.areaId

  if (curFilter.value.id) {
    const countryId = curFilter.value.id.split(',')
    if (!countryId[1]) param.countryId = curFilter.value.id
  }

  if (travelWriteType.value) {
    param.travelWriteType = travelWriteType.value
  }
  loading.value = true
  const { data } = await request(`/website/tourism/projectTravelNotes/travelNotesPageList`, { query: param }).finally(() => closeToast())

  dataList.value = dataList.value.concat(data.dataList)
  loading.value = false
  if (dataList.value.length >= data.totalCount) {
    finished.value = true
  } else {
    finished.value = false
  }
}
// 选择洲
function handleAreaClick(index) {
  areaIndex.value = index
}

// 选择国家
function handleFilterClick(item) {
  curFilter.value = item
  // if (!item.id) {
  //   areaFilterTitle.value = AREA_TEXT
  // } else {
  //   const areaText = filterList.value[areaIndex.value].text || ''
  //   const cityText = item.text || ''
  //   activeIndex.value = areaIndex.value
  //   areaFilterTitle.value = areaText + '-' + cityText
  // }
  // pageNum.value = 1
  // dataList.value = []
  // getList()
  // getRecommend()
  // dropDownMenuRef.value && dropDownMenuRef.value.close()
  // document.title = `${item.id ? '游记-' + item.areaName + '-' + item.text : '旅游笔记'}`
  
  let search =''
  if(item.areaId) search+='area='+item.areaId
  if(item.id) {
    const i = item.countryId.split(',')
    if(!i[1]){
      search+=`${item.areaId?'&':''}country=${item.id}`
    }
    
  }
  location.search=`${search}`
  
}

function transferCount(num = 0) {
  if (isNaN(num)) return 0
  if (num > 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else {
    return num
  }
}
function loadMore() {
  pageNum.value++
  getList()
}
function convertTag(str = '') {
  if (typeof str !== 'string') return []
  return str.split('&')
}

async function getRecommend(){
  const param={
    isHotspot:1,
    pageNum:1,
    pageSize:10
  }
  if (curFilter.value.areaId) param.areaId = curFilter.value.areaId

  if (curFilter.value.id) {
    const countryId = curFilter.value.id.split(',')
    if (!countryId[1]) param.countryId = curFilter.value.id
  }
  const {data:{dataList}} = await request('website/tourism/project/list',{ query: param })
  recomendList.value = dataList || []
}
onMounted(async () => {
  getFilters()
  
})

useSeoMeta({
  title: `旅游笔记`
})
</script>

<style lang="scss" scoped>
:root {
  --tree-select-item-active-color: red;
  /* 选中项背景颜色 */
  --tree-select-item-active-text-color: red;
  /* 选中项文本颜色 */
  --van-tree-select-item-active-color: red;
}

.scrollbar::-webkit-scrollbar {
  width: 0px;
  height: 0px;
  background-color: #ccc;
}

/* 滚动条滑块样式 */
.scrollbar::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #555;
}

.overflow-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  -webkit-box-orient: vertical;
}
</style>
