<script>
export default {
  name: "Question",
};
</script>
<script setup>
import { onMounted, ref } from "vue";
import { NumToLetter, hookCopy } from "@/utils";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import animate from "animejs/lib/anime.es.js";

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  index: Number | String,
  showMore: {
    type: Boolean,
    default: true,
  },
  showAnswer: {
    type: Boolean,
    default: false,
  },
  child: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits([
  "onCollect",
  "onCombination",
  "onQuote",
  "onKnowledge",
  "onAnalysis",
]);

const { paperQuestionIds } = storeToRefs(usePaperStore());

const difficultyType = {
  11: "容易",
  12: "较易",
  13: "普通",
  14: "较难",
  15: "困难",
};

const selected = computed(
  () => paperQuestionIds.value?.includes(props.data.id) || false
);

function onClickQuote(data) {
  emits("onQuote", data);
}

function onClickKnowledge(data) {
  emits("onKnowledge", data, props.data);
}

function handleAnalysis(data) {
  // 选中不隐藏
  if (window.getSelection().toString().length) return;
  emits("onAnalysis", data);
  data.show = !data.show;
}

const collectLoading = ref(false);
function handleCollect(data) {
  collectLoading.value = true;
  emits("onCollect", data, () => {
    collectLoading.value = false;
  });
}

const questionRef = ref();
function handleCombination(data) {
  emits("onCombination", data, selected.value);
  // const itemRect = questionRef.value.getBoundingClientRect();
  // const cartRect = cartDom.getBoundingClientRect();

  // 动态克隆一个 item 元素，避免影响原始位置
  // const clone = questionRef.value.cloneNode(true);
  // document.body.appendChild(clone);
  // clone.style.width = `${itemRect.width}px`;
  // clone.style.position = "fixed";
  // clone.style.left = `${itemRect.left}px`;
  // clone.style.top = `${itemRect.top}px`;
  // clone.style.zIndex = 10000;
  // // 抛物线的控制点
  // const controlX = (itemRect.left + cartRect.left) / 2;
  // const controlY = itemRect.height * -0.5; // 抛物线的高度
  // 购物篮抖一下
  // animate({
  //   targets: cartDom,
  //   scale: [1.3, 0.9, 1],
  //   easing: "easeInOutQuad",
  // delay: 500,
  // });
  // 使用 anime.js 动画
  // animate({
  //   targets: clone,
  //   duration: 1500,
  //   easing: "easeInOutQuad",
  //   keyframes: [
  //     {
  //       translateX: controlX - itemRect.left,
  //       translateY: controlY - itemRect.top,
  //       scale: 0.1, // 中途缩小
  //       opacity: 0.1,
  //     },
  //     {
  //       // translateX: cartRect.left - itemRect.left,
  //       translateY: controlY,
  //       scale: 0, // 最终缩小
  //       opacity: 0,
  //     },
  //   ],
  //   complete: () => {
  //     document.body.removeChild(clone); // 动画完成后移除克隆元素
  //   },
  // });
}

function getQuestion() {
  hookCopy(JSON.stringify(props.data), "试题信息复制成功");
}
</script>

