<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="sort-preview">
    <div class="stem">
      <span class="question-number" :style="{ fontSize: data.property.stem_question_number_font_size }">
        {{ questionNumberEndIsBracket(data.property.question_number) }}
      </span>
      <span v-html="sanitizeHTML(data.stem)"></span>
    </div>
    <div
      v-if="isEnable(data.property.is_enable_description)"
      class="description rich-text"
      v-html="sanitizeHTML(data.description)"
    ></div>
    <div
      v-for="(move_item, move_index) in move_list"
      :key="move_index"
      :class="['move-box-' + data.property.layout_type]"
    >
      <template v-if="data.property.layout_type === 'horizontal'">
        <span class="option-number" :style="{ fontSize: data.property.option_question_number_font_size }">
          {{ computeOptionMethods[data.option_number_show_mode](move_index) }}
        </span>
      </template>
      <draggable
        v-model="move_list[move_index].data_list"
        animation="300"
        :options="{
          group: { name: 'itxst', pull: 'clone' },
        }"
        :sort="!disabled"
        :class="['content-box', 'content-box-' + data.property.layout_type]"
        :group="'move' + move_index"
        @start="onStart($event)"
        @end="onEnd($event)"
      >
        <transition-group>
          <div
            v-for="(itemNode, indexNode) in move_item.data_list"
            :key="indexNode"
            :class="[
              'drag-item',
              {
                error: itemNode.mark !== data.option_list[move_index].data_list[indexNode].mark && isJudgingRightWrong,
                right: itemNode.mark === data.option_list[move_index].data_list[indexNode].mark && isJudgingRightWrong,
              },
              click_index_list.indexOf(indexNode) > -1 && select_index === move_index ? 'drag-item-active' : '',
            ]"
            @click="handleClickItem(move_index, indexNode)"
          >
            <span class="drag-content rich-text" v-html="sanitizeHTML(itemNode.content)"></span>
          </div>
        </transition-group>
      </draggable>
    </div>
    <template v-if="isShowRightAnswer && !is_all_right">
      <h4 class="right-title">正确答案：</h4>

      <template v-for="(move_item, move_index) in data.option_list">
        <div
          v-if="
            JSON.stringify(answer.answer_list[move_index].value_list) !==
            JSON.stringify(data.answer.answer_list[move_index].value_list)
          "
          :key="'answer' + move_index"
          :class="['move-box-' + data.property.layout_type]"
        >
          <template v-if="data.property.layout_type === 'horizontal'">
            <span class="option-number" :style="{ fontSize: data.property.option_question_number_font_size }">
              {{ computeOptionMethods[data.option_number_show_mode](move_index) }}
            </span>
          </template>
          <draggable
            v-model="move_list[move_index].data_list"
            animation="300"
            :options="{
              group: { name: 'itxst', pull: 'clone' },
            }"
            :sort="false"
            :class="['content-box', 'content-box-' + data.property.layout_type]"
          >
            <transition-group>
              <div
                v-for="(itemNode, indexNode) in move_item.data_list"
                :key="'answer-item' + indexNode"
                :class="['drag-item right']"
              >
                <span class="drag-content rich-text" v-html="sanitizeHTML(itemNode.content)"></span>
              </div>
            </transition-group>
          </draggable>
        </div>
      </template>
    </template>

    <div v-if="isEnable(data.property.is_enable_analysis) && isShowRightAnswer" class="analysis">
      <span class="analysis-title">解析</span>
      <div class="analysis-content" v-html="sanitizeHTML(data.analysis)"></div>
    </div>
  </div>
</template>

<script>
import Draggable from 'vuedraggable';
import PreviewMixin from './components/PreviewMixin';
import { computeOptionMethods } from '@/views/exercise_questions/data/common';

