<script setup>
import { ref, reactive, onMounted } from "vue";
import Question from "@/components/Question";
import { NumToChineseNumerals, formatTitleToPaper } from "@/utils";
import draggable from "vuedraggable";
import PaperAnalysisDia from "../components/PaperAnalysisDia";
import ScoreSettingDia from "../components/ScoreSettingDia";
import { useRouter } from "vue-router";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import { syncPaperAnalyze, savePaper, getPaperAnalyzeByContent } from "@/api";

const { proxy } = getCurrentInstance();

const {
  paper,
  questionTotal,
  questionDifficulty,
  paperTotalScore,
  paperInitName,
} = storeToRefs(usePaperStore());
const {
  toggleAnswer,
  clearQuestionGroup,
  clearQuestion,
  clearPaper,
  updateQNum,
  addQuestions,
} = usePaperStore();

const router = useRouter();

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

const drag = ref(false);
const expandLoad = ref(false);
const setLoad = ref(false);
async function handleClick(type) {
  switch (type) {
    case 1:
      onSave();
      break;
    case 2:
      expandLoad.value = true;
      try {
        await syncAnalyze();
        showAnswer.value = !showAnswer.value;
        toggleAnswer(showAnswer.value);
      } catch (err) {
        console.log(err);
      } finally {
        expandLoad.value = false;
      }
      break;
    case 3:
      router.push("/paper/basket");
      break;
    case 4:
      getAnalysis();
      break;
    case 5:
      setLoad.value = true;
      try {
        await syncAnalyze();
        showSetting.value = true;
      } catch (err) {
        console.log(err);
      } finally {
        setLoad.value = false;
      }
      break;
  }
}

const firstLoad = ref(true);
async function syncAnalyze() {
  if (!firstLoad.value) return;
  // 同步解析
  const { stagePid, subjectId } = paper.value.content[0].children[0];
  const baseIdList = [];
  for (const item of paper.value.content) {
    for (const title of item.children) {
      baseIdList.push(title.baseId);
    }
  }
  const res = await syncPaperAnalyze({
    stagePid,
    subjectId,
    baseIdList,
  });
  firstLoad.value = false;
  addQuestions(formatTitleToPaper(res.data), true);
}

function genParams() {
  return {
    name: paper.value.name,
    titleCount: questionTotal.value,
    score: paperTotalScore.value,
    difficulty: questionDifficulty.value,
    infoBoList: paper.value.content.map((i) => ({
      chanelTypeId: i.typeId,
      name: i.type,
      score: i.score,
      titleBoList: i.children.map((j) => ({
        titleId: j.id,
        stagePid: j.stagePid,
        subjectId: j.subjectId,
        score: j.score,
      })),
    })),
  };
}

async function onSave() {
  await savePaper(genParams());
  proxy.$tab.closePage(router.currentRoute.value);
  clearPaper(false);
  router.push("/paper/myPaper");
}

const loading = ref(false);
const analysisData = ref();
async function getAnalysis() {
  loading.value = true;
  try {
    const res = await getPaperAnalyzeByContent(genParams());
    analysisData.value = res.data;
    showAnalysis.value = true;
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

function onChange(val) {
  if (!val) {
    paper.value.name = paperInitName.value;
  }
}

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);
  }
}

onMounted(() => {
  console.log(paper);
});

const message = [
  "vue.draggable",
  "draggable",
  "component",
  "for",
  "vue.js 2.0",
  "based",
  "on",
  "Sortablejs",
];
const dragOptions = ref({
  animation: 200,
  group: "description",
  disabled: false,
  ghostClass: "ghost",
});
const list = ref(message.map((name, index) => ({ name, order: index + 1 })));
</script>

