<script setup lang="ts">
import sentence from '../../classicReading/readDetail/components/sentence.vue'
import ReadMeaningSentence from './components/ReadMeaningSentence.vue'
import happyReadApi from '@/api/subject/happyRead'
import type { sentenceChoose } from './interface/interface'
import ReportDia from '../../phonics/ReportDia.vue'
import { secondsToTime } from '@/utils/tool'
import { useSound } from '@/hooks'
import { useRoute, useRouter } from 'vue-router'
import { $sleep } from '@/utils'
import SearchWordPup from '@/page/subject/strangeBook/components/SearchWordPup.vue'
import { XMessage } from '@/hooks'
import { dialog } from '@/components/mj/mj-dialog'
import { globalBack } from '@/router'

const OSS_URL = import.meta.env.VITE_OSS_URL
const loadBg = `url(${OSS_URL}/urm/phonics_load_bg.svg) center/contain no-repeat`
const read_statistics = `url(${OSS_URL}/urm/read_statistics.png) center/contain no-repeat`

const sentenceDom = ref()
const router = useRouter()
const route = useRoute()
// 单词弹框
const showPop = ref(false)
// 单词弹框数据
const searchWord = ref({
  id: '',
  word: '',
})

// 左边阅读数据
const readEssay = ref<anyObj[]>([])
// 右边选择题数据
const readMeaningSentence = ref<sentenceChoose[]>([])

// 标题数据
const titleData = ref({
  topic: '',
  wordCount: 0,
  levelId: '',
  sessionId: '',
  grade: 1,
  characterName: '', // 人名
})
const beginTime = ref(0)

// 答题结束统计弹框
const showReport = ref(false)
// 单词答题弹框
const showWordChoose = ref(false)
// 单词答题结果存贮
const answerData = ref<anyObj>({})

// 再来一次加载中
const loading = ref(false)
// 统计按钮loading
const loadingBtn = ref(false)
// 显示统计按钮以及题目答案
const showStat = ref(false)
// 是否答题结束
const onEnd = computed(
  () =>
    Boolean(readMeaningSentence.value.length) &&
    Object.keys(answerData.value).length === readMeaningSentence.value.length,
)
// 下一题按钮出现
// const showNext = computed(
//     () => onEnd.value && !loading.value && !loading2.value && !showReport.value,
// );
// 退出确认框
const rewardData = ref({
  diamond: 0,
  exp: 0,
  nextGrade: null,
  nextType: null,
})
// 接口记录数据
const postData = computed(() => {
  return {
    learnTime: 0, // 用时
    learnType: 2,
    rightRate: Number(
      (
        Object.values(answerData.value).filter(item => item.isRight).length /
        readMeaningSentence.value.length
      ).toFixed(2),
    ), // 正确率
    sessionId: titleData.value.sessionId,
    wordCount: titleData.value.wordCount, // 单词数量
    textId: readEssay.value[0]?.[0].textId,
    levelId: titleData.value.levelId,
    grade: titleData.value.grade,
    answers: JSON.stringify(answerData.value),
  }
})

defineOptions({
  name: 'ShortRead',
})
// 答题结束弹框
function reportSound(correctRate: number) {
  if (correctRate >= 0.99) {
    useSound(`${OSS_URL}/sound/report_100.mp3`)
  } else if (correctRate > 0) {
    useSound(`${OSS_URL}/sound/report_99.mp3`)
  } else {
    useSound(`${OSS_URL}/sound/report_0.mp3`)
  }
}
function pickAnswer(index: number, chooseData: { number: number; isRight: number }) {
  // 选择答案
  answerData.value[index] = chooseData
  sentenceDom.value.clearData()
  // if (isRight) rightNum.value++;
  if (onEnd.value) {
    // loading2.value = true;
  }
}

function init(queryData?: anyObj) {
  loading.value = true
  happyReadApi
    .shortReadBeginTrain(
      queryData || {
        grade: Number(route.query.grade),
      },
    )
    .then((res: any) => {
      if (res.data.data) {
        dealData(res.data.data)
        // 计时开始
        beginTime.value = Number(new Date())
      }
    })
    .finally(() => {
      loading.value = false
    })
}

//
function dealData(data: anyObj) {
  console.log('data', data)

  titleData.value.topic = data.text.topic
  titleData.value.wordCount = data.text.wordCount
  titleData.value.characterName = data.text.characterName || ''
  titleData.value.sessionId = data.sessionId
  titleData.value.levelId = data.levelId
  titleData.value.grade = data.grade

  if (data.understandTitle) {
    // Object.keys导致题目对象顺序变化，使用sort变回来
    readMeaningSentence.value = Object.keys(data.understandTitle)
      .sort()
      .map(item => {
        return {
          sentence: item.split(' '),
          options: data.understandTitle[item],
        }
      })
  }

  readEssay.value = data.text.paragraphs.map((item: anyObj) => item.sentenceList)
}

