<template>
  <div
    class="shop-view"
  >
    <menu class="tab-bar">
      <button
        :class="{
          active: tabIdx === 0
        }"
        @click="tabIdx = 0"
      >
        爱心兑换
      </button>
      <button
        :class="{
          active: tabIdx === 2
        }"
        @click="tabIdx = 2"
      >
        排行榜
      </button>
      <button
        :class="{
          active: tabIdx === 1
        }"
        @click="tabIdx = 1"
      >
        爱心记录
      </button>
    </menu>

    <template v-if="tabIdx === 0">
      <button
        class="prev-page"
        :class="{
          hide: pageNumber === 0
        }"
        @click="onClickPrevPage"
      />
      <ul
        v-loading.fullscreen.lock="pageLoading"
        class="prize-list"
      >
        <li
          v-for="prizeItem in prizeList"
          :key="prizeItem.id"
          class="prize"
          :class="{
            disabled: prizeItem.stock === 0,
          }"
          @click="onClickPrizeItem(prizeItem)"
        >
          <img
            class="thumb"
            :src="`${$env.VUE_APP_DEPLOY_ORIGIN}${prizeItem.thumb}`"
            alt=""
            draggable="false"
          >
          <div class="prize-inner">
            <div class="title">
              {{ prizeItem.name }}
            </div>
            <div
              class="remaining"
            >
              <span v-if="prizeItem.id !== 1">剩余：{{ prizeItem.stock }}</span>
            </div>
            <div class="price">
              <span class="number">{{ prizeItem.score }}</span>
              <span class="unit">爱心</span>
            </div>
            <img
              v-show="prizeItem.stock > 0 || (prizeItem.id === 1 && !isRedeemed)"
              class="icon-enabled"
              src="@/assets/images/icon-gift.png"
              alt=""
              draggable="false"
            >
            <img
              v-if="prizeItem.id === 1 && isRedeemed"
              class="icon-enabled redeemed"
              src="@/assets/images/icon_complete@2x-min.png"
              alt=""
              draggable="false"
            >
            <!-- <img
              v-show="prizeItem.isEnabled && prizeItem.stock === 0"
              class="icon-no-stock"
              src="@/assets/images/no-stock.png"
              alt=""
              draggable="false"
            > -->
          </div>
        </li>

        <p
          class="product-tip"
        >
          更多礼品敬请期待
        </p>
      </ul>
      <button
        class="next-page"
        :class="{
          hide: !haveNextPage
        }"
        @click="onClickNextPage"
      />
    </template>

    <div
      v-show="tabIdx === 1"
      class="redeem-record-content"
    >
      <p
        v-show="redeemRecordContact"
        class="tip"
      >
        如有疑问，请咨询 {{ redeemRecordContact }}
      </p>
      <div class="table">
        <div class="row-header">
          <div>时间</div>
          <div>类型</div>
          <div>爱心</div>
          <div>说明</div>
        </div>
        <div class="splitter" />
        <div class="table-content">
          <div
            v-for="item in redeemRecord"
            :key="item.id"
            class="row-data"
          >
            <div>
              {{ item.createTime }}
            </div>
            <div>
              {{ item.type }}
            </div>
            <div>
              {{ item.score > 0 ? '+' : item.score < 0 ? '' : '' }}{{ item.score }}
            </div>
            <div>
              {{ item.description || `（空）` }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      v-show="tabIdx === 2"
      class="ranking-content"
    >
      <div
        v-loading="rankingLoading"
        class="table"
      >
        <div class="row-header">
          <div>排名</div>
          <div>用户名</div>
          <div>爱心</div>
        </div>
        <div class="splitter" />
        <div class="table-content">
          <div
            v-for="(item, idx) in rankingList"
            :key="item.id"
            :class="['row-data', {
              'is-me': store.state.userInfo.userId === item.id
            }]"
          >
            <div :class="['ranking-sort', idx === 0 && 'is-first']">
              <span>{{ idx + 1 }}</span>
            </div>
            <div class="ranking-name">
              <img
                class="ranking-name__avatar"
                fit="cover"
                src="@/assets/images/default-avatar-min.png"
              >
              <span>{{ item.nickName.slice(0, 1) }}***</span>
            </div>
            <div>
              {{ item.pcs }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="coin-number">
      <img
        class="icon"
        src="@/assets/images/icon_money.png"
        alt=""
        draggable="false"
      >
      <span class="value">{{ myScore }}</span>
    </div>

    <PrizeRedeem
      v-if="isShowRedeem"
      :prize-data="redeemPrizeData"
      :score="myScore"
      @open-cert="openCertImg"
      @close="redeemPrizeData = {}, isShowRedeem = false"
      @submit-over="handlePrizeSubmitOver"
    />

    <div
      v-show="isShowCertImg"
      class="cert-view"
    >
      <img
        class="cert-img"
        :src="certImgUrl"
        alt=""
        draggable="false"
      >
      <a
        v-show="$isTablet"
        class="btn-download"
        :href="certImgUrl"
        download="锡善云城-证书"
      >
        下载证书
      </a>
      <button
        class="close"
        @click="isShowCertImg = false"
      />
    </div>
  </div>

  <div
    ref="certCanvas"
    class="cert-canvas"
  >
    <p>{{ certInfo.certName }}</p>
    <p>{{ certInfo.createTime }}</p>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, inject, nextTick } from "vue"