<template>
  <div class="combination">
    <div class="combination-left">
      <div class="box paper-title">
        <el-input
          v-model="paper.name"
          size="large"
          maxlength="90"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 2 }"
          resize="none"
          placeholder="请输入试卷名称"
          @change="onChange"
        ></el-input>
      </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">
            {{ NumToChineseNumerals[idx] }}、 {{ item.type }}
          </div>
          <div class="paper-group-questions">
            <draggable
              v-model="item.children"
              item-key="id"
              :component-data="{
                type: 'transition-group',
                name: !drag ? 'flip-list' : null,
              }"
              :animation="200"
              @start="drag = true"
              @end="
                () => {
                  drag = false;
                  updateQNum();
                }
              "
            >
              <template #item="{ element, index }">
                <div class="paper-group-questions-item">
                  <Question
                    :data="element"
                    :index="element.qNo"
                    :showMore="false"
                  />
                  <div class="tool">
                    <el-button
                      size="small"
                      type="danger"
                      icon="Delete"
                      round
                      @click="clearQuestion(element, item)"
                    ></el-button>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </div>
      </div>
    </div>
    <el-affix :offset="130">
      <div class="combination-right">
        <div v-if="paper.content.length" 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
              :loading="setLoad"
              link
              type="primary"
              @click="handleClick(5)"
              >分值设置</el-button
            >
            <el-button
              :loading="expandLoad"
              link
              type="primary"
              @click="handleClick(2)"
              >{{ showAnswer ? "折叠解析" : "展开解析" }}</el-button
            >
            <el-button link type="primary" @click="handleClick(3)"
              >继续选题</el-button
            >
            <el-button link type="primary" @click="handleClick(4)"
              >试卷分析</el-button
            >
          </div>
        </div>
        <div class="box paper-content">
          <div class="title">试卷信息</div>
          <div class="info">
            <span>题数：{{ questionTotal }}</span>
            <span>难度系数：{{ questionDifficulty }}</span>
          </div>
          <el-scrollbar class="map" max-height="calc(100vh - 420px)">
            <draggable
              v-model="paper.content"
              item-key="id"
              :component-data="{
                type: 'transition-group',
                name: !drag ? 'flip-list' : null,
              }"
              :animation="200"
              @start="drag = true"
              @end="
                () => {
                  drag = false;
                  updateQNum();
                }
              "
            >
              <template #item="{ element, index }">
                <div class="map-groups">
                  <div class="map-group-title">
                    {{ NumToChineseNumerals[index] }}、 {{ element.type }}
                  </div>
                  <div class="map-group-questions">
                    <draggable
                      v-model="element.children"
                      item-key="id"
                      :component-data="{
                        class: 'map-group-questions-row',
                        type: 'transition-group',
                        name: !drag ? 'flip-list' : null,
                      }"
                      :animation="200"
                      @start="drag = true"
                      @end="
                        () => {
                          drag = false;
                          updateQNum();
                        }
                      "
                    >
                      <template #item="{ element: childEle, index: QIdx }">
                        <div>
                          <el-button @click="scrollToElement(childEle.id)">{{
                            childEle.qNo
                          }}</el-button>
                        </div>
                      </template>
                    </draggable>
                  </div>
                  <div class="tool">
                    <el-button
                      size="small"
                      type="danger"
                      icon="Delete"
                      round
                      @click="clearQuestionGroup(element)"
                    ></el-button>
                  </div>
                </div>
              </template>
            </draggable>
          </el-scrollbar>
        </div>
      </div>
    </el-affix>
  </div>
  <PaperAnalysisDia v-model="showAnalysis" :data="analysisData" />
  <ScoreSettingDia v-model="showSetting" />
</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;
        display: flex;
        align-items: center;
        justify-content: center;
        .el-textarea {
          width: 80%;
          :deep(textarea) {
            text-align: center;
            font-weight: bold;
            font-size: 20px;
          }
        }
      }
      &-groups {
        .paper-group-title {
          padding-bottom: 16px;
          font-weight: bold;
          font-size: 18px;
        }
        .paper-group-questions {
          &-item {
            border: 1px solid transparent;
            background: #fff;
            margin-bottom: 40px;
            cursor: move;
            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: 330px;

    .paper-tool {
      height: auto;
      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;
          cursor: move;
          position: relative;
          transition: border 0.3s linear;

          &:hover {
            border: 1px solid var(--el-color-primary);
            border-radius: 4px;
            .tool {
              opacity: 1;
              visibility: visible;
            }
          }
          .tool {
            position: absolute;
            top: calc(100% + 4px);
            right: 0;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s linear;
          }

          .map-group {
            &-title {
              padding-bottom: 16px;
              font-weight: bold;
              font-size: 18px;
            }
            &-questions {
              &-row {
                display: flex;
                flex-wrap: wrap;
                .sortable-ghost {
                  background: transparent !important;
                }
                .el-button {
                  margin-bottom: 12px;
                  &:first-child {
                    margin-left: 12px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
