<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, XMessage } from '@/hooks'
import { subjectStore } from '@/stores'

const props = defineProps<{
  chapterId: string
  moduleId?: any
}>()

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

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

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

// 是否显示难度选择
const difficultyVisible = computed(() => {
  return !props.moduleId
})

let subjectId = route.params.subjectId
let textBookId = route.params.textBookId

const list = ref<anyObj[]>([])
const loading = ref(false)
async function getList() {
  loading.value = true
  try {
    const data = await doWorkApi.getTrainRecordList({
      ...page,
      chapterId: props.chapterId,
      subjectId,
      resourceType: 0,
      freeLearnType: 1,
      moduleId: props.moduleId || undefined,
    })
    list.value.push(...data.rows)
    page.total = data.totalRows
  } finally {
    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 canViewDetail(item: anyObj) {
  return Number(item.gradingStatus) === 1
}

function toDetail(item: anyObj) {
  if (!canViewDetail(item)) {
    XMessage.error('该练习未批改，暂不可查看详情')
    return
  }
  router.push('/subject/doWork/' + item.id)
}
const { difficulty } = toRefs(subjectStore())
function handleStart() {
  router.push({
    path: '/subject/doWork',
    query: {
      resourceType: 0,
      subjectId,
      chapterId: props.chapterId,
      freeLearnType: 1,
      difficulty: difficulty.value,
      textBookId,
      moduleId: props.moduleId || undefined,
    },
  })
}

const debounceStart = debounce(handleStart, 500)

watch([() => props.chapterId, () => props.moduleId], () => initList())

onMounted(() => {
  initList()
})
</script>
<template>
  <div class="train-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': true,
            'can-view': canViewDetail(i),
            'disabled-view': !canViewDetail(i),
          }"
          @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: canViewDetail(i) ? colorConfig[rateType(i.correctRate)] : '#999999',
            }"
          >
            {{ canViewDetail(i) ? '查看' : '未批改' }}
          </div>
        </div>
      </div>
    </div>
    <Empty
      v-else
      class="empty"
      :type="pageLoading ? 'loading' : pageError ? 'network' : 'practice'"
    ></Empty>
    <LoadIcon v-if="loading"></LoadIcon>
    <div class="start-btn-box">
      <DifficultyStart v-if="difficultyVisible" v-model="difficulty"></DifficultyStart>
      <mj-button type="warn" width="365" height="88" size="42" @click="debounceStart">
        开始练习
      </mj-button>
    </div>
  </div>
</template>
<style scoped lang="scss">
.train-list {
  background-color: #ffffff;
  border-radius: 1.67vh;
  height: 100%;
  overflow: hidden;
  position: relative;
  padding: 1.33vh;
  @include hidden_scroll;
  .hidden_scroll {
    height: 100%;
    overflow-y: auto;
    .scroll-box {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(312px, 1fr));
      grid-auto-rows: minmax(180px, auto);
      gap: 1.67vh 20px;
      padding-bottom: 10vh;
      :deep(.xxl-card) {
        width: 100% !important;
        height: 100% !important;
        padding: 1.33vh 20px;
        .xxl-card-title {
          font-size: 2.17vh;
        }
      }
    }

    :deep(.xxl-card-tip) {
      background-color: transparent;
      color: #666;
      text-align: right;
      font-family: 'OPPO Sans';
      font-size: 1.67vh;
      font-style: normal;
      font-weight: 400;
    }
    .train-record-list-item {
      position: relative;
      min-height: 180px;
      &.can-view {
        cursor: pointer;
      }
      &.disabled-view {
        cursor: not-allowed;
      }
      .look {
        color: #a13c00;
        text-align: right;
        font-family: $font-special;
        font-size: 2.17vh;
        position: absolute;
        top: 1.33vh;
        right: 24px;
      }
    }
  }
  .custom_load_icon {
    position: absolute;
    bottom: 0.83vh;
    left: 50%;
    transform: translate(-50%);
  }
  .start-btn-box {
    width: calc(100% - 2.67vh);
    text-align: center;
    position: absolute;
    bottom: 3.33vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .mj-button {
      margin-top: 2.08vh;
    }
  }

  .empty {
    margin-top: -8.33vh;
  }
}
</style>
