<template>
  <div class="mine">
    <ul v-if="user.isLogin ">
      <li class="hot-item" v-for="(item,index) in mineGame" :key="index">
        <img :src="prefix + item.logopic" class="game-logo" :onerror="logoErrorFun" alt=""/>
        <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-button type="primary" :disabled="item.download_url === '' ? true : false" @click="downGame(item.download_url)"  class="pcbt" :icon="Download">
            {{ bytesChange(item.size) }}
          </el-button>
          <el-button type="primary" @click="showGifts(item)" class="pcbt">查看礼包</el-button>
        </div>
        <div class="right">
          <van-button size="small" type="primary" round  @click="showGifts2(item)">查看礼包</van-button>
          <van-button size="small" type="primary" :disabled="item.download_url === '' ? true : false"  round  @click="downGame(item.download_url)">下载</van-button>
        </div>
        <img :src="prefix + item.screenshot" class="game-poster" :onerror="posterErrorFun" alt=""/>
      </li>
    </ul>
    <van-empty v-if="mineGame.length===0 && user.isLogin" description="暂无数据" />
    <div v-if="!user.isLogin" :style="{ height: viewWidth + 'px' }" class="df fdc aic jcc">
      <el-empty description="您还未登录！登录后可查询数据！">
        <el-button type="primary" @click="goLogin">去登录 &gt;&gt;</el-button>
      </el-empty>
    </div>
    <div class="more-action">
      <el-button v-if="params.page*params.pagesize < total" type="primary" @click="loadMore">更多</el-button>
      <el-divider v-else>没有更多了</el-divider>
    </div>
  </div>

  <el-dialog  v-model="dialogVisible" title="游戏礼包" width="80%">
    <el-collapse v-if="giftData.length" v-model="activeName" accordion>
      <div v-for="(item, index) in giftData" :key="index" style="display: flex;justify-content: space-between; align-items: center;">
        <el-collapse-item :title="item.gift_name" :name="item.id" style="width: 70%;">
          <el-form label-width="120px">
            <el-form-item label="礼包内容：">{{ item.gift_content }}</el-form-item>
            <el-form-item label="使用方法：">{{ item.usage }}</el-form-item>
            <el-form-item label="有效期：">{{ item.start_at+'-'+item.end_at }}</el-form-item>
            <el-form-item v-if="item.user_get_at !== ''" style="user-select:auto;" label="礼包码：">
              {{ item.code }}
              <el-button
                icon="DocumentCopy"
                size="small"
                @click="doCopay(item.code)"
                style="margin-left: .5rem;"
              />
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <div style="width: 20%;">
          <el-button :disabled="item.user_get_at !== ''" type="primary" style="color: #fff;" @click="receiveGift(item.id)">领取礼包</el-button>
        </div>
      </div>

    </el-collapse>
    <el-empty v-else description="暂无礼包" />

  </el-dialog>
  <van-dialog v-model:show="dialogVisible2" title="查看礼包" confirm-button-text="关闭">
    <van-collapse v-if="giftData.length" v-model="activeNames">
      <van-collapse-item v-for="(item, index) in giftData" :key="index" :title="item.gift_name" :name="item.id">
        <template #value>
          <van-button size="small" :disabled="item.user_get_at !== ''" round type="primary" @click.stop="receiveGift(item.id)">领取礼包</van-button>
        </template>
        <van-cell-group>
          <van-cell value-class="value-length" center size="large" title="礼包内容：" :value="item.gift_content">
            <template #value>
              <div style="text-align: left;">
                {{ item.gift_content }}
              </div>
            </template>
          </van-cell>
          <van-cell value-class="value-length" center size="large" title="使用方法：" :value="item.usage">
            <template #value>
              <div style="text-align: left;">
                {{ item.usage }}
              </div>
            </template>
          </van-cell>
          <van-cell value-class="value-length" center size="large" title="有效期：" :value="item.start_at+'-'+item.end_at">
            <template #value>
              <div style="text-align: left;">
                {{ item.start_at+'-'+item.end_at }}
              </div>
            </template>
          </van-cell>
          <van-cell v-if="item.user_get_at !== ''" value-class="value-length" style="user-select:auto;" center size="large" title="礼包码：" :value="item.code"/>
        </van-cell-group>
      </van-collapse-item>

    </van-collapse>
    <van-empty v-else description="暂无礼包" />
  </van-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, inject, computed } from 'vue'
import { getMineGame, getGiftHttp, receiveGiftHttp } from '@/api/index'
import { useStore } from '@/store/index'
import { useRoute, useRouter } from 'vue-router'
import Message from '@/utils/Message'
import local from '@/utils/local'
import { bytesChange } from '@/utils/bytesFormatter'
import { Download } from '@element-plus/icons-vue'
import useClipboard from 'vue-clipboard3'

