<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

// @ts-ignore
import { useTabs } from '@vben/hooks';

// @ts-ignore
import { questionCategoryTree } from '#/api/exam/question/category';
import {
  addQuestion,
  questionDetail,
  updateQuestion,
  // @ts-ignore
} from '#/api/exam/question/question';
// @ts-ignore
import TinymceEditor from '#/components/tinymce/src/editor.vue';
// @ts-ignore
const { closeCurrentTab } = useTabs();

const route = useRoute();
// const router = useRouter();
const id = route.query.id as string;

// 分类树形数据
const categoryTreeData: any = ref([]);

const editorOptions = {
  menubar: false,
  statusbar: false,
  plugins: ['image', 'lists', 'anchor'],
  toolbar: 'bullist numlist image bold',
};

interface FormData {
  categoryId: number | string;
  difficultyLevel: string;
  type: string;
  content: string;
  options: string[]; // 字符串数组，例如：['满意', '不满意']
  correctAnswer: string[]; // 数组，选择题标识选项对应的索引位置，填空题为答案字符串数组
  analysis: string;
}

// 表单数据
const formData = ref<FormData>({
  categoryId: '', // 使用数字类型以匹配树节点的id类型
  difficultyLevel: '',
  type: '',
  content: '',
  options: ['', ''], // 字符串数组，例如：['满意', '不满意']
  correctAnswer: [''], // 数组，选择题标识选项对应的索引位置，填空题为答案字符串数组
  analysis: '',
});

// 添加选项
const addOption = () => {
  formData.value.options.push('');
};

// 删除选项
const removeOption = (index: number) => {
  if (formData.value.options.length > 2) {
    formData.value.options.splice(index, 1);
    // 调整正确答案索引：如果删除的位置小于当前正确答案索引，需要将所有大于等于该索引的正确答案减1
    formData.value.correctAnswer = formData.value.correctAnswer
      .filter((answerIndex: any) => answerIndex !== index) // 移除被删除的索引
      .map((answerIndex: any) =>
        answerIndex > index ? answerIndex - 1 : answerIndex,
      ); // 调整剩余索引

    // 如果删除后没有正确答案，默认选择第一个选项
    if (formData.value.correctAnswer.length === 0) {
      formData.value.correctAnswer = ['0'];
    }
  }
};

// 添加填空
const addBlank = () => {
  formData.value.correctAnswer.push('');
};

// 删除填空
const removeBlank = (index: number) => {
  if (formData.value.correctAnswer.length > 1) {
    formData.value.correctAnswer.splice(index, 1);
  }
};

// 加载试题数据
const loadQuestionData = async () => {
  if (id) {
    try {
      // 调用API获取试题详情
      const question = await questionDetail(Number.parseInt(id));

      formData.value = {
        categoryId: question.categoryId, // 保持数字类型以匹配树节点的id类型
        difficultyLevel: question.difficultyLevel,
        type: question.questionType,
        content: question.questionContent,
        options: question.options ? JSON.parse(question.options) : ['', ''], // 解析JSON字符串为数组
        correctAnswer: JSON.parse(question.correctAnswer), // 解析JSON字符串为数组
        analysis: question.answerAnalysis || '',
      };
    } catch (error) {
      console.error('获取试题详情失败:', error);
    }
  }
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    const data: any = await questionCategoryTree();
    categoryTreeData.value = data.rows; // 直接存储树形结构
  } catch (error) {
    console.error('获取分类数据失败:', error);
  }
};

/**
 * 处理保存试题数据
 * @returns 处理后的试题数据对象
 */
const processQuestionData = () => {
  const {
    categoryId,
    difficultyLevel,
    type,
    content,
    options,
    correctAnswer,
    analysis,
  } = formData.value;

  // 初始化保存数据对象
  const saveData: any = {
    categoryId, // categoryId 现在是数字类型，无需转换
    questionType: type,
    questionContent: content,
    answerAnalysis: analysis,
    questionStatus: 'draft', // 默认草稿状态
    difficultyLevel,
    options: null,
    correctAnswer: [],
  };

  // 根据题型处理选项和正确答案
  switch (type) {
    case 'essay': {
      // 简答题
      // 选项设为null
      saveData.options = null;
      // 正确答案直接使用数组形式
      saveData.correctAnswer = JSON.stringify(correctAnswer);
      break;
    }

    case 'fill_blank': {
      // 填空题
      // 选项设为null
      saveData.options = null;
      // 正确答案直接使用数组形式
      saveData.correctAnswer = JSON.stringify(correctAnswer);
      break;
    }

    case 'judgment': {
      // 判断题
      // 选项设为JSON数组
      saveData.options = JSON.stringify(['正确', '错误']);
      // 正确答案使用索引数组
      saveData.correctAnswer = JSON.stringify(correctAnswer);
      break;
    }

    case 'multiple_choice': {
      // 多选题
      // 处理选项数组为JSON格式
      saveData.options = JSON.stringify(options);
      // 正确答案使用索引数组
      saveData.correctAnswer = JSON.stringify(correctAnswer);
      break;
    }

    case 'single_choice': {
      // 单选题
      // 处理选项数组为JSON格式
      saveData.options = JSON.stringify(options);
      // 正确答案使用索引数组
      saveData.correctAnswer = JSON.stringify(correctAnswer);
      break;
    }
  }

  return saveData;
};