import { useStore } from "vuex"
import PrizeRedeem from '@/components/PrizeRedeem.vue'
import {
  getMyScore,
  getShopContact,
  getPrizeList,
  getRedeemRecord,
  getRankingListApi,
  checkRedeemApi,
  getRedeemApi,
  uploadFile,
} from '@/api.js'
import html2canvas from 'html2canvas'
import { formatDate } from '@dage/utils'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const pageLoading = ref(false)
const $env = inject('$env')
const $isTablet = inject('$isTablet')

const {
  windowSizeInCssForRef,
  windowSizeWhenDesignForRef,
} = useSizeAdapt(1920, 972)

const myScore = ref(undefined)
getMyScore().then((res) => {
  myScore.value = res
})

const tabIdx = ref(0)

const redeemRecordContact = ref('')
getShopContact().then((res) => {
  if (res.display === 0) {
    ElMessage({
      message: '商城暂未开启，敬请期待',
      type: 'warning',
    })
    router.replace({
      name: 'HomeView'
    })
    return
  }
  redeemRecordContact.value = res.rtf
})

const handlePrizeSubmitOver = async() => {
  try {
    pageLoading.value = true
    await checkRedeem()
    const scoreRes = await getMyScore()
    myScore.value = scoreRes
    const res = await getPrizeList(pageNumber.value, 8)
    total.value = res.total
    prizeList.value = res.records
  } finally {
    pageLoading.value = false
  }
  isShowRedeem.value = false
}

/**
 * 一页页的商品
 */
const prizeList = ref([])
const pageNumber = ref(0)
const total = ref(0)
function onClickPrevPage() {
  if (pageNumber.value > 0) {
    pageNumber.value--
  }
}
function onClickNextPage() {
  if (haveNextPage.value) {
    pageNumber.value++
  }
}
const haveNextPage = computed(() => {
  return total.value > ((pageNumber.value + 1) * 8)
})
watch(pageNumber, (v) => {
  getPrizeList(v + 1, 8).then((res) => {
    total.value = res.total
    prizeList.value = res.records
  })
}, {
  immediate: true,
})

const isShowRedeem = ref(false)
const redeemPrizeData = ref({})
function onClickPrizeItem(prizeItem) {
  if (prizeItem.id === 1 && isRedeemed.value) {
    openCertImg()
    return
  }

  if (prizeItem.score > myScore.value) {
    ElMessage.warning('积分不足，无法兑换')
    return
  }

  if (prizeItem.stock < 1 && prizeItem.id !== 1) {
    ElMessage.warning('库存不足，无法兑换')
    return
  }

  redeemPrizeData.value = prizeItem
  isShowRedeem.value = true
}

const redeemRecord = ref([])
getRedeemRecord().then((res) => {
  redeemRecord.value = res
})

const rankingList = ref([])
const rankingLoading = ref(false)
const getRankingList = async() => {
  try {
    rankingLoading.value = true
    const data = await getRankingListApi()
    rankingList.value = data
  } finally {
    rankingLoading.value = false
  }
}

watch(tabIdx, val => {
  if (val === 2) {
    getRankingList()
  }
})

onMounted(() => {
  checkRedeem()
})

const isRedeemed = ref(false)
const checkRedeem = async() => {
  const data = await checkRedeemApi()
  isRedeemed.value = data
}

