<script setup lang="ts">
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import LoadIcon from '@/page/system/mailbox/components/LoadIcon.vue'
import VideoFullBox from '@/page/subject/components/VideoFullBox/index.vue'
import subjectApi from '@/api/subject/subject'
import { debounce, useAudio, useLog, LogType } from '@/hooks'
import { userStore, subjectStore } from '@/stores'
import { resource_type_analogy } from '../doWork'

const { subject } = subjectStore()

const route = useRoute()
const router = useRouter()
const { userInfo } = userStore()
let subjectId = (route.params.subjectId as string) || ''

// 列表
const list = ref<anyObj[]>([])
const page = reactive({
  size: 10,
  current: 1,
  total: 0,
})
const loading = ref(false)

async function getList() {
  const { data: res } = await subjectApi.getWrongQuesList({
    subjectId,
    correctFlag: correctFlag.value,
    ...page,
  })

  if (res.code === 200) {
    console.log('res.data', res.data)
    list.value.push(...(res.data.rows || []))
    page.total = res.data.totalRows
  }
}

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 emptyText = ref('暂无错题')

// 初始化列表
async function initList() {
  if (pageLoading.value) return
  pageLoading.value = true
  list.value = []
  page.current = 1
  try {
    await getList()
    emptyText.value = correctFlag.value ? '暂无已订正错题' : '暂无未订正错题'
  } catch {
    emptyText.value = '网络出问题了啦～'
  }
  pageLoading.value = false
}

const correctFlag = ref<0 | 1>(0)
const correctConfig = reactive([
  { value: 0, label: '未订正' },
  { value: 1, label: '已订正' },
])
const unCorrectNum = ref(0)
async function getCorrectConfig() {
  const { data: res } = await subjectApi.getUserErrorInfo({ subjectId })
  unCorrectNum.value = res.data.unCorrectNum
  correctConfig[0].label = `未订正 ${res.data.unCorrectNum}题`
  correctConfig[1].label = `已订正 ${res.data.correctNum}题`
}

function changeCorrect() {
  initList()
}

/*
 ** 音频
 */
// 播放器
let player: anyObj = {}
const activeAudio = ref('')
function handlePlay(item: anyObj) {
  activeAudio.value = item.subjectTitleVo.id
  player.src = item.subjectTitleVo.voiceUrl
  player.play()
}

// 举一反三
function startTrain(item: anyObj) {
  router.push({
    path: '/subject/doWork',
    query: { resourceType: resource_type_analogy, num: 3, subjectId, titleId: item.titleId },
  })
}
const debounceStartTrain = debounce(startTrain, 500)

function handleStart() {
  if (unCorrectNum.value <= 1) {
    handleDiaOK()
  } else {
    showDia.value = true
  }
}

// 订正错题弹窗
const showDia = ref(false)
const correctNum = ref(1)
function handleDiaOK() {
  router.push({
    path: '/subject/doWork',
    query: { resourceType: 2, num: correctNum.value, subjectId },
  })
}
function changeCorrectNum(type: 0 | 1) {
  if (type) {
    if (correctNum.value >= 10) return
    correctNum.value++
  } else {
    if (correctNum.value <= 1) return
    correctNum.value--
  }
}

// 视频播放器
const videoDia = reactive<anyObj>({
  show: false,
  knowledge: {},
})
function playVideo(item: anyObj) {
  // videoDia.videoList = list;
  videoDia.show = true
  videoDia.knowledge.id = item.id
  videoDia.knowledge.name = item.name
}

// 图片预览弹窗
const imgDia = reactive({
  show: false,
  url: '',
})
function handleShow(url: string) {
  imgDia.show = true
  imgDia.url = url
}

// (async () => {
//     // initList();
//     // getCorrectConfig();
//     nextTick(() => {

//     });
// })();

// 埋点 - 学习时间
let startTime = 0
let endTime = 0
watch(
  list,
  newVal => {
    if (newVal.length) {
      startTime = new Date().getTime()
    } else {
      if (startTime) {
        endTime = new Date().getTime()
        useLog(LogType.StudyTime, {
          resourceType: 2,
          studyTime: endTime - startTime,
          subjectId,
          userId: userInfo.userId,
          startTime,
          endTime,
        })
        startTime = 0
      }
    }
  },
  {
    deep: true,
  },
)

onBeforeRouteLeave((_to, _from, next) => {
  if (!startTime) return next()
  endTime = new Date().getTime()
  useLog(LogType.StudyTime, {
    resourceType: 2,
    studyTime: endTime - startTime,
    subjectId,
    userId: userInfo.userId,
    startTime,
    endTime,
  })
  next()
})

onMounted(() => {
  player = useAudio({
    autoplay: false,
  })
})

onActivated(async () => {
  pageLoading.value = false
  loading.value = false
  subjectId = route.params.subjectId as string
  activeAudio.value = ''
  correctFlag.value = 0
  showDia.value = false
  correctNum.value = 1
  getCorrectConfig()
  await initList()
})

onDeactivated(() => {
  showDia.value = false
  player.pause?.()
})

