<template>
  <div class="cate-list">
    <div class="cate-tag">
      <div class="tag-kinds">类型：</div>
      <div v-for="item in typeArr"
           :key="item.id"
           class="tags"
           :class="{ active: typeIndex === item.id }"
           @click="selectType('type', item.id)">
        {{ item.name }}
      </div>
    </div>
    <div class="cate-tag">
      <div class="tag-kinds">标签：</div>
      <div v-for="item in tagArr"
           :key="item.id"
           class="tags"
           :class="{ active: tag_idIndex === item.id }"
           @click="selectType('tag_id', item.id)">
        {{ item.name }}
      </div>
    </div>
    <div class="drop-tag">
      <van-dropdown-menu ref="menuRef">
        <van-dropdown-item title="类型" >
          <van-cell
            v-for="item in typeArr"
            :key="item.id"
            :title="item.name"
            :class="{ active: typeIndex === item.id }"
            @click="selectType('type', item.id)"/>
        </van-dropdown-item>
        <van-dropdown-item title="标签" ref="tag">
          <van-cell
            v-for="item in tagArr"
            :key="item.id"
            :title="item.name"
            :class="{ active: tag_idIndex === item.id }"
            @click="selectType('tag_id', item.id)"/>
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>
    <el-divider class="divide" />
    <ul v-if="gameLis.length">
      <li class="hot-item" v-for="(item,index) in gameLis" :key="index">
        <img class="game-logo" :src="prefix + item.logopic"  :onerror="logoErrorFun" alt=""/>
        <van-button type="primary" class="down-btn" :disabled="item.download_url === ''" size="small" round  @click="downGame(item.download_url, item.download_url === '')">下载</van-button>
        <div class="detail">
          <div class="top">
            <span class="game_title ellip">{{ item.screen_name }}</span>
            <el-tag size="small" type="success">{{ (item.game_score / 10) > 5 ? '5.0' : (item.game_score /
              10).toFixed(1)
            }}</el-tag>
          </div>
          <div class="desc ellip">{{ item.sketch || '暂无简介' }}</div>
          <el-tag
            size="small"
            class="game_tag"
            type="warning"
            round
            v-for="(tag, tIndex) in item.tags"
            :key="tIndex"
          >
            {{ tagArr.findIndex((i:any)=>i.id === tag)>=0 ? tagArr.find((i:any)=>i.id === tag).name :''  }}
          </el-tag>
        </div>
        <img  :src="prefix + item.screenshot" class="game-poster" :onerror="posterErrorFun" alt=""/>
        <div class="action" @click="downGame(item.download_url, item.download_url === '')" :style="item.download_url === ''? 'cursor:not-allowed;':'cursor: pointer;'">
          <img :src="img('download.png')" alt=""/>
          <div class="size">{{ bytesChange(item.size) }}</div>
        </div>
      </li>
    </ul>
    <el-empty v-else :image-size="200" />

    <div class="more-action">
      <el-button type="primary" v-if="params.page*params.pagesize < total" @click="loadMore">更多</el-button>
      <el-divider v-else>没有更多了</el-divider>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { getGameType, getGameTag, getGameList } from '@/api/index'
import Message from '@/utils/Message'
import { bytesChange } from '@/utils/bytesFormatter'
import type { DropdownMenuInstance } from 'vant'
import { useRoute } from 'vue-router'

const route = useRoute()
const img:any = inject('img')
const typeIndex = ref<number>(0)
const tag_idIndex = ref<number>(0)
const gameLis: any = ref([])
const typeArr: any = ref([])
const tagArr: any = ref([])
const prefix = ref<string>('')
const isLoading = ref<boolean>(true)
const total = ref<number>(0)
interface Params {
    type: number,
    tag_id: number,
    page: number,
    pagesize: number
}
const params = reactive<Params>({
  type: 0,
  tag_id: 0,
  page: 1,
  pagesize: 15
})

onMounted(async() => {
  await getGameType().then(res => {
    // console.log('类型', res);
    typeArr.value = res.data.data
    typeArr.value.unshift({ id: 0, name: '全部' })
  })
  await getGameTag().then(res => {
    // console.log('标签', res);
    tagArr.value = res.data.data
    tagArr.value.unshift({ id: 0, name: '全部' })
  })
  if (route.query.tag_id) {
    const id = parseInt(route.query.tag_id as string)
    selectType('tag_id', id)
  } else {
    getGameLists(params)
  }
})

