
<template>
  <div class="w-full transition-all duration-300 hover:shadow-light group right-topic-item">
    <div class="flex items-center justify-between p-15px pr-10px bg-white rounded-4px right-topic-sub-item">
      <div class="flex items-center">
        <div class="flex items-center justify-center mr-6px text-12px text-primary select-none serial-number">
          <span>{{ topicInfo.question.no }}</span>
        </div>
        <div class="flex items-center justify-center px-8px py-4px ml-4px text-12px font-bold leading-1em text-primary bg-primary/10 rounded-4px select-none type">
          <span>{{ showType }}</span>
        </div>
      </div>
      <div class="flex items-center action-box">
        <n-tooltip trigger="hover" placement="top">
          <template #trigger>
            <n-button
              type="primary"
              text
              class="ml-2px text-18px"
              :loading="analysisLoading"
              :disabled="analysisLoading"
              @click="openItemAnalysis"
            >
              <template #icon>
                <icon-solar-checklist-minimalistic-linear />
              </template>
            </n-button>
          </template>
          单项解析
        </n-tooltip>
        <n-tooltip trigger="hover" placement="top">
          <template #trigger>
            <n-button type="primary" text class="ml-2px text-18px" @click="releaseTask">
              <template #icon>
                <icon-solar-bookmark-circle-outline />
              </template>
            </n-button>
          </template>
          发布任务(录制讲解音视频)
        </n-tooltip>
        <n-tooltip trigger="hover" placement="top">
          <template #trigger>
            <n-button
              type="primary"
              text
              class="ml-2px text-18px"
              @click="() => emit('edit-topic', topicInfo)"
            >
              <template #icon>
                <icon-solar-pen-2-linear />
              </template>
            </n-button>
          </template>
          编辑或修改信息
        </n-tooltip>
        <n-tooltip trigger="hover" placement="top">
          <template #trigger>
            <n-button type="success" text class="ml-2px text-18px" @click="addAnswer">
              <template #icon>
                <icon-solar-add-square-linear />
              </template>
            </n-button>
          </template>
          点击添加答题区域
        </n-tooltip>
        <n-tooltip trigger="hover" placement="top">
          <template #trigger>
            <n-button type="error" text class="ml-2px text-18px" @click="delTopic">
              <template #icon>
                <icon-solar-trash-bin-minimalistic-outline />
              </template>
            </n-button>
          </template>
          删除题目
        </n-tooltip>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, defineProps, defineEmits, type PropType } from 'vue';
  import { NButton, NTooltip, useDialog, useMessage } from 'naive-ui';
  import IconSolarChecklistMinimalisticLinear from '~icons/solar/checklist-minimalistic-linear';
  import IconSolarBookmarkCircleOutline from '~icons/solar/bookmark-circle-outline';
  import IconSolarPen2Linear from '~icons/solar/pen-2-linear';
  import IconSolarAddSquareLinear from '~icons/solar/add-square-linear';
  import IconSolarTrashBinMinimalisticOutline from '~icons/solar/trash-bin-minimalistic-outline';
  import type { CurrBookPageAllInfo, TopicInfo } from '@/views/template/template-detail/types';
  import { defAnswerInfo, topicTypeList } from '@/views/template/template-detail/def-data';
  import { type BookReviewInput, type QuestionFromInfo, delBookQuestionAxios, getQuestionInfoAxios, updateBookPageLayoutAxios } from '@/service/api/book';
  import { myStrToJson } from '@/utils/data';

  const props = defineProps({
    /** 题目 */
    topicInfo: { type: Object as PropType<TopicInfo>, required: true },
    /** 当前页码信息 */
    currBookPage: { type: Object as PropType<CurrBookPageAllInfo>, default: undefined },
  });

  const emit = defineEmits<{
    /** 编辑题目 */
    (e: 'edit-topic', topicInfo: TopicInfo): void;
    /** 发布任务 */
    (e: 'release-task', event: MouseEvent, data: BookReviewInput): void;
    /** 添加单项解析区域 */
    (e: 'add-analysis', event: MouseEvent, questionFromInfo: QuestionFromInfo): void;
  }>();

  const dialog = useDialog();
  const message = useMessage();
  const analysisLoading = ref(false);
  const showType = computed(() => {
    return topicTypeList.find((item) => item.value === props.topicInfo.question.type)?.label || '默认';
  });

  function delTopic() {
    dialog.warning({
      title: '温馨提示',
      content: '删除后不可恢复，您确定删除吗？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          await delBookQuestionAxios(props.topicInfo.questionId);
          const copy = [...props.currBookPage!.currBookPageData.layout];
          const index = [...props.currBookPage!.currBookPageData.layout].findIndex((item) => item.questionId === props.topicInfo.questionId);
          copy.splice(index, 1);
          await updateBookPageLayoutAxios({
            id: props.currBookPage!.currBookPageData!.bookPageId!,
            layout: JSON.stringify(copy),
          });
          props.currBookPage!.currBookPageData.layout.splice(index, 1);
          message.success('删除成功');
        } catch (error: any) {
          message.error(error.msg || '删除失败，-BD004');
        }
      },
    });
  }

  /**
   * 打开单项解析
   * @param event 鼠标事件
   */
  async function openItemAnalysis(event: MouseEvent) {
    try {
      analysisLoading.value = true;
      const res = await getQuestionInfoAxios(props.topicInfo!.questionId!);
      const options = myStrToJson<string[]>(res.options || '[]') || [];

      if ([1, 2, 3].includes(res.type ?? -1) && options.length <= 0) {
        message.error('请先完善题目信息');
        analysisLoading.value = false;
        return;
      }
      emit('add-analysis', event, res);
      analysisLoading.value = false;
    } catch (error) {
      analysisLoading.value = false;
      message.error('获取数据失败');
    }
  }

  /**
   * 添加答题区域
   */
  function addAnswer() {
    const answerInfo = defAnswerInfo(props.topicInfo.question.x);
    if (Array.isArray(props.topicInfo?.answerList)) {
      // eslint-disable-next-line vue/no-mutating-props
      props.topicInfo?.answerList?.push(answerInfo);
    } else {
      props.topicInfo!.answerList = [answerInfo];
    }
  }

  /**
   * 发布任务
   */
  function releaseTask(event: MouseEvent) {
    emit('release-task', event, {
      bookId: props.currBookPage!.currBookPageData!.bookId!,
      bookPageId: props.currBookPage!.currBookPageData!.bookPageId!,
      id: props.topicInfo.questionId,
    });
  }
</script>

<style scoped>
.right-topic-item {
  --my-color: #409eff; /* Naive UI primary color usually */
  --my-background: #ecf5ff;
}
</style>