const { user } = useStore()
const router = useRouter()
const img:any = inject('img')
const route = useRoute()
// const header = useStore('header')
const dialogVisible = ref<boolean>(false)
const dialogVisible2 = ref<boolean>(false)
const mineGame: any = ref([])
const prefix = ref<string>('')
const total = ref<number>(0)
const isLoading = ref<boolean>(true)
const viewWidth = ref<number>(document.documentElement.clientHeight - 80)
const userAccount = ref<string | null>(sessionStorage.getItem('account'))
const token = ref<string | null>(sessionStorage.getItem('token'))
const activeName = ref('1')
interface Params {
    page: number,
    pagesize: number,
    account: string | null
}
const params = reactive<Params>({
  page: 1,
  pagesize: 10,
  account: userAccount.value
})
onMounted(() => {
  // 进入页面刷新一次
  if (token.value) {
    if (route.query.account || userAccount.value) {
      getMyGame(params)
    }
    user.getUserProfile()
  }
})

const getMyGame = async(params:Params) => {
  // console.log('params', params);
  await getMineGame(params).then(res => {
    // console.log('res========>', res);
    if (res.data.code === 200 && res.data.data) {
      mineGame.value = mineGame.value.concat(res.data.data.lists)
      prefix.value = res.data.data.prefix
      total.value = res.data.data.total
      isLoading.value = false
    }
  }).catch(err => {
    Message.error(err.data.msg)
  })
}
const { toClipboard } = useClipboard()
const doCopay = async(code:any) => {
  try {
    await toClipboard(code)
    Message.success('已复制到剪贴板')
  } catch (e) {
    Message.error('复制失败')
  }
}
// 加载更多
const loadMore = () => {
  params.page += 1
  getMyGame(params)
}
const platform = computed(() => {
  var u = navigator.userAgent
  return {
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1 // 是否微信
  }
})
const goLogin = () => {
  if (platform.value.mobile) {
    router.push({ path: '/login' })
  } else {
    user.loginFormVisible = true
  }
  local.remove('headerPath')
}
const giftData = ref<any[]>([])
const gameId = ref<number>(0)
const showGifts = async(row:any) => {
//    console.log(row);
  gameId.value = row.game_id
  await getGiftHttp({ game_id: row.game_id }).then((res) => {
    // console.log(res.data.data)
    giftData.value = res.data.data || []
    dialogVisible.value = true
  }).catch((error) => {
    console.log(error)
  })
}
const showGifts2 = async(row:any) => {
//    console.log(row);
  gameId.value = row.game_id
  await getGiftHttp({ game_id: row.game_id }).then((res) => {
    // console.log(res.data.data)
    giftData.value = res.data.data || []
    dialogVisible2.value = true
  }).catch((error) => {
    console.log(error)
  })
}
const receiveGift = async(id:number) => {
  await receiveGiftHttp({ id }).then(async(res) => {
    Message.success(res.data.msg)
    await getGiftHttp({ game_id: gameId.value }).then((res) => {
    // console.log(res.data.data)
      giftData.value = res.data.data || []
      // if (platform.value.mobile) {
      //   dialogVisible2.value = true
      // }
    }).catch((error) => {
      console.log(error)
    })
    // dialogVisible.value = false
  }).catch((error) => {
    console.log(error)
    Message.error(error.data.msg)
  })
}
const posterErrorFun = (event:any) => {
  var imgDom = event.srcElement
  imgDom.src = img('defaultPoster.png')
  imgDom.onerror = null
}
const logoErrorFun = (event:any) => {
  var imgDom = event.srcElement
  imgDom.src = img('default.png')
  imgDom.onerror = null
}
const downGame = (url: string) => {
  // 下载游戏
  window.open(url)
  // window.location.href = url;
}
const activeNames = ref(['1'])

</script>

<style scoped lang="scss">
.mine{
  width: 100%;
  background-color: #fff;
  padding: 1rem;
  box-sizing: border-box;
  .hot-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 8rem;
    overflow: hidden;
    margin-bottom: .7rem;
    border-bottom: .01rem solid #ddd;
    box-sizing: border-box;
    padding: .8rem 0;
    .game-logo{
      width: 6.5rem;
      height: 6.5rem;
      border-radius: .5rem;
      overflow: hidden;
      flex-shrink: 0;
      margin-right: 2rem;
    }
    .detail{
      flex: 1;
      .top{
        display: flex;
        align-items: center;
        .game_title{
          display: inline-block;
          margin-right: 0.5rem;
        }
      }
      .desc{
          font-size: 0.7rem;
          color: #666;
          line-height: 1.3rem;
          margin: 0.5rem 0;
        }
    }
    .right{
      height: 100%;
      // display: flex;
      display: none;
      align-items: center;
      justify-content: space-around;
      flex-direction: column;
    }
    .game-poster{
      width: 11rem;
      height: 6.5rem;
    }
  }
}
.more-action {
    margin: 1rem auto;
    text-align: center;
}
</style>