onUnmounted(() => {
  player.destroy()
})
</script>
<template>
  <div class="wrong-book">
    <div class="top">
      <BackBar :leftText="`【${subject.name}】错题本`" />

      <div class="top-select">
        <SelectTab
          v-model="correctFlag"
          :dataList="correctConfig"
          @change="changeCorrect"
        ></SelectTab>
      </div>
    </div>
    <board-bg class="main">
      <template v-if="list.length">
        <div class="main-list hidden_scroll" @scroll="debounceScroll">
          <div ref="scrollBoxRef" class="scroll-box QuesItemBox">
            <template v-for="i in list" :key="i.id">
              <WrongQuesItem
                v-if="i?.subjectTitleVo"
                :correctFlag="correctFlag"
                :data="
                  Object.assign(i?.subjectTitleVo || {}, {
                    submitAnswer: i.submitAnswer,
                  })
                "
                :time="correctFlag ? i.correctTime : i.errorTime"
                :activeAudio="activeAudio"
                @startTrain="debounceStartTrain(i)"
                @play="handlePlay(i)"
                @playVideo="playVideo"
                @showPic="handleShow"
              ></WrongQuesItem>
            </template>
          </div>
        </div>
        <LoadIcon v-if="loading" class="load-icon"></LoadIcon>
      </template>
      <Empty
        v-else
        class="empty"
        :type="pageLoading ? 'loading' : 'learn'"
        :content="emptyText"
      ></Empty>
    </board-bg>
    <mj-button
      v-if="unCorrectNum"
      class="start_train-btn"
      type="success"
      width="232"
      height="80"
      @click="handleStart"
    >
      订正错题
    </mj-button>
    <mj-dialog
      v-model="showDia"
      :hide-cancel="true"
      ok-text="开始"
      title="订正错题"
      :ok="handleDiaOK"
    >
      <div class="dia_body">
        <div class="dia_body-title">系统将从您的错题本中随机选择题目</div>
        <div class="dia_body-slider">
          <div class="dia_body-slider-box">
            <Icon name="slider_btn_reduce" width="56" @click="changeCorrectNum(0)"></Icon>
            <el-slider
              v-model="correctNum"
              :show-tooltip="false"
              :step="1"
              :max="unCorrectNum > 10 ? 10 : unCorrectNum"
              :min="1"
            ></el-slider>
            <Icon name="slider_btn_add" width="56" @click="changeCorrectNum(1)"></Icon>
          </div>

          <div class="dia_body-slider-text">
            数量：{{ correctNum }}/{{ unCorrectNum > 10 ? 10 : unCorrectNum }}
          </div>
        </div>
      </div>
    </mj-dialog>
    <VideoFullBox
      v-model:show="videoDia.show"
      :knowledge="videoDia.knowledge"
      :data="{
        subjectId,
        resourceType: 2,
        origin: 2,
      }"
    ></VideoFullBox>
    <ImgView v-model="imgDia.show" :url="imgDia.url"></ImgView>
  </div>
</template>
<style scoped lang="scss">
.wrong-book {
  @include main_bg;
  position: relative;
  width: 100vw;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;
  position: relative;
  // @include hidden_scroll;
  .top {
    padding: 2.67vh 64px 0;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    margin-bottom: 2vh;
    display: flex;
    align-items: center;
    &-select {
      width: 1172px;
      margin-left: 62px;
      :deep(.select-list) {
        .data-item {
          width: 50%;
          &.active {
            background: linear-gradient(269deg, #86e6ff 2.25%, #9effda 51.93%, #5fdcfd 99.65%);
            backdrop-filter: blur(3px);
          }
        }
      }
    }
  }
  .main {
    position: relative;
    margin: 13.67vh auto 0;
    background-color: #e6f5fe;
    width: 1792px;
    height: 83vh;
    padding: 5.33vh 36px 0;

    &-list {
      width: 100%;
      height: calc(100% - 3vh);
      // margin: 2.67vh;
      // .scroll-box {
      //   height: 100%;
      //}
    }
    .custom_load_icon {
      position: absolute;
      bottom: 3.17vh;
      left: 50%;
      transform: translate(-50%);
    }
    .empty {
      height: 75vh;
    }
  }
  .start_train-btn {
    position: absolute;
    bottom: 13.33vh;
    right: -35px;
    z-index: 100;
    :deep(.x-button-text) {
      transform: translate(-8px);
    }
  }
}
.dia_body {
  // height: 392px;
  padding: 3.33vh 0;
  text-align: center;
  color: $font-color;
  line-height: 1.5;
  &-title {
    text-align: center;
    font-family: $font-special;
    font-size: 2.67vh;
  }
  &-slider {
    margin-top: 3.33vh;
    &-box {
      display: flex;
      align-items: center;
      padding: 0 24px;
      .x-icon {
        margin: 0 32px;
        flex-shrink: 0;
      }
    }
    :deep(.el-slider) {
      height: 4.67vh;
      .el-slider__runway {
        height: 3vh;
        background: #9a9ea0;
        border-radius: 2.5vh;
      }
      .el-slider__bar {
        height: 3vh;
        border-radius: 2.5vh;
        background: linear-gradient(249deg, #4de798 26.9%, #a2fb6e 79.86%);
      }
      .el-slider__button-wrapper {
        width: 56px;
        height: 4.67vh;
        background: radial-gradient(189.06% 189.06% at 49.22% 50.78%, #fff 0%, #becadf 100%);
        border-radius: 50%;
        filter: drop-shadow(0px 3.5px 3.5px rgba(0, 0, 0, 0.15));
        top: -0.83vh;
      }
      .el-slider__button {
        width: 56px;
        height: 4.67vh;
        border: none;
      }
    }
    &-text {
      margin-top: 1.33vh;
      font-family: OPPOSans;
      font-size: 2vh;
    }
  }
}
</style>
