<script setup lang="ts">
import happyReadApi from '@/api/subject/happyRead'
import { useRouter } from 'vue-router'
import { XMessage } from '@/hooks'

const OSS_URL = `${import.meta.env.VITE_OSS_URL}`
const bgTwo = `url(${OSS_URL}/urm/read_readRecord.svg) 100%/cover no-repeat`
const router = useRouter()
const dataList = ref<anyObj[]>([])
// 阶段
const selectId = ref('')
const selectList = ref([
  {
    value: '',
    label: '全部',
  },
])
// 得分类型
const typeId = ref('')
const typeList = ref([
  { label: '全部', value: '' },
  { label: '满分', value: 1 },
  { label: '失分', value: 2 },
])
const configColor = {
  success: '#2F8A5B',
  primary: '#2D39BC',
  warning: '#A13C00',
  error: '#B22731',
}
const pageData = ref({
  current: 1,
  totalPage: 1,
  totol: 0,
})
const loadingCircle = ref(true)
const dataLoading = ref(false) // 滚动加载loading
const loading = ref(false) // 查看详情loading
// 正确率的颜色
function getColor(rate: number) {
  return rate === 100 ? 'success' : rate >= 80 ? 'primary' : rate >= 60 ? 'warning' : 'error'
}

function timeTool(time: number) {
  if (!time) return '0s'
  if (time <= 60) return `${time}s`
  const m = parseInt(String(time / 60), 10)
  const s = parseInt(String(time % 60), 10)
  return `${m}m ${s}s`
}

function init() {
  //
}
// 改变阶段
function changeStage(e: anyObj) {
  pageData.value.current = 1
  getListData(true)
}
// 改变得分情况
function changeType(e: anyObj) {
  pageData.value.current = 1
  getListData(true)
}

// 获取阶段下拉列表
function getSelectList() {
  happyReadApi.getReadGradeList().then(res => {
    selectList.value = res.data.data.map((item: number) => {
      return {
        value: item,
        label: ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'][item] + '阶',
      }
    })
    selectList.value.unshift({
      value: '',
      label: '全部',
    })
  })
}
// 获取答题记录列表
function getListData(needClear?: boolean) {
  happyReadApi
    .getReadRecoredList({
      current: pageData.value.current,
      size: 20,
      grade: selectId.value, // 阶段
      fullType: typeId.value, // 得分类型
    })
    .then(res => {
      // dataList.value.concat(res.data.data.rows);
      if (needClear) dataList.value = []
      dataList.value = [...dataList.value, ...res.data.data.rows]
      console.log('dataList.value', dataList.value)
      pageData.value.current++
      pageData.value.totalPage = res.data.data.totalPage
      pageData.value.totol = res.data.data.totalRows
      dataLoading.value = false
      loadingCircle.value = false
    })
}

async function onScrollToLower(e: any) {
  if (dataLoading.value) return
  // 滚动条滚动时，距离顶部的距离
  const scrollTop = e.target.scrollTop
  // 可视区的高度
  const windowHeight = e.target.clientHeight
  // 滚动条的总高度
  const scrollHeight = e.target.scrollHeight
  // 当滚动条滚动到距离底部100px时进行翻页
  if (scrollTop + windowHeight >= scrollHeight - 100) {
    dataLoading.value = true
    if (pageData.value.current <= pageData.value.totalPage) {
      getListData()
    }
  }
}

// 查看答题详情
function goDetail(item: anyObj) {
  console.log('item', item)
  if (loading.value) return
  loading.value = true
  happyReadApi
    .getReadRecoredDetail({
      id: item.id,
    })
    .then((res: any) => {
      console.log(res)
      if (!res.data.data.answers) {
        XMessage.error('暂无答题记录')
        return
      }

      router.push(`/subject/happyRead/shortReading/shortReadingDetail?id=${item.id}`)
    })
    .finally(() => {
      loading.value = false
    })
}