export default {
  name: 'SortPreview',
  components: { Draggable },
  mixins: [PreviewMixin],
  data() {
    return {
      computeOptionMethods,
      move_list: [], // 移动后的数组
      drag: false,
      click_index_list: [], // 点击选中的索引
      disrupted: false, // 是否打乱
      is_all_right: false, // 是否全对
      select_index: null, // 点击拖动时选中的小题数
    };
  },
  watch: {
    move_list: {
      handler(val) {
        if (!val || this.isJudgingRightWrong) return;
        this.answer.answer_list = val.map((item) => {
          let value_list = item.data_list.map((items) => {
            return items.mark;
          });
          let answer_item = {
            mark: item.mark,
            value_list,
          };
          return answer_item;
        });
      },
      deep: true,
    },
    isJudgingRightWrong: {
      handler(val) {
        if (!val) return;

        this.move_list = this.answer.answer_list.map((item, index) => {
          let data_list = item.value_list.map((itemm) => {
            return {
              ...this.data.option_list[index].data_list.find((items) => items.mark === itemm),
            };
          });
          let move_item = {
            mark: item.mark,
            data_list,
          };
          return move_item;
        });
        this.is_all_right = JSON.stringify(this.answer.answer_list) === JSON.stringify(this.data.answer.answer_list);
      },
      immediate: true,
    },
    'data.option_list': {
      handler(val) {
        if (!val) return;
        this.disrupted = false;
        this.move_list = val.slice().map((item, index) => {
          let shuffe_item = this.shuffle(item.data_list.slice()).map(
            (items) => ({
              ...items,
            }),
            index === val.length - 1,
          );
          let move_item = {
            mark: item.mark,
            data_list: shuffe_item,
          };
          return move_item;
        });
      },
      deep: true,
      immediate: true,
    },
    click_index_list: {
      handler(val) {
        if (val.length === 2) {
          this.changeSort();
        }
      },
    },
  },
  mounted() {},
  methods: {
    // 随机打乱数组顺序
    shuffle(arr, flag) {
      if (this.disrupted) return arr;
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
      this.disrupted = flag;
      return arr;
    },
    onStart() {
      this.drag = true;
    },
    // 拖拽结束事件
    onEnd() {
      this.drag = false;
      this.click_index_list = [];
      this.select_index = null;
      this.$forceUpdate();
    },
    // 点击item
    handleClickItem(index, indexNode) {
      // 查看答案模式下需要禁用
      if (this.disabled) return;
      if (this.click_index_list.length !== 0) {
        let indexs = this.select_index;
        if (Number(indexs) !== Number(index)) {
          this.click_index_list = [];
        }
      }
      this.select_index = index;
      this.click_index_list.push(indexNode);
    },
    // 点击交换
    changeSort() {
      let indexs = this.select_index;
      let index1 = this.click_index_list[0];
      let index2 = this.click_index_list[1];
      [this.move_list[indexs].data_list[index1], this.move_list[indexs].data_list[index2]] = [
        this.move_list[indexs].data_list[index2],
        this.move_list[indexs].data_list[index1],
      ];
      this.click_index_list = [];
      this.answer.answer_list = this.move_list.map((item) => {
        let value_list = item.data_list.map((items) => {
          return items.mark;
        });
        let answer_item = {
          mark: item.mark,
          value_list,
        };
        return answer_item;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.sort-preview {
  @include preview;

  .move-box-horizontal {
    display: flex;
    column-gap: 8px;

    .option-number {
      line-height: 50px;
    }
  }

  .content-box {
    .drag-item {
      display: flex;
      column-gap: 16px;
      align-items: center;

      // max-width: 800px;
      margin-bottom: 16px;
      cursor: move;

      &.error {
        border: 1px solid $error-color;
        border-radius: 4px;
      }

      &.right {
        border: 1px solid $right-color;
        border-radius: 4px;

        .drag-content {
          background-color: $right-bc-color;
        }
      }
    }

    .drag-icon {
      width: 20px;
      height: 20px;
      color: #000;
    }

    .drag-content {
      flex: 1;

      // max-width: 800px;
      padding: 8px 16px;
      background: $content-color;
      border: 1px solid $content-color;
      border-radius: 4px;

      :deep p {
        margin: 0;
      }
    }

    &-horizontal {
      > span {
        display: flex;
        flex-wrap: wrap;
        column-gap: 8px;
      }

      .drag-item {
        display: block;
        margin-bottom: 8px;
      }

      .drag-content {
        display: block;
        width: max-content;
        padding: 8px 16px;
        background: $content-color;
        border-radius: 4px;
      }

      .drag-icon {
        display: block;
        margin: 16px auto 0;
      }
    }

    .drag-item-active {
      .drag-content {
        border-color: $light-main-color;
      }
    }
  }

  .right-title {
    margin: 24px 0;
    font-size: 16px;
    font-weight: 500;
    line-height: 24px;
    color: #000;
  }
}
</style>
