<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import Question from "@/components/Question";
import { NumToChineseNumerals } from "@/utils";
import draggable from "vuedraggable";
import PaperAnalysisDia from "../components/PaperAnalysisDia";
import { useRouter } from "vue-router";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import { formatTitleToPaper } from "@/utils";
import {
  getSubjectPaperById,
  updateSubjectPaperCollect,
  getPaperAnalyzeById,
  updateSubjectTitleCollect,
} from "@/api";
import { ElMessageBox } from "element-plus";

const paper = ref({});

const { paperQuestionIds, search, paperConfig } = storeToRefs(usePaperStore());
const {
  clearPaper,
  addQuestions,
  removeQuestions,
  switchFilter,
  jumpToKnowledge,
} = usePaperStore();

const router = useRouter();

const showAnswer = ref(false); // 是否全部展开解析
const showAnalysis = ref(false); // 是否打开分析弹窗
const analysisData = ref();

function toggleAnswer(show = null) {
  switchAnswer(paper.value.content);
  function switchAnswer(data) {
    for (let i of data) {
      if (i.children && i.children.length > 0) {
        switchAnswer(i.children);
      } else {
        if (show == null) {
          i.show = !i.show;
        } else {
          i.show = show;
        }
      }
    }
  }
}

async function onCollect() {
  try {
    await updateSubjectPaperCollect({
      stagePid: paper.value.stagePid,
      subjectId: paper.value.subjectId,
      paperId: paper.value.id,
    });
    paper.value.collectFlag === 0
      ? (paper.value.collectFlag = 1)
      : (paper.value.collectFlag = 0);
  } catch (err) {
    console.log(err);
  }
}

const showLoading = ref(false);
async function showAnalyzeDia() {
  showLoading.value = true;
  try {
    const res = await getPaperAnalyzeById(paper.value.id);
    analysisData.value = res.data;
    showAnalysis.value = true;
  } catch (err) {
    console.log(err);
  } finally {
    showLoading.value = false;
  }
}

async function onCopy() {
  await ElMessageBox.confirm(
    "当前试卷禁止编辑，平行组卷将清空试题篮，是否继续？",
    "提示",
    { type: "warning" }
  );
  clearPaper(false);
  paper.value.content.forEach((i) => {
    addQuestions(i.children);
  });
}

// 收藏
async function onCollectTitle(data) {
  try {
    await updateSubjectTitleCollect({
      stagePid: data.stagePid,
      subjectId: data.subjectId,
      titleId: data.id,
    });
    data.collectFlag === 0 ? (data.collectFlag = 1) : (data.collectFlag = 0);
  } catch (err) {
    console.log(err);
  }
}

async function handleClick(type, data, val) {
  switch (type) {
    case 1:
      const questions = [];
      paper.value.content.forEach((i) => questions.push(...i.children));
      await addQuestions(questions);
      break;
    case 2:
      showAnswer.value = !showAnswer.value;
      toggleAnswer(showAnswer.value);
      // 拉取解析
      break;
    case 3:
      onCollect();
      break;
    case 4:
      showAnalyzeDia();
      break;
    case 5:
      onCopy();
      break;
    case 6:
      data.show = !data.show;
      break;
    case 7:
      onCollectTitle(data);
      break;
    case 8:
      if (val) {
        removeQuestions([data]);
      } else {
        addQuestions([data]);
      }
      break;
    case 9:
      addQuestions(data.children);
      break;
  }
}

