<template>
  <el-dialog v-model="visible" title="评分标准" width="600px" :modal="false" @close="handleClose">
    <div class="question-tabs">
      <div class="tab-list">
        <div
          v-for="(q, idx) in questions"
          :key="idx"
          class="tab-item"
          :class="{ active: idx === activeIndex }"
          @click="activeIndex = idx"
        >
          <span>题目 {{ idx + 1 }}</span>
          <el-button text size="small" @click.stop="removeQuestion(idx)" v-if="questions.length > 1">✕</el-button>
        </div>
        <el-button size="small" @click="addQuestion">+ 添加题目</el-button>
      </div>

      <div class="tab-content" v-if="questions[activeIndex]">
        <el-form :model="questions[activeIndex]" size="small" label-width="80px">
          <el-form-item label="题目">
            <el-input v-model="questions[activeIndex].questionTitle" type="textarea" :rows="2" placeholder="输入题目内容" />
          </el-form-item>
          <el-form-item label="满分">
            <el-input-number v-model="questions[activeIndex].maxScore" :min="1" :max="1000" />
          </el-form-item>
          <el-form-item label="参考答案">
            <el-input v-model="questions[activeIndex].referenceAnswer" type="textarea" :rows="3" placeholder="输入参考答案（可选）" />
            <div class="ref-image-section">
              <template v-if="questions[activeIndex].referenceAnswerImage">
                <div class="ref-image-preview">
                  <img :src="questions[activeIndex].referenceAnswerImage" />
                  <el-button size="small" type="danger" text @click="removeRefImage(activeIndex)">删除图片</el-button>
                </div>
              </template>
              <el-button size="small" @click="uploadRefImage(activeIndex)">上传参考答案图片</el-button>
            </div>
          </el-form-item>
          <el-form-item label="评分标准">
            <el-input v-model="questions[activeIndex].rubric" type="textarea" :rows="6" placeholder="输入评分标准" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="footer-left">
        <el-button size="small" @click="handleImport">导入</el-button>
        <el-button size="small" @click="handleExport">导出</el-button>
        <el-button size="small" @click="showTemplateForm = !showTemplateForm">
          {{ showTemplateForm ? '取消' : '保存为模板' }}
        </el-button>
      </div>
      <div class="footer-right">
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button type="primary" size="small" @click="handleSave">应用</el-button>
      </div>
    </template>
    <div v-if="showTemplateForm" class="template-form">
      <el-form inline size="small">
        <el-form-item label="模板名称">
          <el-input v-model="templateName" placeholder="如：期末考试" />
        </el-form-item>
        <el-form-item label="课程">
          <el-input v-model="templateCourse" placeholder="如：Java" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" @click="saveAsTemplate">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/stores/app'
import { useGradingStore } from '@/stores/grading'
import type { QuestionItem } from '@/types'
import { addWatermark } from '@/utils/image'

const appStore = useAppStore()
const gradingStore = useGradingStore()
const visible = ref(false)
const activeIndex = ref(0)
const questions = ref<QuestionItem[]>([])
const showTemplateForm = ref(false)
const templateName = ref('')
const templateCourse = ref('')

function emptyQuestion(): QuestionItem {
  return { questionTitle: '', maxScore: 100, referenceAnswer: '', rubric: '' }
}

watch(() => appStore.isRubricEditorOpen, async (val) => {
  visible.value = val
  if (val) {
    const data = await window.electronAPI?.rubric.getData()
    if (data?.questions?.length) {
      questions.value = JSON.parse(JSON.stringify(data.questions))
      activeIndex.value = data.currentIndex ?? 0
    } else {
      questions.value = [emptyQuestion()]
      activeIndex.value = 0
    }
  }
})

function addQuestion() {
  questions.value.push(emptyQuestion())
  activeIndex.value = questions.value.length - 1
}

function removeQuestion(idx: number) {
  questions.value.splice(idx, 1)
  if (activeIndex.value >= questions.value.length) {
    activeIndex.value = questions.value.length - 1
  }
}

async function handleSave() {
  try {
    gradingStore.setQuestions(JSON.parse(JSON.stringify(questions.value)))
    await window.electronAPI?.rubric.storeData({
      questions: JSON.parse(JSON.stringify(questions.value)),
      currentIndex: 0
    })
    await window.electronAPI?.rubric.resetNextIndex()
    ElMessage.success('评分标准已保存')
  } catch (err) {
    ElMessage.error('保存失败：' + (err as Error).message)
  }
}

async function handleExport() {
  try {
    await window.electronAPI?.rubric.exportJson()
    ElMessage.success('导出成功')
  } catch (err) {
    ElMessage.error('导出失败：' + (err as Error).message)
  }
}

async function handleImport() {
  try {
    const data = await window.electronAPI?.rubric.importJson()
    if (data?.questions?.length) {
      questions.value = JSON.parse(JSON.stringify(data.questions))
      activeIndex.value = 0
      ElMessage.success(`已导入 ${data.questions.length} 题`)
    }
  } catch (err) {
    ElMessage.error('导入失败：' + (err as Error).message)
  }
}

async function saveAsTemplate() {
  if (!templateName.value || !templateCourse.value) {
    ElMessage.warning('请填写模板名称和课程')
    return
  }
  try {
    const ok = await window.electronAPI?.template.save({
      name: templateName.value,
      course: templateCourse.value,
      questions: JSON.parse(JSON.stringify(questions.value))
    })
    if (ok) {
      ElMessage.success('模板已保存')
      templateName.value = ''
      templateCourse.value = ''
      showTemplateForm.value = false
    }
  } catch (err) {
    ElMessage.error('保存模板失败：' + (err as Error).message)
  }
}

function handleClose() {
  window.electronAPI?.dialog.close()
}

async function uploadRefImage(idx: number) {
  if (!window.electronAPI) return
  const data = await window.electronAPI.dialog.openImage()
  if (data) {
    questions.value[idx].referenceAnswerImage = `data:image/${data.mime};base64,${await addWatermark(data.base64, '参考答案')}`
  }
}

function removeRefImage(idx: number) {
  delete questions.value[idx].referenceAnswerImage
}
</script>

<style scoped>
:deep(.el-dialog__footer) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.question-tabs {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.tab-list {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  align-items: center;
}
.tab-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
}
.tab-item.active {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
}
.tab-content {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  max-height: 480px;
  overflow-y: auto;
}
.footer-left {
  display: flex;
  gap: 8px;
}
.footer-right {
  display: flex;
  gap: 8px;
}
.ref-image-section {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.ref-image-preview {
  display: flex;
  align-items: center;
  gap: 8px;
}
.ref-image-preview img {
  max-height: 120px;
  max-width: 200px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}
.template-form {
  padding: 8px 16px;
  border-top: 1px solid #eee;
  background: #fafafa;
}
</style>