function clearData() {
  readMeaningSentence.value = []
  readEssay.value = []
  answerData.value = {}
  showStat.value = false
}

// 下一关
async function next() {
  loading.value = true
  showReport.value = false
  await $sleep(200)
  clearData()
  init({
    grade: titleData.value.grade,
  })
}

// 再来一次
// async function again() {
//     if (loading.value) return;
//     loading.value = true;
//     showReport.value = false;
//     const res = await getReadSessionid();
//     await $sleep(200);
//     clearCurrent();
//     titleData.value.sessionId = res.data.data;
//     loading.value = false;
// }

const wordChooseData = ref<anyObj>({})
// 答题弹框
function openWordChoose(e: anyObj) {
  wordChooseData.value = e
  showWordChoose.value = true
}

function handleBack() {
  if (showStat.value) return router.back()

  dialog.show({
    content: '将不统计本次结果，确定要退出吗？',
    ok: globalBack,
  })
}

// function clearCurrent() {
//     // 再来一次清除当前关卡记录的数据
//     // rightNum.value = 0;
//     answerData.value = {};
//     beginTime.value = Number(new Date());
//     readEssay.value.forEach(item => {
//         item.forEach((item: anyObj) => {
//             item.istranslate = false;
//         });
//     });
// }
// 提高难度或者降低难度
async function handleChangeModel() {
  showReport.value = false
  await $sleep(200)
  clearData()
  init({
    nextType: rewardData.value.nextType,
    grade: rewardData.value.nextGrade,
  })
}

function handleSeeWord(e: anyObj) {
  Object.assign(searchWord.value, e)
  showPop.value = true
}
// 点击遮罩层触发
function handleMaskClick() {
  showPop.value = false
}
function tapExpand(val: boolean) {
  showPop.value = false
}

function closeReport() {
  showReport.value = false
  // showStat.value = true;
}

function handlePostData() {
  if (loadingBtn.value) return
  loadingBtn.value = true
  postData.value.learnTime = Math.floor((Number(new Date()) - beginTime.value) / 1000)
  happyReadApi.readingLearnRecord(postData.value).then((res: any) => {
    if (res.data.data) {
      // Object.assign(rewardData.value, res.data.data);
      rewardData.value.diamond = res.data.data.diamond
      rewardData.value.exp = res.data.data.exp
      rewardData.value.nextType = res.data.data.nextType
      if (res.data.data.nextGrade) {
        rewardData.value.nextGrade = res.data.data.nextGrade
      }
      reportSound(postData.value.rightRate)
      // showReport.value = true;
      showStat.value = true
      loadingBtn.value = false
    }
  })
}

// 查看记录
function getDetail(id: any) {
  happyReadApi
    .getReadRecoredDetail({
      id: id,
    })
    .then((res: any) => {
      console.log(res)
      if (res.data.data.answers) {
        showStat.value = true
        answerData.value = JSON.parse(res.data.data.answers)
        dealData(res.data.data)
      } else {
        XMessage.error('暂无答题记录')
        router.back()
      }
    })
}

