<template>
  <ie-page :safe-area-inset-bottom="false">
    <z-paging ref="paging" v-model="list" :auto="false" :safe-area-inset-bottom="true" :hide-no-more-by-limit="10"
      @query="handleQuery">
      <template #top>
        <ie-navbar title="错题本" />
        <uv-tabs :current="current" keyName="subjectName" :list="tabs" @change="handleTabChange" />
        <uv-line margin="0" />
        <date-time-picker v-model:start-date="startDate" v-model:end-date="endDate" @change="handleChange" />
      </template>
      <view v-for="item in list" :key="item.id">
        <question-book-item :data="item" :show-answer="true" @correct="handleCorrect"
          @toggleCollect="handleToggleCollect" @delete="handleDelete" />
      </view>
    </z-paging>
    <question-correct-popup ref="questionCorrectPopupRef" />
  </ie-page>
</template>

<script lang="ts" setup>
import type { Study } from '@/types';
import QuestionBookItem from '@/pagesStudy/components/question-book-item.vue';
import QuestionCorrectPopup from '@/pagesStudy/pages/exam-start/components/question-correct-popup.vue';
import DateTimePicker from '@/pagesStudy/pages/wrong-book/components/datetime-picker.vue';
import { decodeHtmlEntities } from '@/composables/useExam';
import { getStudentSubject, getWrongBookList } from '@/api/modules/study';
import useQuestionBook from '@/composables/useQuestionBook';

const list = ref<Study.FavoriteQuestionVO[]>([]);
const paging = ref<ZPagingInstance>();
const questionCorrectPopupRef = ref();
const current = ref(0);
const tabs = ref<Study.StudentSubject[]>([]);
const startDate = ref('');
const endDate = ref('');
const { isOptionCorrect, isOptionSelected, cancelCollect, collect, deleteWrongQuestion } = useQuestionBook();

const transfomeToQuestionBookVO = (list: Study.WrongBookQuestion[]): Study.FavoriteQuestionVO[] => {
  const orders = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  return list.map(item => {
    const originalOptions = [...item.options].filter(Boolean) as string[];
    const options: Study.QuestionOption[] = originalOptions.map((option, index) => {
      const cleanedOption = option.replace(/[A-Z]\./g, '').replace(/\s/g, ' ');
      return {
        name: decodeHtmlEntities(cleanedOption),
        no: orders[index],
        id: index,
        isAnswer: false,
        isCorrect: false,
        isSelected: false,
        isIncorrect: false,
        isMissed: false
      }
    });
    return {
      id: item.questionId,
      title: item.title,
      options: options,
      answers: item.answers,
      answer: decodeHtmlEntities(item.answer2 || ''),
      qtype: item.type,
      typeId: item.typeId,
      parse: decodeHtmlEntities(item.parse || ''),
      knowledge: decodeHtmlEntities(item.knowledge || ''),
      collect: item.collect || false
    }
  })
}
const handleQuery = (page: number, size: number) => {
  const queryParams: Study.WrongBookQuestionRequestDTO = {
    pageNum: page,
    pageSize: size,
    subjectId: tabs.value[current.value].subjectId,
    start: startDate.value,
    end: endDate.value
  }
  getWrongBookList(queryParams).then(res => {
    const data = transfomeToQuestionBookVO(res.rows);
    data.forEach(qs => {
      qs.options.forEach(option => {
        option.isCorrect = isOptionCorrect(qs, option);
        option.isSelected = isOptionSelected(qs, option);
        option.isMissed = !option.isSelected && option.isCorrect;
        option.isIncorrect = !option.isCorrect && option.isSelected;
      });
    });
    paging.value?.completeByTotal(data, res.total);
  });
};
const handleCorrect = (question: Study.FavoriteQuestionVO) => {
  questionCorrectPopupRef.value.open(question.id);
}
const handleToggleCollect = (question: Study.FavoriteQuestionVO) => {
  if (question.collect) {
    cancelCollect(question.id).then(res => {
      if (res) {
        paging.value?.refresh();
      }
    });
  } else {
    collect(question.id).then(res => {
      if (res) {
        paging.value?.refresh();
      }
    });
  }
}
const handleDelete = (question: Study.FavoriteQuestionVO) => {
  deleteWrongQuestion(question.id).then(res => {
    if (res) {
      paging.value?.reload();
    }
  });
}
const handleTabChange = (e: any) => {
  current.value = e.index;
  paging.value?.reload();
}
const handleChange = (e: any) => {
  paging.value?.reload();
}
const loadData = () => {
  getStudentSubject().then(res => {
    tabs.value = res.data;
    setTimeout(() => {
      paging.value?.reload();
    }, 0);
  });
}
onMounted(() => {
  loadData();
});
</script>

<style lang="scss"></style>