<script setup lang="ts">
import HuliApi, { AnswerItem, AnswerStart } from '@/api/huli/HuliApi';
import Tiite from '@/assets/images/Answer/Tiite.png';
import PageLeftTitleRightContent from '@/components/parts/PageLeftTitleRightContent.vue';
import SimplePageContentLoader from '@/components/SimplePageContentLoader.vue';
import Box2 from '@/components/small/Box2.vue';
import { useSimpleDataLoader } from '@/composeable/SimpleDataLoader';
import { RandomUtils, waitTimeOut } from '@imengyu/imengyu-utils';
import { ScrollRect } from '@imengyu/vue-scroll-rect';
import { message } from 'ant-design-vue';
import { computed, reactive, ref } from 'vue';

const userName = ref(RandomUtils.genNonDuplicateID(6));
const isAnswer = ref(false);
const isShowRank = ref(false);
const currentDate = ref<AnswerStart>();
const currentSelectIndex = ref(-1);
const currentQuestion = ref<AnswerItem>();
const currentState = ref(-1);
const currentScore = reactive({
  correctCount: 0,
  wrongCount: 0,
  totalCount: 0,
  score: 0,
  finished: true,
});
const rankListData = useSimpleDataLoader(async () => {
  return (await HuliApi.getAnswerRankList());
}, false);
const myRank = computed(() => {
  if (!rankListData.content.value)
    return '0';
  const listIndex = rankListData.content.value.findIndex((item) => item.name === userName.value);
  if (listIndex === -1)
    return '99+';
  return (listIndex + 1).toString();
})

function showRank() {
  isShowRank.value = true;
  rankListData.loadData(undefined, true);
}
async function quitAnswer() {
  isAnswer.value = false;
  isShowRank.value = false;
}
async function goAnswer() {
  isAnswer.value = true;
  currentSelectIndex.value = -1;
  currentScore.correctCount = 0;
  currentScore.wrongCount = 0;
  currentScore.finished = false;
  currentDate.value = await HuliApi.answerStart();
  currentScore.totalCount = currentDate.value.leftCount;
  await nextQuestion();
}
async function nextQuestion() {
  if (currentState.value !== -1)
    return;
  if (currentSelectIndex.value === -1 && currentQuestion.value) {
    message.info('请选择一个答案');
    return;
  }
  if (currentQuestion.value) {
    currentState.value = await HuliApi.answerSubmit(currentSelectIndex.value) === 'answer' ? 1 : 0;
    if (currentState.value === 1)
      currentScore.correctCount++;
    else
      currentScore.wrongCount++;
    await waitTimeOut(1000);
    currentState.value = -1;
  }

  if (currentQuestion.value?.leftCount === 0) {
    currentScore.score = Math.floor(currentScore.correctCount * 100 / (currentScore.correctCount + currentScore.wrongCount));
    currentScore.finished = true;
    await HuliApi.answerComplete(userName.value);
  } else {
    currentSelectIndex.value = -1;
    currentQuestion.value = await HuliApi.answerNext();
  }
}

</script>

<template>
  <PageLeftTitleRightContent :box="false">
    <template #content>
      <div class="d-flex flex-col align-center size-s color-text-second gap-s">
        <img class="w-50" :src="Tiite"  />
        <div class="d-flex flex-row justify-content-center">
          文物守护者
          <span class="ml-3 mr-3">保护文物</span>
          留下历史
        </div>
        <span>守护者 {{ userName }} 欢迎您</span>

        <Box2 v-if="isShowRank" class="list w-70 mt-3">
          <div class="d-flex flex-col p-4 bg-light text-align-center h-100">
            <div class="d-flex flex-row justify-between align-center">
              <img class="main-image-button" src="@/assets/images/IconBack.png" tabindex="0" @click="quitAnswer"></img>
              <h4>排行榜</h4>
              <div class="main-image-button"></div>
            </div>
            <ScrollRect scroll="vertical" class="flex-one">
              <SimplePageContentLoader :loader="rankListData">
                <div class="d-flex flex-column">
                  <div class="d-flex flex-row justify-between align-center size-ss color-text-second p-3 border-bottom-forth">
                    <p>您的排名 {{ myRank }} 分数：{{ currentScore.score }}</p>
                  </div>
                  <div 
                    class="d-flex flex-row justify-between align-center size-ss color-text-second p-3 border-bottom-forth cursor-pointer" 
                    v-for="(item, key) in rankListData.content.value" 
                    :key="key"
                  >
                    <div class="d-flex flex-row align-center">
                      <span class="p-2 bg-light border-all-dark mr-3">{{ key + 1 }}</span>

                      <img class="logo" v-if="key==0" src="@/assets/images/Answer/No1.png" />
                      <img class="logo" v-else-if="key==1" src="@/assets/images/Answer/No2.png" />
                      <img class="logo" v-else src="@/assets/images/Answer/Logo.png" />

                      <span class="ml-3">{{ item.name }}</span>

                    </div>
                    <span>
                      <span class="size-s mr-2">{{ item.score }}分</span>
                      <span>{{ item.costTime }}</span>
                    </span>
                  </div>
                </div>
              </SimplePageContentLoader>
            </ScrollRect>
          </div>
        </Box2>
        <Box2 v-else-if="isAnswer" class="mt-3">
          <div v-if="currentScore.finished" class="d-flex flex-col p-4 bg-light text-align-center">
            <h3>答题结束</h3>
            <hr class="w-100 mt-3 mb-3" />
            <h3>您的得分：{{ currentScore.score }}</h3>
            <p>共计{{ currentScore.totalCount }}题，您答对了 {{ currentScore.correctCount }} 道题！</p>

            <button class="mt-3" @click="showRank">查看排行榜</button>
          </div>
          <div v-else class="d-flex flex-col p-4 bg-light">
            <img class="main-image-button" src="@/assets/images/IconBack.png" tabindex="0" @click="quitAnswer"></img>
            <template v-if="currentQuestion">
              <div class="d-flex flex-row justify-content-between align-center mt-3">
                <span class="border-all-dark p-2 mr-3 flex-shrink-0">{{ currentQuestion.seq }} / {{ currentQuestion.leftCount }}</span>
                <span>{{ currentQuestion.title }}</span>
              </div>
              <hr class="w-100 mt-3 mb-3" />
              <div class="d-flex flex-row flex-wrap justify-content-between gap-ll">
                <button 
                  v-for="(item, index) in currentQuestion.optionList"
                  :key="index" 
                  :class="[
                    'flex-shrink-0 m-0',
                    currentSelectIndex === index ? 'bg-primary color-pure' : '',
                    currentSelectIndex === index ? (currentState === 1 ? 'bg-success color-pure' : currentState === 0 ? 'bg-danger color-pure' : '') : '',
                  ]" 
                  style="width:calc(50% - 40px);height: 15vh"
                  @click="currentSelectIndex = index"
                >
                  <span v-if="currentSelectIndex === index && currentState === 1" class="mr-2 size-l">✔</span>
                  <span v-if="currentSelectIndex === index && currentState === 0" class="mr-2 size-l">❌</span>
                  {{ item.label }}
                </button>
              </div>
              <hr class="w-100 mt-3 mb-3" />
              <div class="d-flex flex-row justify-content-between">
                <button @click="nextQuestion">下一题</button>
              </div>
            </template>
          </div>
        </Box2>
        <button v-else class="mt-4" @click="goAnswer">开始答题</button>
      </div>
    </template>
  </PageLeftTitleRightContent>
</template>

<style lang="scss" scoped>
.list {
  height: 60vh;
}
.logo {
  width: 60px;
  height: 60px;
}
</style>