// 保存并继续添加
const handleSaveAndContinue = async () => {
  // 处理试题数据
  const saveData = processQuestionData();

  try {
    if (id) {
      // 更新试题
      const params = {
        ...saveData,
        id: Number.parseInt(id),
      };
      await updateQuestion(params);
    } else {
      // 新增试题
      await addQuestion(saveData);
    }

    // 保存成功后重置表单
    formData.value = {
      categoryId: formData.value.categoryId, // 保持分类和难度不变
      difficultyLevel: formData.value.difficultyLevel,
      type: formData.value.type, // 保持题型不变
      content: '',
      options: ['', ''],
      correctAnswer: [],
      analysis: '',
    };
  } catch (error) {
    console.error('保存试题失败:', error);
  }
};

// 保存并关闭
const handleSaveAndClose = async () => {
  // 处理试题数据
  const saveData = processQuestionData();

  try {
    if (id) {
      // 更新试题
      const params = {
        ...saveData,
        id: Number.parseInt(id),
      };
      await updateQuestion(params);
    } else {
      // 新增试题
      await addQuestion(saveData);
    }

    // 保存成功后返回上一页
    // router.push('/examManage/questionBank');

    closeCurrentTab();
  } catch (error) {
    console.error('保存试题失败:', error);
  }
};

onMounted(() => {
  loadQuestionData();
  fetchCategories();
});
</script>

