<route lang="json">
{
  "style": {
    "navigationBarTitleText": "我的荣誉",
    "navigationStyle": "custom"
  }
}
</route>
<script setup lang="ts">
import NavbarEvo from '@/components/navbar-evo.vue'
import Card from '@/components/card.vue'
import SectionHeading from '@/components/section-heading.vue'
import {
  getBadges,
  getCertificates,
  getHonorStatistics,
  getListCollectionBadge,
} from '../../../core/libs/requests'
import { useRouter } from '../../../core/utils/router'
import arcBottom from '@designer-hub/assets/src/libs/assets/arcBottom'
import { NetImages } from '../../../core/libs/net-images'
import ProgressEvo from '@/components/progress-evo.vue'
import { Certificate } from '@/core/libs/models'
import dayjs from 'dayjs'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import SwiperEvo from '@/components/swiper-evo.vue'

const id = ref()
const isShared = ref(false)
const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const active = ref('badge')
const autoplay = ref<boolean>(false)
const tabs = ref([
  { label: '徽章', value: 'badge' },
  { label: '证书', value: 'certificate' },
])
const { data: statistics, run: setStatistics } = useRequest(() =>
  getHonorStatistics({ userId: id.value }),
)
const { data: badges, run: setBadges } = useRequest(() => getBadges({ userId: id.value }), {
  initialData: {},
})
const { data: collectionBadges, run: setCollectionBadges } = useRequest(
  () => getListCollectionBadge({ userId: id.value }),
  { initialData: [] },
)
const { data: certificates, run: setCertificates } = useRequest(
  () => getCertificates({ userId: id.value }),
  {
    initialData: [],
  },
)
const save = async (filePath: string) => {
  uni.downloadFile({
    url: filePath, // 下载资源的网络地址
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath, // 临时文件路径
          success: () => {
            uni.showToast({ title: '已保存相册', icon: 'none' })
          },
          fail: (err) => {
            uni.showToast({
              title: '保存失败',
              icon: 'none',
            })
          },
        })
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '下载失败',
        icon: 'none',
      })
    },
  })
}

const handleGetCondition = (badge: any) => {
  uni.navigateTo({
    url: `/pages-sub/mine/honors/detail/collection?badgeId=${badge}&id=${id.value}`,
  })
}