const loading = ref(false);
async function init() {
  loading.value = true;
  try {
    const id = router.currentRoute.value.query.id;

    const { data: res } = await getSubjectPaperById(id);

    paper.value = {
      id: res.id,
      name: res.name,
      updateTime: res.updateTime,
      type: res.typeName,
      lookNum: res.lookNum,
      total: res.titleCount,
      score: res.paperScore,
      difficulty: res.paperDifficulty,
      stagePid: res.stagePid,
      subjectId: res.subjectId,
      collectFlag: res.collectFlag,
      category: res.category,
      content: res.contentDetails.map((i) => ({
        id: i.contentId,
        type: i.contentName,
        score: i.contentScore,
        children: formatTitleToPaper(i.titleList),
      })),
    };
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

function scrollToElement(id) {
  const element = document.getElementById(id);
  if (element) {
    const offset = 200;
    const elementPosition =
      element.getBoundingClientRect().top + window.pageYOffset;
    const offsetPosition = elementPosition - offset;

    window.scrollTo({
      top: offsetPosition,
      behavior: "smooth",
    });

    element.parentNode.style.transition = "all 0.5s linear";
    element.parentNode.style.backgroundColor = "#ecf5ff";
    setTimeout(() => {
      element.parentNode.style.backgroundColor = "";
    }, 1000);
  }
}

// 知识点跳转
async function onKnowledge(data, qData) {
  const { stagePid, subjectId } = qData;
  if (
    search.value.stagePid !== stagePid ||
    search.value.subjectId !== subjectId
  ) {
    await ElMessageBox.confirm(
      `知识点不属于${paperConfig.value.subjectName}${paperConfig.value.chapterName}, 是否切换知识点对应的阶段学科（将清空试题篮）`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
  }
  search.value.stagePid = stagePid;
  search.value.subjectId = subjectId;
  await nextTick();
  router.push("/paper/basket");
  switchFilter(1);
  jumpToKnowledge(data);
}

onMounted(() => {
  init();
});
</script>

<template>
  <div class="combination" v-loading="loading">
    <div class="combination-left">
      <div class="box paper-title">
        <div class="paper-title-main">
          <div>{{ paper.name }}</div>
        </div>
        <div class="paper-title-info">
          <!-- <span>更新时间：{{ paper.updateTime }}</span
          > -->
          <span>浏览次数：{{ paper.lookNum }}</span
          ><span v-if="paper.type"
            >类型：
            {{ paper.type }}
          </span>
        </div>
      </div>
      <div class="box paper-content">
        <div
          class="paper-groups"
          v-for="(item, idx) in paper.content"
          :key="item.id"
        >
          <div class="paper-group-title">
            <div>
              {{ NumToChineseNumerals[idx] }}、
              <span v-html="item.type"></span>
              {{ `（${item.score || 0}分）` }}
            </div>
            <el-button
              v-if="item.children.length"
              type="primary"
              @click="handleClick(9, item)"
              >添加分类下所有题到试题篮</el-button
            >
          </div>
          <div class="paper-group-questions">
            <div
              class="paper-group-questions-item"
              v-for="(q, qIdx) in item.children"
              :key="q.id"
            >
              <Question
                :data="q"
                :index="q.qNo"
                :showMore="false"
                @onKnowledge="onKnowledge"
              />
              <div class="tool">
                <el-button
                  size="small"
                  :icon="q.show ? 'Hide' : 'View'"
                  round
                  @click="handleClick(6, q)"
                ></el-button>
                <el-button
                  size="small"
                  :icon="q.collectFlag === 0 ? 'Star' : 'StarFilled'"
                  round
                  @click="handleClick(7, q)"
                ></el-button>
                <el-button
                  size="small"
                  :type="paperQuestionIds.includes(q.id) ? 'danger' : 'primary'"
                  :icon="paperQuestionIds.includes(q.id) ? 'Minus' : 'Plus'"
                  round
                  @click="handleClick(8, q, paperQuestionIds.includes(q.id))"
                ></el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-affix :offset="130">
      <div class="combination-right">
        <div class="box paper-tool">
          <el-button
            class="submit"
            size="large"
            type="primary"
            style="width: 100%"
            @click="handleClick(1)"
            >全部加入试题篮</el-button
          >
          <div class="btns">
            <el-button link type="primary" @click="handleClick(2)">{{
              showAnswer ? "折叠解析" : "展开解析"
            }}</el-button>
            <el-button
              v-if="paper.category !== 4"
              link
              type="primary"
              @click="handleClick(3)"
              >{{
                paper.collectFlag === 0 ? "收藏试卷" : "取消收藏"
              }}</el-button
            >
            <el-button
              :loading="showLoading"
              link
              type="primary"
              @click="handleClick(4)"
              >试卷分析</el-button
            >
            <el-button link type="primary" @click="handleClick(5)"
              >分值设置</el-button
            >
          </div>
        </div>
        <div class="box paper-content">
          <div class="title">
            {{ `试卷信息（${paper.score || 0} 分）` }}
          </div>
          <div class="info">
            <span>题数：{{ paper.total }}</span>
            <span
              >难度系数：{{ (paper.difficulty / 10000 || 0).toFixed(2) }}</span
            >
          </div>
          <el-scrollbar class="map" max-height="calc(100vh - 420px)">
            <div
              class="map-groups"
              v-for="(item, index) in paper.content"
              :key="item.id"
            >
              <div class="map-group-title">
                <div>
                  {{ NumToChineseNumerals[index] }}、
                  <span v-html="item.type"></span>
                  {{ `（${item.score || 0}分）` }}
                </div>
              </div>
              <div class="map-group-questions">
                <el-button
                  v-for="(q, qIdx) in item.children"
                  @click="scrollToElement(q.id)"
                  >{{ q.qNo }} {{ `（${q.score || 0}分）` }}</el-button
                >
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </el-affix>
  </div>
  <PaperAnalysisDia v-model="showAnalysis" :data="analysisData" />
</template>

<style lang="scss" scoped>
.combination {
  display: flex;
  padding: 16px;

  .box {
    background: #fff;
    padding: 16px;
    margin-bottom: 16px;
    border-radius: 4px;
  }
  .sortable-ghost {
    background: #ecf5ff !important;
    color: #73767a !important;
    border-radius: 4px;
  }

  &-left {
    flex: 1;
    margin-right: 16px;

    .paper {
      &-title {
        min-height: 134px;
        text-align: center;
        &-info {
          color: #73767a;
          font-size: 14px;
          display: flex;
          justify-content: space-around;
          margin-top: 30px;
        }
        &-main {
          margin-top: 12px;
          text-align: center;
          font-weight: bold;
          font-size: 20px;
          div {
            width: 80%;
            margin: 0 auto;
          }
        }
      }
      &-groups {
        .paper-group-title {
          padding-bottom: 16px;
          font-weight: bold;
          font-size: 18px;
          display: flex;
          justify-content: space-between;
        }
        .paper-group-questions {
          &-item {
            border: 1px solid transparent;
            background: #fff;
            margin-bottom: 40px;
            padding: 16px;
            position: relative;
            transition: border 0.3s linear;
            &:hover {
              border: 1px solid var(--el-color-primary);
              border-radius: 4px;
              .tool {
                opacity: 1;
                visibility: visible;
              }
            }

            :deep(.questions-item-content) {
              margin-top: 0;
            }

            .tool {
              position: absolute;
              top: calc(100% + 8px);
              right: 0;
              opacity: 0;
              visibility: hidden;
              transition: all 0.3s linear;
            }
          }
        }
      }
    }
  }
  &-right {
    width: 380px;

    .paper-tool {
      height: 134px;
      text-align: center;
      .submit {
        margin-top: 12px;
      }
      .btns {
        margin-top: 16px;
      }
    }

    .paper-content {
      padding: 16px 0;
      .title {
        font-size: 20px;
        font-weight: bold;
        padding: 0 16px;
      }
      .info {
        display: flex;
        justify-content: space-between;
        margin: 16px 0;
        font-size: 14px;
        color: #73767a;
        padding: 0 16px;
      }
      .map {
        padding: 0 16px;

        .map-groups {
          border: 1px solid transparent;
          margin-bottom: 32px;
          padding: 8px;
          .map-group {
            &-title {
              padding-bottom: 16px;
              font-weight: bold;
              font-size: 18px;
            }
            &-questions {
              display: flex;
              flex-wrap: wrap;
              .el-button {
                margin-bottom: 12px;
                &:first-child {
                  margin-left: 12px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