<template>
  <div class="question-edit">
    <div class="rounded-lg bg-white p-4 shadow-sm">
      <div class="mb-4 flex items-center justify-between">
        <h2 class="text-lg font-semibold text-gray-800">
          {{ id ? '编辑试题' : '新增试题' }}
        </h2>
      </div>

      <div class="space-y-6">
        <!-- 试题属性 -->
        <div class="rounded-lg">
          <h3
            class="text-md mb-3 font-medium text-gray-700"
            style="border-left: 4px solid #007bff; padding-left: 10px"
          >
            试题属性
          </h3>
          <!-- <h3 class="text-md mb-3 font-medium text-gray-700">试题属性</h3> -->
          <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
            <el-form-item label="试题分类" label-width="80px">
              <el-tree-select
                v-model="formData.categoryId"
                :data="categoryTreeData"
                placeholder="请选择试题分类"
                node-key="id"
                :props="{ label: 'name', children: 'children' }"
              />
            </el-form-item>
            <el-form-item label="试题难度" label-width="80px">
              <el-select
                v-model="formData.difficultyLevel"
                placeholder="请选择试题难度"
              >
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>
            <el-form-item label="试题类型" label-width="80px">
              <el-select v-model="formData.type" placeholder="请选择试题类型">
                <el-option label="单选题" value="single_choice" />
                <el-option label="多选题" value="multiple_choice" />
                <el-option label="判断题" value="judgment" />
                <el-option label="填空题" value="fill_blank" />
                <el-option label="简答题" value="essay" />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <!-- 题目（题干内容） -->
        <div>
          <h3
            class="text-md mb-3 font-medium text-gray-700"
            style="border-left: 4px solid #007bff; padding-left: 10px"
          >
            题目（题干内容）
          </h3>
          <TinymceEditor
            v-model="formData.content"
            :height="300"
            :options="editorOptions"
          />
        </div>

        <!-- 选项（单选题、多选题、判断题） -->
        <div
          v-if="
            ['single_choice', 'multiple_choice', 'judgment'].includes(
              formData.type,
            )
          "
        >
          <h3
            class="text-md mb-3 font-medium text-gray-700"
            style="border-left: 4px solid #007bff; padding-left: 10px"
          >
            选项
          </h3>
          <div class="space-y-3">
            <!-- 判断题特殊处理 -->
            <div v-if="formData.type === 'judgment'" class="rounded-lg">
              <div class="items-start gap-2">
                <div class="flex items-center">
                  <el-radio
                    v-model="formData.correctAnswer[0]"
                    :label="0"
                    class="mt-1"
                  >
                    正确
                  </el-radio>
                  <el-radio
                    v-model="formData.correctAnswer[0]"
                    :label="1"
                    class="mt-1"
                  >
                    错误
                  </el-radio>
                </div>
              </div>
            </div>

            <!-- 单选题和多选题选项 -->
            <div
              v-else
              v-for="(option, index) in formData.options"
              :key="index"
              class="rounded-lg"
            >
              <div class="items-start gap-2">
                <div class="flex items-center">
                  <span class="ml-2 font-medium" style="margin-right: 15px">
                    {{ String.fromCodePoint(65 + index) }}.
                  </span>
                  <!-- 单选题 -->
                  <el-radio
                    v-if="formData.type === 'single_choice'"
                    v-model="formData.correctAnswer[0]"
                    label="答案"
                    :value="index"
                    class="mt-1"
                  />
                  <!-- 多选题 -->

                  <el-checkbox
                    v-else-if="formData.type === 'multiple_choice'"
                    v-model="formData.correctAnswer"
                    label="答案"
                    :value="index"
                    class="mt-1"
                  />
                </div>
                <div class="flex-1">
                  <!-- 选项内容 -->
                  <div class="mb-2">
                    <TinymceEditor
                      v-model="formData.options[index]"
                      :height="200"
                      :options="editorOptions"
                    />
                  </div>
                  <!-- 删除选项按钮 -->
                  <div class="flex justify-end">
                    <el-button
                      type="danger"
                      text
                      size="small"
                      @click="removeOption(index)"
                      :disabled="formData.options.length <= 2"
                    >
                      删除选项
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 添加选项按钮（非判断题） -->
            <div
              v-if="formData.type !== 'judgment'"
              class="flex justify-center"
            >
              <el-button type="primary" plain @click="addOption">
                添加一个新选项
              </el-button>
            </div>
          </div>
        </div>

        <!-- 填空题和简答题答案 -->
        <div v-if="['fill_blank', 'essay'].includes(formData.type)">
          <h3
            class="text-md mb-3 font-medium text-gray-700"
            style="border-left: 4px solid #007bff; padding-left: 10px"
          >
            答案
          </h3>
          <div class="space-y-3">
            <!-- 填空题多个空 -->
            <div v-if="formData.type === 'fill_blank'" class="space-y-4">
              <div
                v-for="(answer, index) in formData.correctAnswer"
                :key="index"
                class="flex items-start gap-3"
              >
                <div class="mt-1 flex-shrink-0">
                  <span class="text-gray-700">填空{{ index + 1 }}:</span>
                </div>
                <div class="flex-1">
                  <el-input
                    v-model="formData.correctAnswer[index]"
                    placeholder="请输入答案"
                    class="w-full"
                  />
                </div>
                <div class="mt-1 flex-shrink-0">
                  <el-button
                    v-if="formData.correctAnswer.length > 1"
                    type="danger"
                    text
                    size="small"
                    @click="removeBlank(index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <!-- 添加新空按钮 -->
              <div class="mt-2 w-full">
                <el-button
                  plain
                  @click="addBlank"
                  style="
                    width: 100%;
                    border-style: dashed;
                    border-color: #d9d9d9;
                    color: #333;
                  "
                >
                  + 添加一个新填空
                </el-button>
              </div>
            </div>
            <!-- 简答题单个答案 -->
            <div v-else class="rounded-lg">
              <div class="mb-2">
                <TinymceEditor
                  v-model="formData.correctAnswer[0]"
                  :height="300"
                  :options="editorOptions"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 答案解析 -->
        <div>
          <h3
            class="text-md mb-3 font-medium text-gray-700"
            style="border-left: 4px solid #007bff; padding-left: 10px"
          >
            答案解析
          </h3>
          <div class="mb-2 flex items-center gap-2">
            <!--TODO: 引用功能未实现-->
            <el-button type="default" plain size="small"> 引用 </el-button>
          </div>
          <TinymceEditor
            v-model="formData.analysis"
            :height="300"
            :options="editorOptions"
          />
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-start gap-3 border-t pt-4">
          <el-button type="primary" @click="handleSaveAndContinue">
            保存并继续添加
          </el-button>
          <el-button type="primary" plain @click="handleSaveAndClose">
            保存并关闭
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.question-edit {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

/* 富文本编辑器样式 */
:deep(.el-textarea) {
  font-family: inherit;
}

:deep(.el-textarea__inner) {
  border: none;
  resize: none;
  padding: 0;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-textarea__inner:focus) {
  box-shadow: none;
}
</style>