const handleGetBadge = (badge: any) => {
  uni.navigateTo({
    url: `/pages-sub/mine/honors/leaderboard/index?id=${badge}`,
  })
}
const currentCertificate = ref<Certificate | undefined>()
const isOwner = computed(() => String(userInfo.value?.userId) === id.value)
onLoad(async (query?: Record<string | 'active' | 'id' | 'isShared', string>) => {
	// console.log('query:::::', query)
  if (Object.keys(query).length !== 0) {
    if (query?.active) {
      active.value = query.active
    }
    if (query?.id) {
      id.value = query.id
    }
    if (query?.isShared) {
      isShared.value = true
    }
  }
  await setStatistics()
  await setBadges()
  await setCertificates()
  await setCollectionBadges()  
})
</script>
<template>
  <div class="flex-grow bg-gradient-to-b from-[#181614] to-[#0f0f0f] flex flex-col gap-4 p-3.5">
    <div class="aspect-[1.63/1] m--3.5 overflow-hidden relative">
      <wd-img width="100%" mode="widthFix" :src="NetImages.HonorsHeader"></wd-img>
      <div class="absolute left-7 bottom-6.5">
        <div
          class="text-white text-3xl font-bold font-['Alimama_ShuHeiTi'] leading-relaxed pr-2.5"
          style="
            background: linear-gradient(92deg, #fff 0.4%, #ffebb2 107.42%);
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
          "
        >
          荣誉主页
        </div>
        <div class="mt-4 flex justify-between">
          <template
            v-for="(it, i) in [
              { label: '获得徽章', value: statistics?.badgeCount, unit: '枚' },
              { label: '获得证书', value: statistics?.certCount, unit: '个' },
            ]"
            :key="i"
          >
            <div class="flex flex-col items-center gap-1.25">
              <div
                class="text-center text-[#f6e8da]/80 text-xs font-normal font-['PingFang_SC'] leading-snug"
              >
                {{ it.label }}
              </div>
              <div class="flex items-end gap-1">
                <div
                  class="text-center text-white text-2xl font-medium font-['D-DIN-PRO'] leading-6"
                >
                  {{ it.value }}
                </div>
                <div
                  class="text-center text-[#f6e8da]/80 text-xs font-normal font-['PingFang_SC'] leading-snug"
                >
                  {{ it.unit }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <NavbarEvo dark fixed transparent></NavbarEvo>
    <div class="flex items-center justify-around">
      <template v-for="(it, i) in tabs" :key="i">
        <div class="flex flex-col items-center gap-1" @click="active = it.value">
          <div
            class="text-center font-normal font-['PingFang_SC']"
            :class="`${it.value === active ? 'text-white text-lg leading-relaxed ' : 'text-white/60 text-base leading-normal'}`"
          >
            {{ it.label }}
          </div>
          <wd-img v-if="it.value === active" width="17" height="5.6" :src="arcBottom"></wd-img>
        </div>
      </template>
    </div>
    <template v-if="active === 'badge'">
      <!-- <view class="h-[145px]" v-if="String(userInfo.userId) === id">	 -->
      <view class="h-[145px]">
        <SwiperEvo :items="collectionBadges" dot-color="#fff">
          <template #default="{ item }">
            <Card custom-class="border border-solid bg-[#25221f]! border-[rgba(255,236,185,0.20)]">
              <div class="grid grid-cols-[90px_1fr] gap-x-4">
                <div
                  class="grid-row-start-1 grid-row-end-4 col-start-1"
                  @click="
                    router.push(
                      `/pages-sub/mine/honors/detail/index?type=badge&id=${id}&data=${JSON.stringify(item)}`,
                    )
                  "
                >
                  <wd-img width="90" height="90" :src="item.badgeYesObtainedImage"></wd-img>
                </div>
                <div class="row-start-1 col-start-2 flex items-center justify-between">
                  <div
                    class="text-center text-[#ffecb9] text-lg font-normal font-['PingFang_SC'] leading-relaxed"
                    @click="
                      router.push(
                        `/pages-sub/mine/honors/detail/index?type=badge&id=${id}&data=${JSON.stringify(item)}`,
                      )
                    "
                  >
                    {{ item.badgeName }}
                  </div>
                  <div
                    class="h-[26px] px-2.5 rounded-[30px] border border-solid border-[#ffecb9] justify-center items-center gap-2.5 inline-flex"
                  >
                    <div
                      class="text-center text-[#ffecb9] text-xs font-normal font-['PingFang_SC'] leading-relaxed"
                      @click="handleGetCondition(item.id)"
                    >
                      获取条件
                    </div>
                  </div>
                </div>
                <div class="row-start-2 col-start-2">
                  <div
                    class="text-start text-white/60 text-xs font-normal font-['PingFang_SC'] leading-relaxed"
                  >
                    {{ item.badgeDescription }}
                  </div>
                </div>
                <div class="row-start-3 col-start-2 flex items-center gap-4">
                  <div class="flex-1">
                    <ProgressEvo
                      :height="5"
                      :model-value="
                        (
                          Number.parseInt(item.userSize as any) /
                          Number.parseInt(item.badgeSize as any)
                        ).toFixed(2) * 100
                      "
                      color="linear-gradient(90deg, #FFDA72 0%, #FFECB9 100%)"
                    ></ProgressEvo>
                  </div>
                  <div>
                    <span class="text-white text-xs font-normal font-['PingFang_SC'] leading-none">
                      {{ item.userSize }}
                    </span>
                    <span
                      class="text-[#a1a1a1] text-xs font-normal font-['PingFang_SC'] leading-none"
                    >
                      /{{ item.badgeSize }}
                    </span>
                  </div>
                </div>
                <div class="row-start-4 col-start-1 flex items-center justify-center">
                  <div
                    class="w-[59px] h-[21px] px-2.5 bg-[#524c3b] rounded-[30px] shadow shadow-inner justify-center items-center gap-0.5 inline-flex"
                  >
                    <div
                      class="text-center text-[#ffecb9] text-[10px] font-normal font-['PingFang_SC'] leading-relaxed"
                      @click="handleGetBadge(item.id)"
                    >
                      获取榜
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </template>
        </SwiperEvo>
      </view>

      <template v-for="([key, it], index) in Object.entries(badges)" :key="index">
        <Card
          v-if="!((!isOwner || isShared) && ['积分徽章', '积分徽章'].includes(key))"
          custom-class="bg-[#171615]! text-white border border-solid border-[rgba(255,236,185,0.20)]"
        >
          <div class="flex items-center gap-2 py-4">
            <div class="w-1.5 h-1.5 bg-[#ffecb9] rounded-full"></div>
            <SectionHeading :title="key.toString()" dark></SectionHeading>
          </div>
          <div class="grid grid-cols-3 gap-y-6">
            <template v-for="(item, i) in it" :key="i">
              <div
                class="w-full px-4 box-border"
                @click="
                  router.push(
                    `/pages-sub/mine/honors/detail/index?type=badge&id=${id}&data=${JSON.stringify(item)}`,
                  )
                "
              >
                <wd-img
                  width="100%"
                  mode="widthFix"
                  :src="item.quantity ? item.badgeYesObtainedImage : item.badgeNotObtainedImage"
                ></wd-img>
                <div
                  class="text-center text-white text-xs font-normal font-['PingFang_SC'] leading-relaxed"
                >
                  {{ item.badgeName }}
                </div>
              </div>
            </template>
          </div>
        </Card>
      </template>
    </template>
    <template v-if="active === 'certificate'">
      <div>
        <div class="grid grid-cols-2 gap-2.5">
          <template v-for="(it, i) in certificates" :key="i">
            <div class="aspect-[1.35/1]" @click="currentCertificate = it">
              <wd-img
                width="100%"
                height="100%"
                :src="it.certificateImage"
                mode="aspectFill"
                custom-class="vertical-bottom"
              ></wd-img>
            </div>
          </template>
        </div>
      </div>
    </template>
    <wd-overlay :show="currentCertificate !== undefined" @click="currentCertificate = undefined">
      <div class="h-full flex flex-col items-center justify-around">
        <div class="flex flex-col">
          <wd-img
            width="85vw"
            height="94vw"
            :src="currentCertificate?.certificateImage"
            mode="aspectFit"
          ></wd-img>
          <div
            class="text-center text-white text-xl font-normal font-['PingFang_SC'] uppercase mt-7"
          >
            {{ currentCertificate?.certificateName }}
          </div>
          <div class="flex center gap-3">
            <div class="w-3.5 h-[1.5px] bg-white"></div>
            <div class="text-center text-white text-sm font-normal font-['PingFang_SC'] uppercase">
              <!--          2024年10月2日获得-->
              {{ dayjs(currentCertificate?.createTime).format('YYYY年MM月DD日') }}获得
            </div>
            <div class="w-3.5 h-[1.5px] bg-white"></div>
          </div>
        </div>
        <wd-button custom-class="bg-[#0CBE7D]!" @click="save(currentCertificate?.certificateImage)">
          保存到本地
        </wd-button>
      </div>
    </wd-overlay>
  </div>
</template>