<template>
  <div ref="questionRef" class="questions-item" :id="data.id">
    <div v-if="showMore" class="questions-item-title">
      <span>{{ data.type }}</span
      >|<span>{{ difficultyType[data.difficulty] }}</span
      >|<span>组卷{{ data.groupCount || 0 }}次</span>
      <template v-if="data.quotes.length">
        |
        <el-popover
          placement="bottom-start"
          trigger="hover"
          popper-class="paper-popover"
        >
          <template #reference>
            <span style="cursor: pointer"
              >引用（{{ data.quotes.length }}）</span
            >
          </template>
          <p v-for="quote in data.quotes" :key="quote">
            <el-link :underline="false" @click="onClickQuote(quote)">
              {{ quote.paperName }}</el-link
            >
          </p>
        </el-popover>
      </template>
    </div>
    <div @click="handleAnalysis(data)">
      <div
        :class="{
          'questions-item-content': true,
          'is-row': !data.title,
          inline: child || data.score == null,
        }"
      >
        <div v-if="!(index == null)" class="questions-item-content-index">
          <template v-if="!child"> {{ index }}. </template>
          <template v-else-if="data.options?.[0]?.length">
            （{{ index }}）
          </template>
          {{ data.score == null ? "" : `（${data.score}分）` }}
        </div>
        <div class="questions-item-content-title" v-html="data.title"></div>
      </div>
      <audio
        v-if="data.voiceUrl"
        :src="data.voiceUrl"
        controls
        style="margin-top: 8px"
      ></audio>
      <div class="questions-item-content-child">
        <Question
          v-for="(item, idx) in data.children"
          :key="item.id"
          :data="item"
          :index="`${idx + 1}`"
          :showMore="false"
          :showAnswer="data.show"
          child
        ></Question>
      </div>
      <div
        v-if="data.options?.[0]?.length"
        :class="{
          'questions-item-options': true,
          'is-row': !data.title,
        }"
        :style="{
          marginTop: !data.title ? '0px' : '8px',
        }"
      >
        <div
          class="option-row"
          v-for="(opt, optIdx) in data.options"
          :key="opt"
        >
          <div v-if="data.options.length > 1" class="option-row-index">
            ({{ optIdx + 1 }})
          </div>
          <div class="option-row-content">
            <div
              :class="{
                option: true,
                'option-long': opt[0].length > 40,
                correct: data.answer?.split(',').includes(NumToLetter[oIdx]),
              }"
              v-for="(o, oIdx) in opt"
            >
              <div class="option-content">
                <div class="option-index">{{ NumToLetter[oIdx] }}.</div>
                <div v-html="o"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="questions-item-answer" v-if="child ? showAnswer : data.show">
        <div v-if="data.knowledge?.length" class="questions-item-answer-row">
          <el-tag type="info">知识点</el-tag>
          <div class="tags">
            <el-link
              v-for="k in data.knowledge"
              :key="k.id"
              :underline="false"
              @click.stop="onClickKnowledge(k)"
            >
              {{ k.knowledgeName }}</el-link
            >
          </div>
        </div>
        <div
          v-if="
            data.answer &&
            !data.options?.[0]?.length &&
            !data.children?.[0].options?.[0]?.length
          "
          class="questions-item-answer-row"
        >
          <el-tag type="success">答案</el-tag>
          <span v-html="data.answer"></span>
        </div>
        <div
          v-if="data.analyze.length || data.analyzePic"
          class="questions-item-answer-row"
        >
          <el-tag type="primary">解析</el-tag>
          <div>
            <template v-if="data.analyze">
              <span v-for="a in data.analyze" :key="a" v-html="a"></span>
            </template>
            <el-image v-if="data.analyzePic" :src="data.analyzePic"></el-image>
          </div>
        </div>
      </div>
      <div
        v-html="
          `${
            data.sourceName
              ? `<span style='color:#409EFF;margin-right:4px;'>${data.sourceName}</span>`
              : ''
          }`
        "
      ></div>
    </div>
    <div v-if="showMore" class="questions-item-tool">
      <div>
        <template v-if="!(data.scoreRate == null)">
          最近一次得分率：{{ data.scoreRate / 100 }}%
        </template>
      </div>
      <div class="btns">
        <el-button @click="handleAnalysis(data)">
          {{ data.show ? "收起" : "解析" }}</el-button
        >
        <el-button :loading="collectLoading" @click="handleCollect(data)">{{
          data.collectFlag === 0 ? "收藏" : "取消收藏"
        }}</el-button>
        <el-button
          :type="selected ? 'danger' : 'primary'"
          @click="handleCombination(data)"
          >{{ selected ? "移除" : "添加" }}</el-button
        >
        <el-button type="warning" @click="getQuestion()">反馈</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.questions {
  &-item {
    padding-left: 16px;
    position: relative;
    font-family: "Microsoft YaHei";
    &-title {
      border-bottom: 1px solid #eee;
      padding: 0 0 16px 0;
      span {
        display: inline-block;
        padding: 0 16px;
        color: #73767a;
        font-size: 16px;
      }
    }
    &-content {
      margin: 16px 0 8px;
      display: flex;
      flex-wrap: wrap;
      align-items: start;
      word-wrap: break-word;
      word-break: break-all;
      white-space: normal;

      &.inline {
        flex-wrap: nowrap;
        .questions-item-content-index {
          width: max-content;
        }
      }

      &-index {
        width: 100%;
        margin-right: 4px;
        white-space: nowrap;
        color: blue;
        font-size: 18px;
        line-height: 25px;
      }
      &-title {
        width: 100%;
        white-space: normal;
        word-break: break-word;
        overflow-wrap: break-word;
        line-break: auto;
        font-size: 18px;
        line-height: 25px;
      }
      // &.is-row {
      //   display: inline;
      //   // position: absolute;
      //   // top: 8px;
      //   // left: -16px;
      //   // margin-top: 0;
      //   // border: 1px solid red;
      // }
    }

    &-options {
      width: 100%;
      margin-top: 8px;
      padding: 0 16px;

      .option-row {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        &-index {
          width: 30px;
        }

        &-content {
          display: flex;
          flex-wrap: wrap;
          width: calc(100% - 30px);
          font-size: 18px;

          .option {
            width: 25%;
            max-width: 25%;
            box-sizing: border-box;
            display: flex;
            padding: 0 16px 16px 0;

            &-index {
              width: 22px;
              margin: 2px 8px 0 0;
              word-break: break-all;
            }

            &-content {
              display: flex;
              align-items: center;
              width: max-content;
              padding: 8px;
              overflow: auto;
              word-wrap: break-word;
              word-break: break-word;
              white-space: normal;
            }
          }

          .option-long {
            width: calc(50% - 16px);
          }

          .correct {
            // .option-index {
            //   color: #67c23a;
            // }
            .option-content {
              background: #00b050;
              border-radius: 8px;
              color: #fff;
            }
          }
        }
      }

      &.is-row {
        width: calc(100% - 20px);
        margin-left: 20px;
      }
    }

    &-answer {
      &-row {
        display: flex;
        margin-bottom: 16px;
        min-height: 24px;
        .el-tag {
          margin-right: 16px;
        }
        .tags {
          .el-link {
            margin: 0 12px 0 0;
          }
        }
        & > div {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          span {
            width: 100%;
            display: inline-block;
            line-height: 1.5em;
            margin-bottom: 8px;
            font-size: 18px;
          }
        }
      }
    }

    &-tool {
      margin-top: 16px;
      border-top: 1px solid #eee;
      padding-top: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
<style>
ol {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
p,
span {
  margin: 0;
  line-height: 24px;
}
</style>
