<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="select-preview" :style="getAreaStyle()">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />

    <div class="main">
      <ul class="option-list">
        <draggable
          v-model="move_list"
          :disabled="disabled"
          animation="300"
          @start="onStart($event)"
          @end="onEnd($event)"
        >
          <transition-group
            class="group"
            :style="{
              flexDirection: data.property.arrange_direction === arrangeTypeList[0].value ? 'row' : 'column',
            }"
          >
            <li
              v-for="(item, i) in move_list"
              :key="i"
              :class="['drag-item', ...computedDragItemClass(i)]"
              @click="handleClickItem(i)"
            >
              <span class="rich-text" v-html="sanitizeHTML(item.content)"></span>
            </li>
          </transition-group>
        </draggable>
      </ul>

      <template v-if="isShowRightAnswer && !is_all_right">
        <div class="right-title">正确答案：</div>
        <ul class="option-list">
          <draggable v-model="right_answer_list" animation="300" :disabled="true">
            <transition-group
              class="group"
              :style="{
                flexDirection: data.property.arrange_direction === arrangeTypeList[0].value ? 'row' : 'column',
              }"
            >
              <li v-for="(item, i) in right_answer_list" :key="i" :class="['drag-item', 'right']">
                <span class="rich-text" v-html="sanitizeHTML(item.content)"></span>
              </li>
            </transition-group>
          </draggable>
        </ul>
      </template>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

import { getSortData, arrangeTypeList } from '@/views/book/courseware/data/sort';

import PreviewMixin from '../common/PreviewMixin';

export default {
  name: 'SortPreview',
  components: { draggable },
  mixins: [PreviewMixin],
  data() {
    return {
      data: getSortData(),
      arrangeTypeList,
      move_list: [], // 移动后的数组
      right_answer_list: [], // 正确答案列表
      drag: false,
      clickIndexList: [], // 点击选中的索引
      is_all_right: false, // 是否全对
    };
  },
  watch: {
    move_list: {
      handler(val) {
        if (!val || this.isJudgingRightWrong) return;
        this.answer.answer_list = val.map(({ mark }) => mark);
      },
      deep: true,
    },
    isJudgingRightWrong: {
      handler(val) {
        if (!val) return;
        this.move_list = this.answer.answer_list.map((mark) =>
          this.data.option_list.find((item) => item.mark === mark),
        );
        this.is_all_right = this.move_list.every(
          ({ custom_serial_number }, index) => index + 1 === Number(custom_serial_number),
        );

        this.right_answer_list = this.data.option_list.toSorted(
          (a, b) => Number(a.custom_serial_number) - Number(b.custom_serial_number),
        );
      },
      immediate: true,
    },
    'data.option_list': {
      handler(val) {
        if (!val) return;
        this.move_list = JSON.parse(JSON.stringify(val));
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    onStart() {
      this.drag = true;
    },
    // 拖拽结束事件
    onEnd() {
      this.drag = false;
      this.clickIndexList = [];
    },
    /**
     * 计算拖拽项目样式
     * @param {number} index 索引
     */
    computedDragItemClass(index) {
      return [
        {
          selected: this.clickIndexList.includes(index),
        },
        this.isJudgingRightWrong
          ? Number(this.move_list[index].custom_serial_number) === index + 1
            ? 'right'
            : 'error'
          : '',
      ];
    },
    /**
     * 处理点击项目事件
     * @param {number} index 索引
     */
    handleClickItem(index) {
      if (this.disabled) return;
      if (this.clickIndexList.length === 1) {
        if (this.clickIndexList[0] === index) {
          this.clickIndexList = [];
          return;
        }
      }
      this.clickIndexList.push(index);
      if (this.clickIndexList.length === 2) {
        this.changeSort();
      }
    },
    // 点击交换
    changeSort() {
      const index1 = this.clickIndexList[0];
      const index2 = this.clickIndexList[1];
      [this.move_list[index1], this.move_list[index2]] = [this.move_list[index2], this.move_list[index1]];
      this.clickIndexList = [];
      this.answer.answer_list = this.move_list.map(({ mark }) => mark);
    },
  },
};
</script>

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

.select-preview {
  @include preview-base;

  .option-list {
    .group {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .drag-item {
        min-height: 40px;
        padding: 8px 16px;
        cursor: move;
        background: $content-color;
        border: 1px solid $content-color;
        border-radius: 4px;

        &.selected {
          border-color: $light-main-color;
        }

        &.error {
          border-color: $error-color;
        }

        &.right {
          background-color: $right-bc-color;
          border-color: $right-color;
        }
      }
    }
  }

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