// 初始化列表数据
const getGameLists = async(params:any) => {
  // console.log('参数', params);

  await getGameList(params).then(res => {
    // console.log('数据', res);
    if (res.data.code === 200 && res.data.data) {
      gameLis.value = gameLis.value.concat(res.data.data.lists)
      total.value = res.data.data.total
      prefix.value = res.data.data.prefix
      isLoading.value = false
    }
  }).catch(err => {
    Message.error(err.data.msg)
  })
}
const menuRef = ref<DropdownMenuInstance>()
// 点击类型、标签、排序
const selectType = (type: 'type' | 'tag_id', index: any) => {
  console.log(index)

  gameLis.value = []
  params.page = 1

  if (type === 'type') {
    typeIndex.value = index
    params.type = index
  }
  if (type === 'tag_id') {
    tag_idIndex.value = index
    params.tag_id = index
  }
  if (menuRef.value) {
    menuRef.value.close()
  }
  // 如果都为 全部  则发起请求 页面显示15条数据
  if (params.type === 0 && params.tag_id === 0) {
    params.pagesize = 15
    getGameLists(params)
  } else {
    allData()
  }
}
// 全部数据
const allData = async() => {
  params.pagesize = total.value
  // console.log('params', params);
  await getGameList(params).then(resp => {
    // console.log('resp===>', resp);
    if (resp.data.code === 200 && resp.data.data) {
      prefix.value = resp.data.data.prefix
      gameLis.value = resp.data.data.lists.filter((item:any) => {
        // 如果标签为全部  类型不为全部 返回匹配的类型数据
        if (params.tag_id === 0) {
          return item.type === params.type
        } else if (params.type === 0) {
          // 如果类型为全部  标签不为全部 返回匹配的标签数据
          return item.tags.includes(params.tag_id)
        } else return item.type === params.type && item.tags.includes(params.tag_id) // 否则返回匹配的标签和类型数据
      })
    }
  }).catch(err => {
    Message.error(err.data.msg)
  })
}
const downGame = (url: string, disabled:boolean) => {
  if (disabled) return
  // 下载游戏
  window.open(url)
  // window.location.href = url;
}
// 加载更多
const loadMore = () => {
  params.page += 1
  getGameLists(params)
}
const logoErrorFun = (event:any) => {
  var imgDom = event.srcElement
  imgDom.src = img('default.png')
  imgDom.onerror = null
}
const posterErrorFun = (event:any) => {
  var imgDom = event.srcElement
  imgDom.src = img('defaultPoster.png')
  imgDom.onerror = null
}
</script>

<style scoped lang="scss">
.cate-list{
  background-color: #fff;
  padding: 1.1rem 1rem;
  box-sizing: border-box;
  width: 100%;
  >div{
    font-size: .8rem;
  }
  .tag-kinds{
    margin-top: 1rem;
  }
  .cate-tag{
    display: flex;
    .tags{
      margin: 1rem;
      cursor: pointer;
    }
  }
  .drop-tag{
    display: none;
  }
  .hot-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    margin-bottom: .5rem;
    border-bottom: .5px solid #ddd;
    height: 10rem;
    .down-btn{
      display: none;
    }
    .game-logo{
      width: 6rem;
      height: 6rem;
      border-radius: .2rem;
      background-color: #f7f7f7;
      display: block;
      flex-grow: 0;
      flex-shrink: 0;
    }
    .game-poster{
      width: 12.1rem;
      height: 7rem;
      display: block;
      flex-grow: 0;
      flex-shrink: 0;
    }
    .detail{
      width: 30rem;
      .top{
        display: flex;
        align-items: center;
        .game_title{
          margin-right: .3rem;
          font-size: 1rem;
        }
      }
      .desc{
        font-size: .8rem;
        margin: .5rem 0;
      }
    }
    &:hover .action{
        transform: translateX(-5rem);
    }
    .action{
      position: absolute;
      right: -6rem;
      // top: 50%;
      width: 5rem;
      height: 7rem;
      background-color: rgba($color: #99ccff, $alpha: .5);
      // transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      transition: all 200ms ease;
      img{
        width: 2.5rem;
      }
      .size{
        font-size: .5rem;
        margin-top: .5rem;
        color: #fff;
      }

    }
  }
  .more-action{
    text-align: center;
  }
}
// .header_list {
//     .top_type {
//         margin: 15px 0 10px;
//         background-color: #fff;
//         padding: 20px 50px 20px 20px;
//         box-sizing: border-box;

//         .left_title {
//             width: 50px;
//             font-size: 14px;
//             color: #666;
//         }

//         .right_type {

//             // background-color: #ed8c0f;
//             .cont {
//                 margin-right: 20px;
//                 padding: 3px 5px;
//                 cursor: pointer;

//                 &:hover {
//                     color: #ed8c0f;
//                 }
//             }
//         }

//         .type {
//             margin-bottom: 20px;
//         }
//     }

//     .el-button {
//         margin: 5px 20px 15px 0;
//         padding: 0 20px;
//         border: 0;
//         color: #999;
//     }
// }

.active {
    color: #ed8c0f
}
</style>
