<template>
  <div class="page__container">
    <div :class="['wrapper', { not_data: !table.data.length }]">
      <div class="back-btn" @click="router.back()"></div>
      <div class="title">
        <img class="full-w-h" :src="icon_title" />
      </div>
      <div v-if="table.data.length" class="table_container">
        <div class="table">
          <div class="row header">
            <div v-for="item in table.column" :key="item.label" class="cell">
              {{ item.label }}
            </div>
          </div>
          <div class="tbody">
            <div v-for="row in table.data" :key="row.id" class="row" @click="checkDetail(row.id)">
              <div v-for="data in table.column" :key="data.label" class="cell">
                <div v-if="data.prop === 'rightNum'" class="cellGroup">
                  <div
                    class="cell"
                    :style="{
                      color: getColor(Math.floor((row[data.prop] / row.totalNum) * 100)),
                    }"
                  >
                    {{ Math.floor((row[data.prop] / row.totalNum) * 100) }}%
                  </div>
                  <div
                    class="cell"
                    :style="{
                      color: getColor(Math.floor((row[data.prop] / row.totalNum) * 100)),
                    }"
                  >
                    {{ row[data.prop] }}/{{ row.totalNum }}
                  </div>
                </div>
                <div
                  v-else-if="data.prop === 'createTime'"
                  class="createTime"
                  :style="{
                    color: isDay(row[data.prop]) ? '#90CEFC' : '#17538A',
                  }"
                >
                  <img
                    v-if="isDay(row[data.prop])"
                    class="icon_time"
                    :src="icon_day"
                    mode="scaleToFill"
                  />
                  <img v-else class="icon_time" :src="icon_night" mode="scaleToFill" />
                  {{ row[data.prop].replace(/-/g, '/').replace(/\s/g, '\n') }}
                </div>
                <div v-else-if="data.prop === 'duration'">
                  {{ dealTime(row[data.prop] / 1000) }}
                </div>
                <div v-else-if="data.prop === 'testType'" class="fz0">
                  <img
                    v-if="row[data.prop] === 1"
                    class="table_icon"
                    :src="icon_sui"
                    mode="scaleToFill"
                  />
                  <img v-else class="table_icon" :src="icon_fu" mode="scaleToFill" />
                </div>
                <div
                  v-else-if="data.prop === 'comboNum'"
                  :style="{
                    color: getColor(Math.floor((row[data.prop] / row.totalNum) * 100)),
                  }"
                >
                  {{ row[data.prop] }}
                </div>
                <div v-else>
                  {{ (row as any)[data.prop] }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="filter_btns">
        <div class="btn" @click="changeMode(1 - modeCode)">
          <img v-show="modeCode === 0" :src="btn_mode_1" />
          <img v-show="modeCode === 1" :src="btn_mode_2" />
        </div>
        <i class="t-icon t-icon-Question_fill1" @click="isShowIllustrate = true"></i>
      </div>
      <div class="btn_start" @click="toTest">开始测试</div>
    </div>
    <ConfirmDia v-model="showDia" text="还没学够十个词，快去学习吧～" @confirm="showDia = false" />
    <RecordDetailPop v-model="showDetail" v-bind="detail as any" />
    <div v-show="isShowIllustrate" class="popup">
      <div class="popup_content">
        <img class="full-w-h" :src="icon_popup" />
        <div class="close-btn pointer" @click="isShowIllustrate = false"></div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import RecordDetailPop from './components/RecordDetailPop.vue'
import wordTestApi from '@/api/subject/wordTest'
import useExam from './hooks/useExam'
import type { TestRecord } from './type'
import { useRouter } from 'vue-router'
import hud from '@/utils/hud'

// import { onShow } from '@dcloudio/uni-app';

const table = reactive({
  column: [
    {
      label: '模式',
      prop: 'testType',
    },
    {
      label: '成绩',
      prop: 'rightNum',
    },
    {
      label: '连击数',
      prop: 'comboNum',
    },
    {
      label: '时间',
      prop: 'createTime',
    },
    {
      label: '耗时',
      prop: 'duration',
    },
  ],
  data: [] as TestRecord[],
})

const router = useRouter()

const OSS_URL = import.meta.env.VITE_OSS_URL
const icon_sui = `${OSS_URL}/xuexiaole_clinet/normalMode/icon_sui.png`
const icon_fu = `${OSS_URL}/xuexiaole_clinet/normalMode/icon_fu.png`
const btn_mode_1 = `${OSS_URL}/xuexiaole_clinet/normalMode/btn_mode_1.png`
const btn_mode_2 = `${OSS_URL}/xuexiaole_clinet/normalMode/btn_mode_2.png`
const icon_night = `${OSS_URL}/xuexiaole_clinet/normalMode/icon_night.png`
const icon_day = `${OSS_URL}/xuexiaole_clinet/normalMode/icon_day.png`
const icon_title = `${OSS_URL}/xuexiaole_clinet/normalMode/title.png`
const icon_popup = `${OSS_URL}/xuexiaole_clinet/normalMode/popup.png`
const back_btn = `url(${OSS_URL}/xuexiaole_clinet/normalMode/back_btn.png)`
const not_data = `url(${OSS_URL}/xuexiaole_clinet/normalMode/not_data.png) center/contain no-repeat`
const pattern_bg = `#fffef5 url(${OSS_URL}/xuexiaole_clinet/normalMode/pattern_bg.png)`

const state = useExam()
const showDetail = ref(false)
const detail = ref([])
const modeCode = ref(0) // 0: 复习模式， 1：随机模式
const showDia = ref(false)
const isShowIllustrate = ref(false)

function checkDetail(id: any) {
  wordTestApi.getWordTestRecordDetail(id).then(res => {
    if (res.data.code === 200) {
      showDetail.value = true
      detail.value = res.data.data
    }
  })
}

function changeMode(code: number) {
  modeCode.value = code
  state.mode.value = code
}
function dealTime(time: number) {
  const h = parseInt(String((time / 60 / 60) % 24), 10)
  const m = parseInt(String((time / 60) % 60), 10)
  const s = parseInt(String(time % 60), 10)

  if (time === undefined) return

  if (h > 0) {
    return m === 0 ? `${h}h` : `${h}h ${m}m`
  } else if (m > 0) {
    return s === 0 ? `${m}m` : `${m}m ${s}s`
  } else if (s > 0) {
    return `${s}s`
  } else {
    return '0'
  }
}
function getColor(rate: number) {
  return rate >= 100 ? '#99D609' : rate >= 80 ? '#09C2D6' : rate >= 60 ? '#FFA51F' : '#D9574E'
}
function isDay(date: string) {
  const hour = parseInt(date.split(' ')[1].split(':')[0], 10)
  return hour > 6 && hour < 18
}

const loadingWords = ref(false)
function toTest() {
  if (loadingWords.value) return

  loadingWords.value = true
  state.mode.value = modeCode.value
  hud.loading('加载中')
  wordTestApi
    .getWordTestWords({
      size: state.numOfQuestions.value,
      testType: state.mode.value, // 0: 复习模式， 1：随机模式
      startTime: new Date().getTime(),
    })
    .then(res => {
      state.questionsChooseTitleLib.value = res.chooseTitle
      state.questionSpellTitleLib.value = res.spellTitle
      state.questions.total = res.chooseTitle.length + res.spellTitle.length
      // uni.navigateTo({ url: '/pages/wordsTest/testList' });
      router.push('/subject/learnWord/word-table-test')
    })
    .catch(res => {
      if (res.data?.code === 9998) {
        showDia.value = true
      } else {
        hud.error('网络异常，请稍后重试')
      }
    })
    .finally(() => {
      loadingWords.value = false
      hud.hideLoading()
    })
}
defineOptions({
  name: 'WordTestRecords',
})

onMounted(() => {
  wordTestApi.getWordTestRecordList({ size: 7 }).then(res => {
    table.data = res.data.data.rows || []
  })
  state.reset()
})
</script>
<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
.back-btn {
  width: 10vh;
  height: 10vh;
  background-image: v-bind(back_btn);
  background-repeat: no-repeat;
  background-size: cover;
  pointer-events: auto;
  cursor: pointer;
  position: absolute;
  left: -63px;
  top: -5.17vh;
}
.page__container {
  height: 100%;
  overflow: auto;
  position: relative;
  background-color: #dfdaf2;

  .popup {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 10;
    background: rgba($color: #000000, $alpha: 0.45);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    .popup_content {
      position: relative;
      width: 666px;
      height: 58.92vh;
      .close-btn {
        position: absolute;
        right: 0;
        top: 1.5vh;
        width: 4vh;
        height: 4vh;
      }
    }
  }
}
.wrapper {
  position: relative;
  width: 1600px;
  height: 71.67vh;
  margin: 9.17vh auto;
  padding: 5vh 40px;
  border-radius: 3.33vh;
  border: 0.33vh solid #d9d163;
  background: #fffef5;
  &.not_data {
    background: v-bind(pattern_bg);
    &::after {
      content: '';
      width: 674px;
      height: 31.08vh;
      position: absolute;
      left: 464px;
      top: 12.67vh;
      background: v-bind(not_data);
    }
  }

  .title {
    width: 26.33vh;
    height: 11.33vh;
    position: absolute;
    left: 50%;
    top: -5.83vh;
    transform: translateX(-50%);
  }
  .table_container {
    border-radius: 2.5vh;
    padding: 2.67vh 32px;
    // background: url('~@/static/studyReport/fill.png') center/cover no-repeat;
    background-color: #fef79a;
  }
  .table {
    border-radius: 1.67vh;
    border: 0.33vh solid #ccc018;
    background-color: #fffef2;
    color: #6a3906;
    font-size: 2.67vh;
    font-weight: 500;
    .row {
      display: flex;
      width: 100%;
      border-bottom: 0.17vh solid #ccc018;
      cursor: pointer;
      &:last-child {
        border-bottom: none;
      }
      .cell {
        width: 190px;
        height: 6.33vh;
        flex: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #6a3906;
        font-family: $font-special;
        font-size: 2.17vh;
        text-align: center;

        font-weight: 500;
        border-left: 0.17vh solid #ccc018;
        &:first-child {
          border-left: none;
          width: 162px;
        }

        .fz0 {
          font-size: 0;
        }
        .table_icon {
          width: 5.33vh;
          height: 5.33vh;
        }
        .createTime {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          white-space: pre-wrap;
          font-size: 1.67vh;
          .icon_time {
            width: 4vh;
            height: 4vh;
          }
        }
      }
      .cellGroup {
        flex: 1;
        display: flex;
        .cell {
          width: unset;
          flex: 1;
          text-align: center;
        }
      }
    }
    .header {
      .cell {
        font-family: $font-text;
        font-size: 2.33vh;
        height: 7.5vh;
      }
    }
  }
  .filter_btns {
    cursor: pointer;
    position: absolute;
    left: 75px;
    top: 67.58vh;
    .btn {
      width: 21.33vh;
      height: 6.67vh;
      & > img {
        width: 100%;
        height: 100%;
      }
    }
    .t-icon {
      width: 3.33vh;
      height: 3.33vh;
      position: absolute;
      right: -44px;
      top: 0;
      cursor: pointer;
    }
  }
  .btn_start {
    cursor: pointer;
    position: absolute;
    left: 50%;
    top: 100%;
    transform: translate(-50%, -50%);
    padding: 0.83vh 90px;
    border-radius: 4.67vh;
    border: 0.33vh solid #6a3906;
    background: #fff01f;
    color: #ffa51f;
    text-align: center;
    font-family: $font-special;
    font-size: 4vh;
  }
}
</style>
