<script setup lang="ts">
import { Bottom, Delete, Top } from '@element-plus/icons-vue'

import {
  batchUpdateTypeId,
  getQuestionTypeList,
} from '#/api/service/question-bank/school-book'

import { usePaperStore } from '../..'

defineOptions({ name: 'PaperDetail' })

const paperStore = usePaperStore()
const { paper, questionGroups, detailRef } = storeToRefs(paperStore)
const { removeQuestionGroup, moveUpQuestionGroup, moveDownQuestionGroup } =
  paperStore

const typeDialogVisible = ref(false)
const questionTypeList = ref<any[]>([])
const selectedTypeId = ref('')
const savingType = ref(false)
const currentNullGroup = ref<any>(null)

const openTypeDialog = (group: any) => {
  currentNullGroup.value = group
  selectedTypeId.value = group.isNullType ? '' : group.id
  typeDialogVisible.value = true
}

const loadQuestionTypes = async () => {
  if (questionTypeList.value.length > 0) return
  const res = await getQuestionTypeList({
    courseId: paper.value.courseId,
    current: -1,
  })
  questionTypeList.value = res
}

const handleSaveType = async () => {
  if (!selectedTypeId.value) {
    ElMessage.warning('请选择题型')
    return
  }
  const group = currentNullGroup.value
  if (!group) return
  const typeName = questionTypeList.value.find(
    (t: any) => t.id === selectedTypeId.value,
  )?.name
  savingType.value = true
  try {
    const params = group.questions.map((q: any) => ({
      id: q.id,
      typeId: selectedTypeId.value,
    }))
    await batchUpdateTypeId(params)
    paperStore.updateGroupType(group.id, selectedTypeId.value, typeName)
    typeDialogVisible.value = false
    ElMessage.success('题型设置成功')
  } finally {
    savingType.value = false
  }
}

// 处理标题悬停效果
const handleTitleMouseEnter = (event: MouseEvent) => {
  let group = event.target as HTMLElement
  group = group.closest('.question-group') as HTMLElement
  if (group) {
    group.classList.add('hide-preview')
  }
}

const handleTitleMouseLeave = (event: MouseEvent) => {
  let group = event.target as HTMLElement
  group = group.closest('.question-group') as HTMLElement
  if (group) {
    group.classList.remove('hide-preview')
  }
}

const updateQuestionsEvents = (add: boolean) => {
  const titles = detailRef.value?.querySelectorAll(
    '.question-group-questions',
  ) as any
  if (!titles) return
  for (const title of titles) {
    title.removeEventListener('mouseenter', handleTitleMouseEnter)
    title.removeEventListener('mouseleave', handleTitleMouseLeave)
    if (add) {
      title.addEventListener('mouseenter', handleTitleMouseEnter)
      title.addEventListener('mouseleave', handleTitleMouseLeave)
    }
  }
}

onUnmounted(() => {
  // 清理事件监听器
  updateQuestionsEvents(false)
})

onUpdated(() => {
  updateQuestionsEvents(true)
})
</script>

<template>
  <div class="paper-detail" ref="detailRef">
    <el-input class="title" v-model="paper.name" placeholder="请输入试卷名称" />
    <div v-if="questionGroups.length" class="question-groups">
      <div
        class="question-group"
        v-for="group in questionGroups"
        :key="group.name"
        :id="`detail-group-${group.id}`"
      >
        <div class="preview-toolbar">
          <el-button
            :icon="Top"
            type="primary"
            title="上移"
            :disabled="group.isFirst"
            @click="moveUpQuestionGroup(group)"
          />
          <el-button
            :icon="Bottom"
            type="primary"
            title="下移"
            :disabled="group.isLast"
            @click="moveDownQuestionGroup(group)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            title="删除"
            @click="removeQuestionGroup(group)"
          />
        </div>
        <h3 class="question-group-title">
          <template v-if="group.isNullType">
            {{ group.namePrefix }}
            <el-tag
              type="danger"
              effect="plain"
              class="null-type-tag"
              @click.stop="openTypeDialog(group)"
            >
              请选择题型
            </el-tag>
            {{ `（共${group.score || 0}分）` }}
          </template>
          <template v-else>
            {{ group.namePrefix }}
            <el-tag
              type="primary"
              effect="plain"
              class="null-type-tag"
              @click.stop="openTypeDialog(group)"
            >
              {{ group.questions[0]?.titleChannelTypeName }}
            </el-tag>
            {{ `（共${group.score || 0}分）` }}
          </template>
        </h3>
        <div class="question-group-questions">
          <paper-question-item
            v-for="question in group.questions"
            :key="question.id"
            :question="question"
            :index="question.seq"
            preview
            :id="`detail-question-${question.id}`"
          />
        </div>
      </div>
    </div>
    <el-empty v-else description="暂无题目数据" />

    <el-dialog
      v-model="typeDialogVisible"
      title="选择题型"
      width="420px"
      :close-on-click-modal="false"
      @open="loadQuestionTypes"
    >
      <el-select
        v-model="selectedTypeId"
        placeholder="请选择题型"
        style="width: 100%"
        filterable
      >
        <el-option
          v-for="item in questionTypeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <template #footer>
        <el-button @click="typeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="savingType" @click="handleSaveType">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.paper-detail {
  @keyframes highlight-flash {
    0% {
      background-color: transparent;
    }

    50% {
      background-color: rgb(0 255 0 / 30%);
    }

    100% {
      background-color: transparent;
    }
  }

  flex: 1;
  height: 100%;
  padding: 16px;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 4px;

  .highlight-flash {
    animation: highlight-flash 1.5s ease-in-out;
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    margin-bottom: 16px;
    font-size: 22px;
    font-weight: 500;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    :deep(.el-input__wrapper) {
      background-color: transparent !important;

      .el-input__inner {
        color: #000 !important;
        text-align: center;
      }
    }
  }

  .question-groups {
    display: flex;
    flex-direction: column;
    gap: 16px;

    :deep(.paper-question-item) {
      background-color: transparent;
    }

    .question-group {
      position: relative;
      border: 1px solid transparent;
      border-radius: 4px;
      border-top-right-radius: 0;

      .preview-toolbar {
        position: absolute;
        top: -50px;
        right: -1px;
        display: none;
        gap: 10px;
        align-items: center;
        height: 50px;
        padding: 0 10px;
        background-color: #fff;
        border: 1px solid #246cff;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
      }

      &-title {
        padding: 16px;
        font-size: 16px;
        font-weight: 500;
        cursor: pointer;
        border: 1px solid transparent;

        .null-type-tag {
          font-size: 14px;
          cursor: pointer;
        }
      }

      &:hover {
        border-color: #246cff;

        .preview-toolbar {
          display: flex;
        }
      }

      &.hide-preview {
        border-color: transparent;

        .preview-toolbar {
          display: none;
        }
      }

      &-questions {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }
    }
  }
}
</style>