const certCanvas = ref()
// const $isSafari = inject('$isSafari')
const isShowCertImg = ref(false)
const certImgUrl = ref('')
const openCertImg = async(certName) => {
  try {
    pageLoading.value = true
    if (isRedeemed.value) {
      await getRedeem()
    } else {
      certInfo.value = {
        certName,
        createTime: formatDate(new Date(), "YYYY年MM月DD日")
      }
    }
    await nextTick(async() => {
      const canvas = await html2canvas(certCanvas.value, {
        width: certCanvas.value.offsetWidth,
        scale: 1,
        allowTaint: true,
        useCORS: true,
      })
      canvas.toBlob(
        async (blob) => {
          if (blob) {
            const uploadRes = await uploadFile(blob)
            // certImgUrl.value = URL.createObjectURL(blob)
            certImgUrl.value = `${process.env.VUE_APP_DEPLOY_ORIGIN}${uploadRes}`
            isShowCertImg.value = true
          }
        },
        'image/jpeg',
        0.95,
      )
      // const dataUrl = canvas.toDataURL('image/jpeg')
      // certImgUrl.value = dataUrl
      // isShowCertImg.value = true
      // uploadFile(dataUrl)
    })
  } finally {
    pageLoading.value = false
  }
}

const certInfo = ref({
  certName: '',
  createTime: ''
})
const getRedeem = async() => {
  const data = await getRedeemApi()
  data.createTime = formatDate(data.createTime, "YYYY年MM月DD日")
  certInfo.value = data
}
</script>