onActivated(() => {
  pageData.value.current = 1

  getListData(true)
})
onMounted(() => {
  getSelectList()
})
</script>
<template>
  <div class="page">
    <div class="top">
      <BackBar leftText="阅读记录" class="backBar" />
      <div class="right">
        <LineFont :text="`共${pageData.totol}篇`" class="num" />
        <Select v-model="selectId" :selectList="selectList" @selectChange="changeStage"></Select>
        <Select v-model="typeId" :selectList="typeList" @selectChange="changeType"></Select>
      </div>
    </div>
    <div class="content">
      <div v-if="dataList.length" class="list hidden_scroll pointer" @scroll="onScrollToLower">
        <div
          v-for="(item, index) in dataList"
          :Key="index"
          class="list-item"
          @click="goDetail(item)"
        >
          <div class="top">
            <span :class="['', 'one', 'two'][item.grade]">
              {{
                (['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'][item.grade] ||
                  '') + '阶'
              }}
            </span>
            <div class="title">
              {{ item.topic }}
            </div>
          </div>
          <div class="bottom">
            <div class="bottom-item wordCount">
              本文词汇量：<span class="num"> {{ item.wordCount }}</span>
            </div>
            <div class="bottom-item readCoastTime">
              阅读时长：<span class="num">{{ timeTool(item.learnTime) }}</span>
            </div>
            <div class="bottom-item readDate">
              阅读时间：<span class="num">{{
                item.createTime.slice(0, item.createTime.length - 3)
              }}</span>
            </div>
            <div class="bottom-item rate">
              <span
                class="rate-text"
                :style="{
                  color: configColor[getColor(item.rightRate)],
                }"
              >
                正确率：
                <span class="rate-num">{{ item.rightRate }}%</span>
              </span>
              <ProgressBar
                :rate="item.rightRate / 100"
                :type="getColor(item.rightRate)"
                width="226"
                height="28"
              ></ProgressBar>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty">
        <Icon v-if="loadingCircle" name="global_loading" loading size="96" />
        <Empty v-else type="learn" content="暂无阅读记录，快去阅读吧！"> </Empty>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  padding: $space-4_h $space-6;
  @include main_bg;
  text-align: center;
  .top {
    display: flex;
    justify-content: space-between;
    .right {
      display: grid;
      grid-template-columns: repeat(3, 254px);
      gap: 50px;
      justify-items: right;
      align-items: center;
      .num {
        font-family: $font-special;
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
      }
    }
  }
  .content {
    width: 100%;
    height: 85.33vh;
    display: flex;
    justify-content: center;
    // background-color: #faffff;
    background: v-bind(bgTwo);

    border-radius: 3.33vh;
    margin-top: $space-2_h;
    padding: $space-5_h $space-6;

    .list {
      width: 1696px;
      //
      height: 78.67vh;
      overflow: auto;
      .list-item {
        padding: 2vh 32px;
        border-radius: 1.67vh;
        border: 0.33vh solid #90fcf7;
        background: #f2fffe;
        box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25);
        margin-top: 1.33vh;
        &:first-child {
          margin: 0;
        }
        .top,
        .bottom {
          display: flex;
          align-items: center;
        }
        .top {
          span {
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 0.67vh;
            background-color: #801fff;

            color: #fff;
            font-family: $font-special;
            font-size: 2vh;
            padding: 0 12px;
            &.one {
              background-color: #99d609;
            }
            &.two {
              background-color: #ffa51f;
            }
          }
          .title {
            flex: 1;
            text-align: left;
            margin-left: 8px;
            color: $font-color;
            font-family: $font-special;
            font-size: 2.67vh;
            font-style: normal;
            font-weight: 400;
          }
        }
        .bottom {
          margin-top: 2vh;
          .bottom-item {
            text-align: left;
            border-right: 0.17vh solid #ccc;
            color: #999;
            font-family: OPPOSans;
            font-size: 2.33vh;
            font-style: normal;
            font-weight: 400;
            line-height: 2.33vh; /* 128.571% */
            height: 2.33vh;
            margin-left: 62px;
            .num {
              color: #666;
            }
            &:first-child {
              margin: 0;
            }

            &:last-child {
              border: none;
              display: flex;
              width: 414px;
              box-sizing: content-box;
            }
            &.wordCount {
              width: 264px;
            }
            &.readCoastTime {
              width: 280px;
            }
            &.readDate {
              width: 452px;
            }
            &.rate {
              width: 430px;
              .rate-text {
                display: flex;
                text-wrap: nowrap;
                font-family: $font-special;
              }
              .rate-num {
                width: 80px;
                text-align: center;
                margin-right: 10px;
              }
            }
          }
        }
      }
    }
    :deep(.empty) {
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .empty-content {
        color: #afbfcf;
      }
    }
  }
}
</style>
