<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import Card from '@/page/subject/components/Card.vue'
import LoadIcon from '@/page/system/mailbox/components/LoadIcon.vue'
import doWorkApi from '@/api/subject/doWork'
import dayjs from '@/plugins/dayjs'
import { debounce, rateType } from '@/hooks'
import RoundSplit from '../textbookDetail/RoundSplit.vue'
import { subjectStore } from '@/stores'

const route = useRoute()
const router = useRouter()

const colorConfig: anyObj = {
  primary: '#2D39BC',
  success: '#2F8A5B',
  error: '#BC2D37',
  warning: '#a13c00',
}

const page = reactive({
  size: 28,
  current: 1,
  total: 0,
})

let knowledgeId = route.params.knowledgeId
let subjectId = route.params.subjectId
let textBookId = route.query.textBookId

const list = ref<anyObj[]>([])
const loading = ref(false)
async function getList() {
  loading.value = true
  try {
    const data = await doWorkApi.getTrainRecordList({
      ...page,
      knowledgeId,
      subjectId,
      resourceType: 0,
    })
    list.value.push(...data.rows)
    page.total = data.totalRows
  } catch {}
  loading.value = false
}

const scrollBoxRef = ref()
async function handleScroll(event: any) {
  if (list.value.length >= page.total) return
  if (loading.value) return
  if (event.target.scrollTop + event.target.offsetHeight >= scrollBoxRef.value?.offsetHeight - 50) {
    page.current++
    try {
      loading.value = true
      await getList()
    } catch {
      page.current--
    }
    loading.value = false
  }
}

const debounceScroll = debounce(handleScroll, 200, false)

const pageLoading = ref(false)
const pageError = ref(false)
// 初始化列表
async function initList() {
  if (pageLoading.value) return
  pageError.value = false
  pageLoading.value = true
  list.value = []
  page.current = 1
  try {
    await getList()
  } catch {
    pageError.value = true
  }
  pageLoading.value = false
}

function toDetail(item: anyObj) {
  router.push('/subject/doWork/' + item.id)
}
const { difficulty } = toRefs(subjectStore())
function handleStart() {
  router.push({
    path: '/subject/doWork',
    query: {
      resourceType: 0,
      subjectId,
      knowledgeId,
      difficulty: difficulty.value,
      textBookId,
    },
  })
}

const debounceStart = debounce(handleStart, 500)

onActivated(() => {
  knowledgeId = route.params.knowledgeId
  subjectId = route.params.subjectId
  textBookId = route.query.textBookId
  initList()
})
</script>
<template>
  <div class="train-record">
    <div class="train-record-title">
      练习记录
      <DifficultyStart v-model="difficulty"></DifficultyStart>
    </div>
    <RoundSplit :length="88"></RoundSplit>
    <div class="train-record-list">
      <div v-if="list.length" class="hidden_scroll" @scroll="debounceScroll">
        <div ref="scrollBoxRef" class="scroll-box">
          <div
            v-for="i in list"
            :key="i.id"
            class="train-record-list-item pointer"
            @click="toDetail(i)"
          >
            <Card
              width="100%"
              height="100%"
              :title="`答题正确率：${i.correctRate / 100}%`"
              :rate="i.correctRate / 10000"
              :tip="dayjs(i.createTime).format('YYYY-MM-DD HH:mm')"
              :type="rateType(i.correctRate)"
              :difficulty="i.difficulty || 0"
            >
            </Card>
            <div class="look" :style="{ color: colorConfig[rateType(i.correctRate)] }">查看</div>
          </div>
        </div>
      </div>
      <Empty
        v-else
        class="empty"
        :type="pageLoading ? 'loading' : pageError ? 'network' : 'practice'"
      ></Empty>
      <LoadIcon v-if="loading"></LoadIcon>
      <mj-button
        type="warn"
        class="start-btn"
        width="386"
        height="108"
        size="48"
        @click="debounceStart"
        >开始练习</mj-button
      >
    </div>
  </div>
</template>
<style scoped lang="scss">
.train-record {
  line-height: 1.5;
  position: relative;
  &-title {
    color: $font-color;
    font-family: $font-special;
    font-size: 3vh;
    padding: 2vh 32px;
    border-radius: 1.67vh;
    background: linear-gradient(269deg, #86e6ff 2.25%, #9effda 51.93%, #5fdcfd 99.65%);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .round-split {
    position: absolute;
    width: calc(100% - 50px);
    left: 50%;
    transform: translate(-50%);
    // z-index: 1;
    top: 8.75vh;
    :deep(.dot) {
      background: linear-gradient(180deg, #5e67ba 0%, #7b87f5 100%);
    }
  }
  &-list {
    height: 76.83vh;
    background: linear-gradient(180deg, #f0faff 0%, #fafdff 100%);
    border-radius: 1.67vh;
    padding: 2.67vh 40px;
    position: relative;
    overflow: hidden;
    .hidden_scroll {
      height: 100%;
      .scroll-box {
        display: grid;
        grid-template-columns: repeat(4, 398px);
        grid-template-rows: 192px;
        grid-auto-rows: 192px;
        row-gap: 2.67vh;
        column-gap: 40px;
      }

      :deep(.xxl-card-tip) {
        background-color: transparent;
        color: #666;
        text-align: right;
        font-family: 'OPPO Sans';
        font-size: 2vh;
        font-style: normal;
        font-weight: 400;
      }
      .train-record-list-item {
        position: relative;
        cursor: pointer;
        .look {
          color: #a13c00;
          text-align: right;
          font-family: $font-special;
          font-size: 2.33vh;
          position: absolute;
          top: 1.33vh;
          right: 24px;
        }
      }
    }
    .custom_load_icon {
      position: absolute;
      bottom: 0.83vh;
      left: 50%;
      transform: translate(-50%);
    }
    .start-btn {
      position: absolute;
      bottom: 4vh;
      left: 50%;
      transform: translate(-50%);
    }
    .empty {
      margin-top: -8.33vh;
    }
  }
}
</style>