<style lang="less" scoped>
.shop-view{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  >menu{
    flex: 0 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: calc(300 / 1920 * 100%);
    >button{
      margin: 28px 0;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 28px;
      color: #424A4A;
      line-height: 33px;
      position: relative;
      &.active{
        font-weight: bold;
        color: #589498;
        &::after{
          content: '';
          position: absolute;
          left: 50%;
          top: 100%;
          transform: translate(-50%);
          width: 90px;
          height: 9px;
          background: #FFE794;
          box-shadow: 0px 1px 4px 0px rgba(193,165,64,0.5);
          border-radius: 4px;
        }
      }
    }
  }
  >button.prev-page{
    width: 58px;
    height: 58px;
    background-image: url(@/assets/images/icon_arrow-left-round.png);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    margin-right: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    &.hide {
      pointer-events: none;
      opacity: 0;
    }
  }
  ul.prize-list{
    position: relative;
    flex: 0 0 auto;
    width: calc(1400 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    height: calc((393 * 2 + 25) / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    .product-tip {
      position: absolute;
      left: 50%;
      bottom: -20px;
      transform: translateX(-50%);
      color: #666;
    }
    li.prize{
      display: inline-block;
      width: calc(322 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      height: calc(393 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      background: linear-gradient( 180deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0.8) 100%);
      border-radius: calc(7 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      padding: calc(7 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef')) calc(12 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      box-shadow: 0px 1px 11px 0px rgba(0,0,0,0.1);
      position: relative;
      margin-right: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      margin-bottom: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      cursor: pointer;
      >img.thumb{
        width: calc(307 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        height: calc(246 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        object-fit: cover;
        border-radius: calc(4 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      }
      .prize-inner {
        padding: 0 calc(22 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      }
      .title{
        margin-top: calc(13 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-size: calc(28 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-family: Source Han Sans SC, Source Han Sans SC;
        color: #424A4A;
        line-height: calc(33 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-weight: bold;
        overflow: hidden;
        white-space: pre;
        text-overflow: ellipsis;
      }
      .remaining{
        min-height: calc(20 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        margin-top: calc(5 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-size: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-family: Source Han Sans SC, Source Han Sans SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.5);
        line-height: calc(19 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        overflow: hidden;
        white-space: pre;
        text-overflow: ellipsis;
      }
      .price{
        margin-top: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        >.number{
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: bold;
          font-size: calc(28 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          color: #589498;
          line-height: calc(33 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        }
        >.unit{
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          color: #424A4A;
          line-height: calc(19 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          margin-left: 0.5em;
        }
      }
      img.icon-enabled{
        position: absolute;
        right: calc(29 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        bottom: calc(20 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        width: calc(57 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        height: calc(57 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));

        &.redeemed {
          width: calc(80 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          height: calc(80 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        }
      }
    }
    >article.prize-item.disabled{
      pointer-events: none;
    }
  }
  >button.next-page{
    width: 58px;
    height: 58px;
    background-image: url(@/assets/images/icon_arrow-right-round.png);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    &.hide {
      pointer-events: none;
      opacity: 0;
    }
  }
  .ranking-sort {
    position: relative;
    font-family: 'Alibaba PuHuiTi-Bold' !important;

    &.is-first {
      color: #70581A !important;

      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 36px;
        height: 36px;
        background: url('@/assets/images/icon_winner@2x-min.png') no-repeat center / contain;
        transform: translate(-50%, -50%);
      }
    }
    span {
      position: relative;
      z-index: 1;
    }
  }
  .ranking-name {
    display: flex !important;
    align-items: center;
    justify-content: center;
    gap: 17px;

    &__avatar {
      width: 36px;
      height: 36px;
      border: 2px solid white;
      border-radius: 50%;
    }
  }
  .ranking-content{
    flex: 1 0 1px;
    height: 100%;
    margin: 25px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .table{
      margin-top: 14px;
      flex: 1 0 1px;
      width: 100%;
      margin-bottom: 43px;
      background: linear-gradient( 180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0) 100%);
      box-shadow: 15px 15px 38px 0px rgba(255,255,255,0.5);
      border-radius: 8px 8px 8px 8px;
      display: flex;
      flex-direction: column;
      >.row-header{
        flex: 0 0 auto;
        height: 72px;
        display: flex;
        align-items: center;
        margin-right: 16px;
        >div{
          display: inline-block;
          width: 33.3333%;
          text-align: center;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: bold;
          font-size: 20px;
          color: #424A4A;
          line-height: 23px;
        }
      }
      .table-content{
        flex: 1 0 1px;
        overflow: auto;
        margin-right: 10px;
        >.row-data{
          height: 68px;
          display: flex;
          align-items: center;
          &.is-me {
            background: linear-gradient( 90deg, rgba(88,148,152,0.1) 0%, #589498 50%, rgba(88,148,152,0.1) 100%);
          }
          >div{
            display: inline-block;
            width: 33.3333%;
            text-align: center;
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 400;
            font-size: 20px;
            color: #424A4A;
            line-height: 23px;
            opacity: 0.8;
          }
        }
      }
    }
  }
  >.redeem-record-content{
    flex: 1 0 1px;
    height: 100%;
    margin: 25px;
    display: flex;
    flex-direction: column;
    align-items: center;
    >p.tip{
      margin-top: 23px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 16px;
      color: #589498;
      line-height: 19px;
    }
    >.table{
      margin-top: 14px;
      flex: 1 0 1px;
      width: 100%;
      margin-bottom: 43px;
      background: linear-gradient( 180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0) 100%);
      box-shadow: 15px 15px 38px 0px rgba(255,255,255,0.5);
      border-radius: 8px 8px 8px 8px;
      display: flex;
      flex-direction: column;
      >.row-header{
        flex: 0 0 auto;
        height: 72px;
        display: flex;
        align-items: center;
        margin-right: 16px;
        >div{
          display: inline-block;
          width: 25%;
          text-align: center;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: bold;
          font-size: 20px;
          color: #424A4A;
          line-height: 23px;
        }
      }
      >.splitter{
        width: calc(100% - 30px * 2);
        height: 1px;
        background-color: #B5C2B9;
        margin-left: auto;
        margin-right: auto;
      }
      >.table-content{
        flex: 1 0 1px;
        overflow: auto;
        margin-right: 10px;
        >.row-data{
          height: 68px;
          display: flex;
          align-items: center;
          >div{
            display: inline-block;
            width: 25%;
            text-align: center;
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 400;
            font-size: 20px;
            color: #424A4A;
            line-height: 23px;
            opacity: 0.8;
          }
        }
      }
    }
  }
  >.coin-number{
    position: absolute;
    left: 0;
    bottom: 43px;
    width: 266px;
    height: 56px;
    background: linear-gradient( 90deg, #589498 0%, rgba(88,148,152,0) 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    >img.icon{
      position: relative;
      top: -15px;
      width: 59px;
      height: 59px;
      margin-right: 20px;
    }
    >.value{
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: bold;
      font-size: 28px;
      line-height: 33px;
      color: #fff;
      margin-bottom: 10px;
      text-shadow: 0px 1px 1px rgba(0,0,0,0.25);
    }
  }

  .cert-view {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(10px);
    >img.cert-img{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 80%;
      height: 80%;
      object-fit: contain;
    }
    >a.btn-download{
      display: none;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 40px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: bold;
      font-size: 20px;
      color: #000;
    }
    >button.close{
      position: absolute;
      top: 20px;
      right: 20px;
      width: 50px;
      height: 50px;
      background-image: url(@/assets/images/icon_close.png);
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center center;
    }
  }
}

.cert-canvas {
  position: absolute;
  top: calc(-200% - 1920px);
  left: calc(-200% - 2880px);
  width: 1336px;
  height: 919px;
  background: url('@/assets/images/cert-min.png') no-repeat center / contain;

  p:first-child {
    position: absolute;
    top: calc(50% - 8px);
    left: 50%;
    color: #CFC49E;
    font-size: 70px;
    letter-spacing: 5px;
    font-family: 'Source Han Sans CN-Bold';
    transform: translate(-50%, -50%);
  }
  p:last-child {
    position: absolute;
    left: 352px;
    bottom: 155px;
    font-size: 20px;
  }
}
</style>