onMounted(() => {
  if (route.query.id) {
    getDetail(route.query.id as string)
    return
  }
  init()
})
</script>
<template>
  <div class="page">
    <!-- <BackBar leftText="短篇阅读" class="backBar" /> -->
    <div class="backBar" @click="handleBack">
      <Icon name="left_arrow" size="80"></Icon>
      <LineFont text="短篇阅读" />
    </div>

    <div class="content">
      <div class="title">
        <span :class="['normal', ['grade', 'one', 'two'][titleData.grade]]">
          {{
            (['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'][titleData.grade] ||
              '') + '阶'
          }}
        </span>
        <span class="topic">
          {{ titleData.topic }}
        </span>
      </div>
      <board-bg class="article">
        <div v-if="!loading" class="left">
          <sentence
            ref="sentenceDom"
            needAnswer
            :characterName="titleData.characterName"
            :showNext="showStat"
            :data="readEssay"
            @seeWord="handleSeeWord"
            @open="openWordChoose"
          ></sentence>
        </div>
        <div v-if="!loading" class="right">
          <div
            v-for="(item, index) in readMeaningSentence || []"
            :key="index"
            class="sentence-item"
          >
            <ReadMeaningSentence
              :isEnd="onEnd"
              :data="item"
              :index="index"
              :showNext="showStat"
              :answer="answerData[index]"
              @chooseAnswer="pickAnswer(index, $event)"
              @seeWord="handleSeeWord"
            />
          </div>
        </div>
        <div v-if="loading" class="loading">
          <Icon name="global_loading" loading size="96" />
        </div>
      </board-bg>
    </div>
    <ReportDia
      v-model="showReport"
      :data="{
        rewardData: rewardData,
        rate: postData.rightRate,
        readCount: titleData.wordCount,
        readTime: secondsToTime(postData.learnTime),
      }"
      @changeModel="handleChangeModel"
      @back="closeReport"
      @next="next"
    />
    <!-- <div v-if="showWordChoose" class="wordChoose">
            <WordChoose
                v-model="showWordChoose"
                v-bind="wordChooseData"
                @handleError="() => chooseNumber++"
                @handleRight="
                    () => {
                        chooseNumber++;
                        rightNum++;
                    }
                "
                @handleSurrender="() => chooseNumber++"
                @changeStrange="(e: number) => (wordChooseData.strangeWord = e ? 0 : 1)"
            />
        </div> -->
    <div class="wordDetailPopup">
      <van-popup v-model:show="showPop" position="bottom" @maskClick="handleMaskClick">
        <SearchWordPup
          v-if="showPop"
          :wordId="searchWord.id"
          :wordSpell="searchWord.word"
          :closed="false"
          @tapDown="tapExpand(false)"
        ></SearchWordPup>
      </van-popup>
    </div>
    <div
      v-if="showStat && !route.query.id"
      class="nextBtn animate__slideInLeft pointer"
      :style="{
        background: read_statistics,
      }"
      @click="() => (showReport = true)"
    >
      <!-- <Icon name="double_arrow_right_black"></Icon> -->
      <!-- <div class="text">统计</div> -->
    </div>
    <Btn
      v-if="onEnd && !showStat"
      width="386"
      height="108"
      size="48"
      :loading="loadingBtn"
      class="postBtn pointer"
      @click="handlePostData"
      >提交答案</Btn
    >
  </div>
</template>
<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  @include main_bg;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .backBar {
    position: absolute;
    display: flex;
    align-items: center;
    left: $space-6;
    top: 2.67vh;
    cursor: pointer;
    .x-icon {
      margin-right: $space-3;
    }
  }

  .content {
    width: 1880px;
    height: 84.83vh;
    display: flex;
    // background: v-bind(loadBg);
    position: relative;
    // margin-top: 4.17vh;
    padding: 6vh 40px 0;
    z-index: 2;

    .article {
      width: 100%;
      height: 82vh;
      padding-top: 2vh;

      :deep(.board-content) {
        gap: 128px;
        flex-direction: row;
        justify-content: center;
      }
    }

    .title {
      min-width: 300px;
      height: 9vh;
      background: #faffff;
      border-radius: 3.33vh 3.33vh 0 0;
      position: absolute;
      top: -2.83vh;
      left: 50%;
      transform: translateX(-50%);
      font-family: $font-special;
      font-size: 3.33vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 48px;

      .normal {
        border-radius: 1.17vh;
        padding: 0 20px;
        line-height: 6vh;
        margin-right: 16px;
        background-color: #801fff;
        color: white;
        width: 126px;
        flex-shrink: 0;

        &.one {
          background-color: #99d609;
        }
        &.two {
          background-color: #ffa51f;
        }
      }
      .topic {
        text-wrap: nowrap;
        width: max-content;
      }
    }
    .left {
      width: 768px;
      height: 72vh;
    }
    .right {
      padding: 2.67vh;

      height: 70.42vh;
      width: 800px;
      // margin-left: 64px;
      border-radius: 1.67vh;
      border: 0.33vh solid #d6f2ff;

      overflow-y: auto;
      &::-webkit-scrollbar {
        width: 8px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 0.33vh;
        background: #fff78c;
      }

      &::-webkit-scrollbar-track {
        border-radius: 0.5vh;
        background: rgba(0, 0, 0, 0.05);
      }
      :deep(.sentence-item) {
        &:first-child {
          .readSentence {
            margin: 0;
          }
        }
      }
    }
    .loading {
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.wordChoose {
  position: absolute;
  background-color: #fff;
  z-index: 999;
  width: 100vw;
  height: 100vh;
}
.nextBtn {
  width: 88px;
  height: 25vh;
  position: absolute;
  right: 26px;
  top: 43%;
  transform: translateY(-50%);
  animation-duration: 0.5s;
  animation-fill-mode: both;
  z-index: 10;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .text {
    font-size: 1.83vh;
    font-weight: 600;
    line-height: 4.17vh;
    width: 20px;
    // margin-top: 20px;
  }
}
:deep(.postBtn) {
  position: absolute;
  z-index: 9;
  display: flex;
  align-items: center;
  justify-content: center;
  top: 88%;
  font-family: $font-special;
  font-size: 4vh;
  font-weight: 400;
  color: $font-color;
  .x-icon {
    top: 0;
  }
}
</style>
