<template>
  <v-container fluid class="pt-0">
    <!-- 页面标题 -->
    <v-row class="mb-4">
      <v-col cols="12">
        <h2>{{ $t('task.title') }}</h2>
      </v-col>
    </v-row>

    <!-- 筛选条件和日历的左右布局 -->
    <div class="d-flex task-layout">
      <!-- 左侧：筛选条件面板 -->
      <div
        class="filter-panel-container"
        :class="{ 'filter-panel-collapsed': !isFilterExpanded }"
      >
        <v-card elevation="2" class="h-100 filter-panel-card">
          <v-card-title class="pa-2">
            <div class="d-flex align-center">
              <v-icon class="me-2">mdi-filter</v-icon>
              <span>{{ $t('task.filters.title') }}</span>
            </div>
          </v-card-title>
          <v-card-text>
            <v-row>
              <v-col cols="12">
                <v-select
                  v-model="filters.studentId"
                  :items="studentOptions"
                  :label="$t('task.task.student')"
                  clearable
                  density="compact"
                  variant="outlined"
                  @update:model-value="onStudentChange"
                />
              </v-col>
              <v-col cols="12">
                <v-select
                  v-model="filters.subjectId"
                  :items="subjectOptions"
                  :label="$t('task.task.subject')"
                  clearable
                  density="compact"
                  variant="outlined"
                  @update:model-value="onSubjectChange"
                />
              </v-col>
              <v-col cols="12">
                <v-select
                  v-model="filters.termId"
                  :items="termOptions"
                  :label="$t('task.task.term')"
                  :disabled="!filters.studentId"
                  clearable
                  density="compact"
                  variant="outlined"
                  :hint="!filters.studentId ? $t('task.filters.selectStudentFirst') : ''"
                  persistent-hint
                  @update:model-value="onTermChange"
                />
              </v-col>
              <v-col cols="12">
                <v-btn
                  @click="applyFilters"
                  color="primary"
                  variant="flat"
                  :loading="isLoading"
                  block
                  class="mb-2"
                >
                  {{ $t('task.filters.apply') }}
                </v-btn>
                <v-btn
                  @click="clearFilters"
                  variant="outlined"
                  block
                >
                  {{ $t('task.filters.clear') }}
                </v-btn>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>
      </div>

      <!-- 右侧：日历和数据展示 -->
      <div
        class="calendar-container"
        :class="{ 'calendar-full-width': !isFilterExpanded }"
        style="height: calc(100vh - 270px); overflow-y: auto;"
      >
        <!-- 错误提示已移至编辑对话框内部 -->

        <!-- 日历组件 -->
        <v-card
          elevation="2"
          :style="{
            height: '100%',
            display: 'flex',
            'flex-direction': 'column',
            position: isFullscreen ? 'fixed' : 'relative',
            top: isFullscreen ? '0' : 'auto',
            left: isFullscreen ? '0' : 'auto',
            width: isFullscreen ? '100vw' : 'auto',
            height: isFullscreen ? '100vh' : '100%',
            'z-index': isFullscreen ? '9999' : 'auto'
          }"
        >
          <v-card-title class="d-flex justify-space-between align-center">
            <span>{{ $t('task.calendar.title') }}</span>
            <div class="d-flex gap-1">
              <!-- 筛选面板切换按钮 -->
              <v-btn
                :icon="isFilterExpanded ? 'mdi-filter-minus' : 'mdi-filter-plus'"
                variant="outlined"
                color="primary"
                size="small"
                @click="toggleFilterPanel"
                :title="isFilterExpanded ? $t('task.filters.collapse') : $t('task.filters.expand')"
                :disabled="isLoading"
              />
              <!-- 全屏切换按钮 -->
              <v-btn
                :icon="isFullscreen ? 'mdi-fullscreen-exit' : 'mdi-fullscreen'"
                variant="text"
                size="small"
                @click="toggleFullscreen"
                :title="isFullscreen ? $t('task.calendar.exitFullscreen') : $t('task.calendar.enterFullscreen')"
                :disabled="isLoading"
              />
            </div>
          </v-card-title>
          <v-card-text :style="{
            flex: '1',
            'overflow-y': 'auto',
            padding: isFullscreen ? '24px' : '16px'
          }">
            <!-- Vuetify v-calendar 组件 -->
            <div class="mb-4" :style="{ height: isFullscreen ? 'calc(100vh - 200px)' : 'auto', position: 'relative' }">
              <v-calendar
                ref="calendar"
                v-model="selectedDate"
                :events="calendarEvents"
                @click:event="onEventClick"
                @click:date="onDateClick"
                class="task-calendar"
                :first-interval="0"
                :interval-count="24"
                :interval-height="isFullscreen ? 80 : 60"
                type="month"
                :disabled="isLoading"
              >
                <!-- 自定义日历事件显示 -->
                <template #day-event="{ event }">
                  <div class="custom-event" @click="onEventClick(event)">
                    <div class="event-content">
                      <span
                        class="subject-tag"
                        :style="{ color: event.color, fontWeight: 'bold' }"
                      >
                        [{{ getSubjectShortName(event.taskData?.subject_id) }}]
                      </span>
                      {{ event.title }}
                    </div>
                    <!-- 完成度进度条 -->
                    <div class="completion-bar">
                      <div
                        class="completion-fill"
                        :style="{
                          width: `${event.taskData?.completion_percent || 0}%`,
                          backgroundColor: '#4CAF50' // 绿色
                        }"
                      ></div>
                    </div>
                  </div>
                </template>
              </v-calendar>

              <!-- 加载遮罩层 -->
              <div v-if="isLoading" class="loading-overlay">
                <v-progress-circular
                  indeterminate
                  color="primary"
                  size="64"
                  width="6"
                />
              </div>
            </div>

            <div v-if="calendarEvents.length === 0 && !isLoading" class="text-center py-8">
              <v-icon size="64" color="grey-lighten-1">mdi-calendar-blank</v-icon>
              <div class="text-h6 mt-2 text-grey-lighten-1">{{ $t('task.calendar.noEvents') }}</div>
            </div>
          </v-card-text>
        </v-card>
      </div>
    </div>

    <!-- 任务详情对话框 -->
    <v-dialog v-model="taskDetailDialog" max-width="600">
      <v-card v-if="selectedTask">
        <v-card-title>
          <span>{{ selectedTask.task_name }}</span>
          <v-spacer />
          <v-btn
            icon="mdi-close"
            variant="text"
            @click="taskDetailDialog = false"
          />
        </v-card-title>
        <v-card-text>
          <v-row>
            <v-col cols="6">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.subject') }}</v-list-item-title>
                <v-list-item-subtitle>{{ getSubjectName(selectedTask.subject_id) }}</v-list-item-subtitle>
              </v-list-item>
            </v-col>
            <v-col cols="6">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.student') }}</v-list-item-title>
                <v-list-item-subtitle>{{ getStudentName(selectedTask.student_id) }}</v-list-item-subtitle>
              </v-list-item>
            </v-col>
            <v-col cols="6">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.startDate') }}</v-list-item-title>
                <v-list-item-subtitle>{{ formatDate(selectedTask.start_date) }}</v-list-item-subtitle>
              </v-list-item>
            </v-col>
            <v-col cols="6">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.endDate') }}</v-list-item-title>
                <v-list-item-subtitle>{{ formatDate(selectedTask.end_date) }}</v-list-item-subtitle>
              </v-list-item>
            </v-col>
            <v-col cols="12">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.completionPercent') }}</v-list-item-title>
                <v-list-item-subtitle>
                  <v-progress-linear
                    :model-value="selectedTask.completion_percent"
                    :color="getCompletionColor(selectedTask.completion_percent)"
                    height="20"
                    rounded
                  >
                    <template #default="{ value }">
                      <strong>{{ Math.ceil(value) }}%</strong>
                    </template>
                  </v-progress-linear>
                </v-list-item-subtitle>
              </v-list-item>
            </v-col>
            <v-col cols="12" v-if="selectedTask.task_description">
              <v-list-item>
                <v-list-item-title>{{ $t('task.task.description') }}</v-list-item-title>
                <v-list-item-subtitle>{{ selectedTask.task_description }}</v-list-item-subtitle>
              </v-list-item>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- 任务编辑对话框 -->
    <v-dialog v-model="editDialog" max-width="600">
      <v-card>
        <!-- 固定在对话框顶部的错误消息 -->
        <div class="error-message-container" v-if="isError">
          <v-alert
            type="error"
            variant="tonal"
            closable
            class="mb-0"
            style="width: 100%;"
            @click:close="isError = false"
          >
            {{ errorMessage }}
          </v-alert>
        </div>

        <v-card-title>
          <span>{{ isCreateMode ? $t('task.edit.createTitle') : $t('task.edit.title') }}</span>
          <v-spacer />
          <v-btn
            icon="mdi-close"
            variant="text"
            @click="closeEditDialog"
          />
        </v-card-title>
        <v-card-text>
          <v-form ref="editFormRef">
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.task_name"
                  :label="$t('task.task.name') + ' *'"
                  :placeholder="$t('task.task.name')"
                  variant="outlined"
                  density="compact"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-textarea
                  v-model="editForm.task_description"
                  :label="$t('task.task.description')"
                  :placeholder="$t('task.task.description')"
                  variant="outlined"
                  density="compact"
                  rows="3"
                />
              </v-col>
              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.student_id"
                  :items="studentOptions"
                  :label="$t('task.task.student') + ' *'"
                  variant="outlined"
                  density="compact"
                  required
                />
              </v-col>
              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.subject_id"
                  :items="subjectOptions"
                  :label="$t('task.task.subject') + ' *'"
                  variant="outlined"
                  density="compact"
                  required
                />
              </v-col>
              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.term_id"
                  :items="editTermOptions"
                  :label="$t('task.task.term') + ' *'"
                  :disabled="!editForm.student_id"
                  variant="outlined"
                  density="compact"
                  :hint="!editForm.student_id ? $t('task.filters.selectStudentFirst') : ''"
                  persistent-hint
                  required
                />
              </v-col>
              <v-col cols="12" md="6">
                <!-- <v-text-field
                  v-model="editForm.completion_percent"
                  :label="$t('task.task.completionPercent') + ' *'"
                  :placeholder="$t('task.task.completionPercent')"
                  variant="outlined"
                  density="compact"
                  type="number"
                  min="0"
                  max="100"
                  required
                /> -->
                <v-slider
                  v-model="editForm.completion_percent"
                  :label="$t('task.task.completionPercent') + ' *'"
                  :min="0"
                  :max="100"
                  :step="1"
                  thumb-label="always"
                  persistent-hint
                  :hint="`${editForm.completion_percent}%`"
                >
                  <template #append>
                    <v-text-field
                      v-model="editForm.completion_percent"
                      type="number"
                      min="0"
                      max="100"
                      hide-details
                      density="compact"
                      style="width: 80px;"
                    />
                  </template>
                </v-slider>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  v-model="editForm.start_date"
                  :label="$t('task.task.startDate') + ' *'"
                  variant="outlined"
                  density="compact"
                  type="date"
                  required
                />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  v-model="editForm.end_date"
                  :label="$t('task.task.endDate') + ' *'"
                  variant="outlined"
                  density="compact"
                  type="date"
                  required
                />
              </v-col>

              <!-- 图像显示区域 -->
              <v-col cols="12">
                <v-divider class="my-4" />
                <div class="text-h6 mb-4">{{ $t('task.task.images') }}</div>
              </v-col>

              <v-col cols="12" sm="6" md="4" v-for="index in 5" :key="index">
                <div class="image-container">
                  <div class="image-label">{{ $t('task.task.image') }} {{ index }}</div>
                  <div
                    v-if="imageCache[index]"
                    class="image-preview clickable"
                    @click="openImageDialog(index)"
                  >
                    <img
                      :src="imageCache[index]"
                      :alt="`${$t('task.task.image')} ${index}`"
                      class="preview-image"
                    />
                  </div>
                  <div v-if="imageCache[index]" class="image-actions-bottom">
                    <v-btn
                      icon="mdi-upload"
                      size="small"
                      color="primary"
                      variant="tonal"
                      @click.stop="uploadImage(index)"
                      :title="$t('task.task.updateImage')"
                    />
                    <v-btn
                      icon="mdi-delete"
                      size="small"
                      color="error"
                      variant="tonal"
                      @click.stop="deleteImage(index)"
                      :title="$t('task.task.deleteImage')"
                    />
                  </div>
                  <div
                    v-else-if="imageLoading[index]"
                    class="image-preview loading"
                  >
                    <v-progress-circular
                      indeterminate
                      color="primary"
                      size="32"
                      width="3"
                    />
                  </div>
                  <div
                    v-else
                    class="image-preview empty"
                  >
                    <v-icon size="large" color="grey">mdi-image-off</v-icon>
                    <div class="upload-placeholder">{{ $t('task.task.noImage') }}</div>
                  </div>
                  <div v-if="!imageCache[index] && !imageLoading[index]" class="image-actions-bottom">
                    <v-btn
                      icon="mdi-upload"
                      size="small"
                      color="primary"
                      variant="tonal"
                      @click.stop="uploadImage(index)"
                      :title="$t('task.task.updateImage')"
                    />
                  </div>
                </div>
              </v-col>
            </v-row>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-btn
            v-if="!isCreateMode"
            color="error"
            variant="text"
            prepend-icon="mdi-delete"
            @click="openDeleteDialog(editingTask)"
          >
            {{ $t('common.buttons.delete') }}
          </v-btn>
          <v-spacer />
          <v-btn
            @click="closeEditDialog"
            variant="outlined"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            @click="updateTask"
            color="primary"
            variant="flat"
            :loading="isSaving"
          >
            {{ isCreateMode ? $t('common.buttons.create') : $t('common.buttons.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 删除确认对话框 -->
    <v-dialog v-model="deleteDialog" max-width="400px">
      <v-card>
        <v-card-title class="text-h5 text-error">
          <v-icon icon="mdi-alert" class="mr-2" />
          {{ $t('task.dialog.delete') }}
        </v-card-title>
        <v-card-text>
          <div class="text-body-1 mb-4">
            {{ $t('task.deleteConfirmation.message') }}
          </div>
          <div v-if="taskToDelete" class="bg-grey-lighten-4 pa-3 rounded">
            <div class="d-flex align-center mb-2">
              <div>
                <div class="font-weight-medium">{{ taskToDelete.task_name }}</div>
                <div class="text-caption text-medium-emphasis">
                  {{ getStudentName(taskToDelete.student_id) }} | {{ formatDate(taskToDelete.start_date) }} - {{ formatDate(taskToDelete.end_date) }}
                </div>
              </div>
            </div>
          </div>
          <div class="text-body-2 text-error mt-4">
            <v-icon icon="mdi-alert-circle" size="small" class="mr-1" />
            {{ $t('task.deleteConfirmation.warning') }}
          </div>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="closeDeleteDialog"
            :disabled="isDeleting"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="error"
            variant="elevated"
            prepend-icon="mdi-delete"
            :loading="isDeleting"
            :disabled="isDeleting"
            @click="confirmDeleteTask"
          >
            {{ $t('common.buttons.confirm') + ' ' + $t('common.buttons.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 图像放大查看对话框 -->
    <v-dialog v-model="imageDialog" max-width="800">
      <v-card>
        <v-card-title>
          <span>{{ $t('task.task.image') }} {{ currentImageIndex }}</span>
          <v-spacer />
          <v-btn
            icon="mdi-close"
            variant="text"
            @click="closeImageDialog"
          />
        </v-card-title>
        <v-card-text class="d-flex justify-center align-center image-viewer-container" style="min-height: 500px;">
          <div
            v-if="currentImageSrc"
            class="image-zoom-container"
            @wheel.prevent="handleWheel"
            @mousedown="startDrag"
            @mousemove="doDrag"
            @mouseup="stopDrag"
            @mouseleave="stopDrag"
          >
            <img
              :src="currentImageSrc"
              :alt="`${$t('task.task.image')} ${currentImageIndex}`"
              class="enlarged-image"
              :style="{
                transform: `translate(${imagePosition.x}px, ${imagePosition.y}px) scale(${zoomLevel})`,
                cursor: isDragging ? 'grabbing' : 'grab'
              }"
              @dragstart.prevent
            />
          </div>
          <div v-else-if="currentImageIndex && !currentImageSrc" class="d-flex flex-column align-center">
            <v-progress-circular
              indeterminate
              color="primary"
              size="64"
              width="6"
            />
            <div class="mt-4">{{ $t('task.task.loadingImage') }}</div>
          </div>
          <div v-else class="text-center">
            {{ $t('task.task.noImage') }}
          </div>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- 删除确认对话框 -->
    <v-dialog
      v-model="deleteDialog"
      max-width="500px"
      persistent
    >
      <v-card>
        <v-card-title class="text-h5 bg-error text-white">
          {{ $t('common.messages.dialogs.deleteConfirmation') }}
        </v-card-title>
        <v-card-text class="pt-4">
          <div v-if="isError" class="mb-4">
            <v-alert
              type="error"
              variant="tonal"
              closable
              class="mb-2"
            >
              {{ errorMessage }}
            </v-alert>
          </div>

          <p class="text-body-1 mb-4">{{ $t('task.messages.deleteConfirmation') }}</p>

          <v-card variant="outlined" class="mb-4">
            <v-card-item>
              <v-card-title>{{ taskToDelete?.task_name }}</v-card-title>
            </v-card-item>
          </v-card>

          <v-alert
            type="warning"
            variant="tonal"
            icon="mdi-alert-circle"
            class="mb-0"
          >
            {{ $t('common.messages.deleteWarning') }}
          </v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            @click="closeDeleteDialog"
            variant="outlined"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="error"
            variant="flat"
            :loading="isDeleting"
            @click="confirmDeleteTask"
          >
            {{ $t('common.buttons.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup>
import { onMounted, ref, computed, watch, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { getTasks, getTaskById, getTaskImage, updateTask as updateTaskAPI, deleteTask } from '@/api/taskService.js'
import { getStudents } from '@/api/studentService.js'
import { getSubjects } from '@/api/subjectService.js'
import { getTerms } from '@/api/termService.js'
import { COLOR_MAPPING } from '@/components/constants/colors'
// 从 Labs 正确导入 VCalendar 组件
import { VCalendar } from 'vuetify/labs/VCalendar'

// 在 Composition API 中注册 Labs 组件
defineOptions({
  components: {
    VCalendar
  }
})

const { t } = useI18n()
const authStore = useAuthStore()

// 基础状态
const isLoading = ref(false)
const isError = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 删除功能相关状态
const deleteDialog = ref(false)
const taskToDelete = ref(null)
const isDeleting = ref(false)
const tasks = ref([])

// 日历相关状态
const calendar = ref(null)
const selectedDate = ref(new Date())
const taskDetailDialog = ref(false)
const selectedTask = ref(null)
const isFullscreen = ref(false)

// 筛选相关状态
const filters = ref({
  studentId: null,
  subjectId: null,
  termId: null
})
const isFilterExpanded = ref(true)

// 关联数据
const students = ref([])
const subjects = ref([])
const terms = ref([])

// 计算属性
const studentOptions = computed(() => [
  { title: t('task.filters.allStudents'), value: null },
  ...students.value.map(student => ({
    title: student.student_name,
    value: student.student_id
  }))
])

const subjectOptions = computed(() => [
  { title: t('task.filters.allSubjects'), value: null },
  ...subjects.value.map(subject => ({
    title: subject.subject_name,
    value: subject.subject_id
  }))
])

// 学期选项根据选择的学生进行筛选
const termOptions = computed(() => {
  // 如果没有选择学生或选择了"所有学生"，只显示"所有学期"选项
  if (!filters.value.studentId) {
    return [{ title: t('task.filters.allTerms'), value: null }]
  }

  // 筛选属于选定学生的学期
  const filteredTerms = terms.value.filter(term =>
    term.student_id === filters.value.studentId
  )

  return [
    { title: t('task.filters.allTerms'), value: null },
    ...filteredTerms.map(term => ({
      title: term.term_name,
      value: term.term_id
    }))
  ]
})

// 监听学生选择变化，重置学期选择
watch(() => filters.value.studentId, (newStudentId, oldStudentId) => {
  // 当学生选择发生变化时，重置学期选择
  if (newStudentId !== oldStudentId) {
    filters.value.termId = null
    console.log('Student selection changed, term selection reset')
  }
})

// 将任务数据转换为日历事件格式
const calendarEvents = computed(() => {
  if (!tasks.value || tasks.value.length === 0) {
    console.log('No tasks available for calendar')
    return []
  }

  const events = tasks.value.map((task, index) => {
    // 解析日期
    const startDate = new Date(task.start_date)
    const endDate = new Date(task.end_date)

    console.log(`Task ${index}:`, {
      original: task,
      startDate: startDate,
      endDate: endDate,
      isValidStart: !isNaN(startDate.getTime()),
      isValidEnd: !isNaN(endDate.getTime())
    })

    // Vuetify v-calendar 事件标准格式
    return {
      name: task.task_name, // Vuetify v-calendar 使用 name 属性
      start: startDate,
      end: endDate,
      color: getSubjectColor(task.subject_id),
      timed: false, // 设置为全天事件
      // 额外数据用于调试和点击处理
      id: task.task_id,
      title: task.task_name,
      taskData: {
        id: task.task_id,
        completion_percent: task.completion_percent,
        subject_id: task.subject_id,
        student_id: task.student_id,
        description: task.task_description
      }
    }
  })

  console.log('Calendar events formatted for Vuetify:', events)
  return events
})

// 获取学科颜色
const getSubjectColor = (subjectId) => {
  const subject = subjects.value.find(s => s.subject_id === subjectId)
  if (subject && subject.calendar_color) {
    // 如果有预定义的颜色映射，使用映射值；否则直接使用颜色键
    return COLOR_MAPPING[subject.calendar_color] || subject.calendar_color
  }
  // 如果没有找到学科或没有设置颜色，返回默认颜色
  return '#9E9E9E' // 默认灰色
}

// 根据背景色计算文字颜色（黑色或白色）
// 注释掉未使用的方法
/* const getTextColor = (backgroundColor) => {
  // 如果背景色是十六进制颜色值
  if (backgroundColor && backgroundColor.startsWith('#')) {
    // 移除 # 符号并解析 RGB 值
    const hex = backgroundColor.replace('#', '')
    const r = parseInt(hex.substring(0, 2), 16)
    const g = parseInt(hex.substring(2, 4), 16)
    const b = parseInt(hex.substring(4, 6), 16)

    // 计算亮度
    const brightness = (r * 299 + g * 587 + b * 114) / 1000

    // 如果亮度大于 128，使用黑色文字，否则使用白色文字
    return brightness > 128 ? '#000000' : '#FFFFFF'
  }

  // 对于其他颜色值，使用白色文字
  return '#FFFFFF'
} */

// 获取完成度对应的颜色
const getCompletionColor = (percent) => {
  if (percent >= 100) return 'success'
  if (percent >= 70) return 'info'
  if (percent >= 30) return 'warning'
  return 'error'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''

  // 如果是字符串，转换为 Date 对象
  const dateObj = typeof date === 'string' ? new Date(date) : date

  if (isNaN(dateObj.getTime())) return ''

  return dateObj.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取学生名称
const getStudentName = (studentId) => {
  const student = students.value.find(s => s.student_id === studentId)
  return student ? student.student_name : `Student ${studentId}`
}

// 获取学科名称
const getSubjectName = (subjectId) => {
  const subject = subjects.value.find(s => s.subject_id === subjectId)
  return subject ? subject.subject_name : `Subject ${subjectId}`
}

// 获取学科简称（取学科名称的第一个字符）
const getSubjectShortName = (subjectId) => {
  const subject = subjects.value.find(s => s.subject_id === subjectId)
  if (subject && subject.subject_name) {
    // 取学科名称的第一个字符，如果第一个字符是英文字母则大写
    const firstChar = subject.subject_name.charAt(0)
    return /^[\u4e00-\u9fa5]$/.test(firstChar) ? firstChar : firstChar.toUpperCase()
  }
  return '学' // 默认显示"学"
}

// 获取学期名称
// eslint-disable-next-line no-unused-vars
const getTermName = (termId) => {
  const term = terms.value.find(t => t.term_id === termId)
  return term ? term.term_name : `Term ${termId}`
}

// API调用函数
const fetchTasks = async (filterParams = null) => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    // 使用传入的筛选参数或当前筛选条件
    const params = filterParams || {
      student_id: filters.value.studentId,
      subject_id: filters.value.subjectId,
      term_id: filters.value.termId
    }

    console.log('Fetching tasks with filters:', params)

    const response = await getTasks(params)

    // 现在API返回的直接是数组（已经处理了所有分页）
    tasks.value = Array.isArray(response) ? response : []

    console.log('Fetched tasks:', tasks.value)
    console.log('Sample task dates:', tasks.value[0] ? {
      start_date: tasks.value[0].start_date,
      end_date: tasks.value[0].end_date,
      start_parsed: new Date(tasks.value[0].start_date),
      end_parsed: new Date(tasks.value[0].end_date)
    } : 'No tasks')
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('task.messages.loadError')
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

// 获取单个任务的详细信息 - 此方法已被onEventClick中的直接调用getTaskById替代，可以移除
// const fetchTaskDetail = async (taskId) => {
//   try {
//     const taskDetail = await getTaskById(taskId)
//     console.log('Fetched task detail:', taskDetail)
//     return taskDetail
//   } catch (error) {
//     console.error('Failed to fetch task detail:', error)
//     errorMessage.value = error?.response?.data?.detail || error?.message || t('task.messages.loadError')
//     isError.value = true
//     setTimeout(() => {
//       isError.value = false
//       errorMessage.value = ''
//     }, 3000)
//     throw error
//   }
// }

const fetchStudents = async () => {
  try {
    const students_data = await getStudents()
    console.log('Students data:', students_data)

    // 现在API返回的直接是数组（已经处理了所有分页）
    students.value = Array.isArray(students_data) ? students_data : []
  } catch (error) {
    console.error('Failed to fetch students:', error)
  }
}

const fetchSubjects = async () => {
  try {
    const subjects_data = await getSubjects()
    console.log('Subjects data:', subjects_data)

    // 现在API返回的直接是数组（已经处理了所有分页）
    subjects.value = Array.isArray(subjects_data) ? subjects_data : []
  } catch (error) {
    console.error('Failed to fetch subjects:', error)
  }
}

const fetchTerms = async () => {
  try {
    const terms_data = await getTerms()
    console.log('Terms data:', terms_data)

    // 现在API返回的直接是数组（已经处理了所有分页）
    terms.value = Array.isArray(terms_data) ? terms_data : []
  } catch (error) {
    console.error('Failed to fetch terms:', error)
  }
}

// 事件处理函数
const onEventClick = async (event) => {
  console.log('Calendar event clicked:', event)
  // 从事件中获取任务ID
  const taskId = event.taskData?.id || event.id

  if (taskId) {
    try {
      // 显示加载状态
      isLoading.value = true

      // 从后端获取完整的任务详情
      const taskDetail = await getTaskById(taskId)

      // 打开编辑对话框
      openEditDialog(taskDetail)
    } catch (error) {
      console.error('Failed to fetch task detail:', error)
      // 显示错误消息
      errorMessage.value = error?.message || t('task.messages.loadError')
      isError.value = true
      setTimeout(() => {
        isError.value = false
        errorMessage.value = ''
      }, 3000)
    } finally {
      // 隐藏加载状态
      isLoading.value = false
    }
  } else {
    console.error('Task ID not found for event:', event)
  }
}

const onDateClick = (date) => {
  console.log('onDateClick called with date:', date);

  // v-calendar的click:date事件应该传递日期对象，而不是点击事件
  // 但如果收到的是点击事件，我们需要处理这种情况
  if (date) {
    if (date.target) {
      // 这是一个DOM事件对象，而不是日期
      console.log('Received DOM event instead of date, using current date');
      selectedDate.value = new Date();
      // 传递null给openCreateDialog，它会使用当前日期
      openCreateDialog(null);
    } else {
      // 这是一个正常的日期对象
      console.log('Received valid date object');
      selectedDate.value = date;
      // 点击日历空白处，打开新增对话框
      openCreateDialog(date);
    }
  } else {
    // 如果没有收到日期参数，使用当前日期
    console.log('No date received, using current date');
    selectedDate.value = new Date();
    openCreateDialog(null);
  }
}

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

const toggleFilterPanel = () => {
  isFilterExpanded.value = !isFilterExpanded.value
}

// 监听键盘事件，用ESC退出全屏
const handleKeydown = (event) => {
  if (event.key === 'Escape' && isFullscreen.value) {
    isFullscreen.value = false
  }
}

const applyFilters = async () => {
  console.log('Applying filters:', filters.value)
  // 直接使用当前筛选条件调用 fetchTasks
  await fetchTasks()
}

const clearFilters = async () => {
  filters.value = {
    studentId: null,
    subjectId: null,
    termId: null
  }
  console.log('All filters cleared')
  // 清除筛选后重新获取所有数据
  await fetchTasks({})
}

// 学生选择变化处理函数
const onStudentChange = async (studentId) => {
  filters.value.studentId = studentId
  // 当学生选择变化时，自动重置学期选择
  filters.value.termId = null
  console.log('Student changed to:', studentId, 'Term reset to null')

  // 自动应用筛选
  if (studentId || filters.value.subjectId) {
    await fetchTasks()
  }
}

// 学科选择变化处理函数
const onSubjectChange = async (subjectId) => {
  filters.value.subjectId = subjectId
  console.log('Subject changed to:', subjectId)

  // 自动应用筛选
  if (subjectId || filters.value.studentId || filters.value.termId) {
    await fetchTasks()
  }
}

// 学期选择变化处理函数
const onTermChange = async (termId) => {
  filters.value.termId = termId
  console.log('Term changed to:', termId)

  // 自动应用筛选
  if (termId || filters.value.studentId || filters.value.subjectId) {
    await fetchTasks()
  }
}

// 编辑功能相关状态
const editDialog = ref(false)
const isCreateMode = ref(false) // 标记是否为创建模式
const editingTask = ref(null)
const editForm = ref({
  task_name: '',
  task_description: '',
  student_id: null,
  subject_id: null,
  term_id: null,
  start_date: '',
  end_date: '',
  completion_percent: 0,
  // 图像数据
  image_01: null,
  image_01_mime_type: null,
  image_02: null,
  image_02_mime_type: null,
  image_03: null,
  image_03_mime_type: null,
  image_04: null,
  image_04_mime_type: null,
  image_05: null,
  image_05_mime_type: null
})
const isSaving = ref(false)
const editFormRef = ref(null)

// 为编辑对话框创建独立的学期选项计算属性
const editTermOptions = computed(() => {
  // 如果没有选择学生，显示所有学期
  if (!editForm.value.student_id) {
    return [
      { title: t('task.filters.allTerms'), value: null },
      ...terms.value.map(term => ({
        title: term.term_name,
        value: term.term_id
      }))
    ]
  }

  // 筛选属于选定学生的学期
  const filteredTerms = terms.value.filter(term =>
    term.student_id === editForm.value.student_id
  )

  return [
    { title: t('task.filters.allTerms'), value: null },
    ...filteredTerms.map(term => ({
      title: term.term_name,
      value: term.term_id
    }))
  ]
})

// 图像放大查看相关状态
const imageDialog = ref(false)
const currentImageIndex = ref(null)
const currentImageSrc = ref(null)
const zoomLevel = ref(1) // 缩放级别，1表示原始大小
const imagePosition = ref({ x: 0, y: 0 }) // 图像位置，用于拖拽平移
const isDragging = ref(false) // 是否正在拖拽
const dragStart = ref({ x: 0, y: 0 }) // 拖拽起始位置

// 图像加载状态管理
const imageLoading = ref({
  1: false,
  2: false,
  3: false,
  4: false,
  5: false
})

const imageCache = ref({
  1: null,
  2: null,
  3: null,
  4: null,
  5: null
})

// 编辑功能方法
const openEditDialog = async (task) => {
  // 设置为编辑模式
  isCreateMode.value = false;
  console.log('Setting isCreateMode to false for editing existing task');

  // 清理图像缓存
  Object.keys(imageCache.value).forEach(key => {
    if (imageCache.value[key]) {
      URL.revokeObjectURL(imageCache.value[key]);
      imageCache.value[key] = null;
    }
  });

  // 清理图片删除标记
  for (let i = 1; i <= 5; i++) {
    const imageKey = `image_0${i}`;
    editForm.value[`delete_${imageKey}`] = false;
  }

  // 重置加载状态
  Object.keys(imageLoading.value).forEach(key => {
    imageLoading.value[key] = false;
  });

  editingTask.value = task
  editForm.value = {
    task_name: task.task_name || '',
    task_description: task.task_description || '',
    student_id: task.student_id || null,
    subject_id: task.subject_id || null,
    term_id: task.term_id || null,
    start_date: task.start_date ? task.start_date.split('T')[0] : '',
    end_date: task.end_date ? task.end_date.split('T')[0] : '',
    completion_percent: task.completion_percent || 0,
    // 图像数据
    image_01: task.image_01 || null,
    image_01_mime_type: task.image_01_mime_type || null,
    image_02: task.image_02 || null,
    image_02_mime_type: task.image_02_mime_type || null,
    image_03: task.image_03 || null,
    image_03_mime_type: task.image_03_mime_type || null,
    image_04: task.image_04 || null,
    image_04_mime_type: task.image_04_mime_type || null,
    image_05: task.image_05 || null,
    image_05_mime_type: task.image_05_mime_type || null
  }
  console.log('Editing task data:', task)
  console.log('Converted form data:', editForm.value)
  editDialog.value = true

  // 对话框打开后，预加载所有图片
  if (task && task.task_id) {
    // 使用setTimeout让对话框先显示出来，然后再加载图片
    setTimeout(() => {
      // 尝试预加载5个图片位置的图片
      for (let i = 1; i <= 5; i++) {
        // 检查是否有key或etag信息，如果有则尝试加载图片
        const imageKey = `image_0${i}`;
        const imageKeyField = `${imageKey}_key`;
        const imageEtagField = `${imageKey}_etag`;

        // 添加调试日志
        console.log(`Checking image ${i} for preloading:`, {
          hasKey: !!task[imageKeyField],
          hasEtag: !!task[imageEtagField],
          key: task[imageKeyField],
          etag: task[imageEtagField]
        });

        // 尝试加载图片，无论是否有key或etag信息
        loadTaskImage(task.task_id, i)
          .then(() => {
            console.log(`Image ${i} preloaded successfully`);
          })
          .catch(error => {
            // 如果是404错误，说明该索引位置没有图片，这是正常的
            if (error.response && error.response.status === 404) {
              console.log(`No image found at index ${i} - this is normal`);
            } else {
              console.error(`Failed to preload image ${i}:`, error);
            }
          });
      }
    }, 100);
  }
}

// 打开创建对话框
const openCreateDialog = (date) => {
  // 添加调试信息，记录传入的date参数
  console.log('openCreateDialog called with date:', date);
  console.log('date type:', typeof date);
  if (date) {
    console.log('date properties:', Object.keys(date));
  }

  // 清理图像缓存
  Object.keys(imageCache.value).forEach(key => {
    if (imageCache.value[key]) {
      URL.revokeObjectURL(imageCache.value[key]);
      imageCache.value[key] = null;
    }
  });

  // 清理图片删除标记
  for (let i = 1; i <= 5; i++) {
    const imageKey = `image_0${i}`;
    editForm.value[`delete_${imageKey}`] = false;
  }

  // 重置加载状态
  Object.keys(imageLoading.value).forEach(key => {
    imageLoading.value[key] = false;
  });

  // 设置为创建模式
  isCreateMode.value = true;
  editingTask.value = null;

  // 初始化表单数据 - 增强对各种date参数格式的处理
  let formattedDate;
  try {
    // 处理不同格式的日期参数
    if (date) {
      if (date.date) {
        // v-calendar可能传递{date: '2023-01-01'}格式
        console.log('Using date.date property:', date.date);
        formattedDate = new Date(date.date).toISOString().split('T')[0];
      } else if (date instanceof Date) {
        // 直接传递Date对象
        console.log('Using Date object');
        formattedDate = date.toISOString().split('T')[0];
      } else if (typeof date === 'string') {
        // 直接传递日期字符串
        console.log('Using date string');
        formattedDate = new Date(date).toISOString().split('T')[0];
      } else if (date.year && date.month && date.day) {
        // v-calendar可能传递{year: 2023, month: 1, day: 1}格式
        console.log('Using year/month/day properties');
        formattedDate = new Date(date.year, date.month - 1, date.day).toISOString().split('T')[0];
      } else {
        // 其他情况，尝试转换为日期
        console.log('Attempting to convert unknown date format');
        const dateObj = new Date(date);
        if (!isNaN(dateObj.getTime())) {
          formattedDate = dateObj.toISOString().split('T')[0];
        } else {
          throw new Error('Invalid date format');
        }
      }
    } else {
      throw new Error('No date provided');
    }
  } catch (error) {
    // 如果日期处理出错，使用当前日期
    console.warn('Error processing date, using current date:', error);
    formattedDate = new Date().toISOString().split('T')[0];
  }

  editForm.value = {
    task_name: '',
    task_description: '',
    student_id: filters.value.studentId || null,
    subject_id: filters.value.subjectId || null,
    term_id: filters.value.termId || null,
    start_date: formattedDate,
    end_date: formattedDate,
    completion_percent: 0,
    // 图像数据初始化为空
    image_01: null,
    image_01_mime_type: null,
    image_02: null,
    image_02_mime_type: null,
    image_03: null,
    image_03_mime_type: null,
    image_04: null,
    image_04_mime_type: null,
    image_05: null,
    image_05_mime_type: null
  };

  console.log('Creating new task with date:', formattedDate);
  editDialog.value = true;
}

const closeEditDialog = () => {
  editDialog.value = false;
  editingTask.value = null;
  isCreateMode.value = false;

  // 清除错误消息状态
  isError.value = false;
  errorMessage.value = '';

  editForm.value = {
    task_name: '',
    task_description: '',
    student_id: null,
    subject_id: null,
    term_id: null,
    start_date: '',
    end_date: '',
    completion_percent: 0,
    // 图像数据
    image_01: null,
    image_01_mime_type: null,
    image_02: null,
    image_02_mime_type: null,
    image_03: null,
    image_03_mime_type: null,
    image_04: null,
    image_04_mime_type: null,
    image_05: null,
    image_05_mime_type: null
  }

  // 清理图像缓存
  Object.keys(imageCache.value).forEach(key => {
    if (imageCache.value[key]) {
      URL.revokeObjectURL(imageCache.value[key]);
      imageCache.value[key] = null;
    }
  });

  // 重置加载状态
  Object.keys(imageLoading.value).forEach(key => {
    imageLoading.value[key] = false;
  });
}

const closeImageDialog = () => {
  imageDialog.value = false
  currentImageIndex.value = null
  currentImageSrc.value = null
  resetZoom() // 关闭对话框时重置缩放
  resetPosition() // 关闭对话框时重置位置
}

// 删除功能方法
const openDeleteDialog = (task) => {
  taskToDelete.value = task
  deleteDialog.value = true
}

const closeDeleteDialog = () => {
  deleteDialog.value = false
  taskToDelete.value = null
}

const confirmDeleteTask = async () => {
  if (!taskToDelete.value?.task_id) {
    console.error('Unable to get task ID')
    return
  }

  isDeleting.value = true

  try {
    console.log('Deleting task:', taskToDelete.value)

    // 1. 调用API删除任务
    await deleteTask(taskToDelete.value.task_id)

    // 2. 从本地列表中移除任务
    const index = tasks.value.findIndex(t => t.task_id === taskToDelete.value.task_id)
    if (index !== -1) {
      tasks.value.splice(index, 1)
    }

    // 3. 显示成功消息
    successMessage.value = t('task.messages.deleteSuccess', { name: taskToDelete.value.task_name })
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)

    closeDeleteDialog()
    closeEditDialog() // 如果正在编辑，也关闭编辑对话框

  } catch (error) {
    console.error('Deletion failed:', error)
    // 在删除对话框中显示错误，但不关闭对话框
    errorMessage.value = error.message || t('task.messages.deleteError')
    isError.value = true
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isDeleting.value = false
  }
}

// 图像缩放功能 - 这些方法已被鼠标滚轮缩放功能替代，可以移除
// const zoomIn = () => {
//   if (zoomLevel.value < 3) { // 最大放大3倍
//     zoomLevel.value += 0.25
//   }
// }

// const zoomOut = () => {
//   if (zoomLevel.value > 0.5) { // 最小缩小到0.5倍
//     zoomLevel.value -= 0.25
//   }
// }

const resetZoom = () => {
  zoomLevel.value = 1 // 重置为原始大小
}

// 图像拖拽平移功能
const startDrag = (event) => {
  if (event.button === 0) { // 只响应鼠标左键
    isDragging.value = true
    dragStart.value = {
      x: event.clientX - imagePosition.value.x,
      y: event.clientY - imagePosition.value.y
    }
  }
}

const doDrag = (event) => {
  if (isDragging.value) {
    imagePosition.value = {
      x: event.clientX - dragStart.value.x,
      y: event.clientY - dragStart.value.y
    }
  }
}

const stopDrag = () => {
  isDragging.value = false
}

const resetPosition = () => {
  imagePosition.value = { x: 0, y: 0 }
}

// 鼠标滚轮缩放功能
const handleWheel = (event) => {
  event.preventDefault()

  // 获取鼠标在图像上的相对位置
  //const container = event.currentTarget
  // const rect = container.getBoundingClientRect()

  // 计算缩放前的缩放级别
  // const oldZoom = zoomLevel.value

  // 根据滚轮方向调整缩放级别
  if (event.deltaY < 0) { // 向上滚动，放大
    if (zoomLevel.value < 3) {
      zoomLevel.value += 0.1
    }
  } else { // 向下滚动，缩小
    if (zoomLevel.value > 0.5) {
      zoomLevel.value -= 0.1
    }
  }

  // 限制缩放范围
  zoomLevel.value = Math.max(0.5, Math.min(3, zoomLevel.value))
}

// 上传图片方法
const uploadImage = async (index) => {
  // 创建文件选择器
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*'; // 只接受图片文件

  // 监听文件选择事件
  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      // 设置加载状态
      imageLoading.value[index] = true;

      // 读取文件为base64
      const reader = new FileReader();
      reader.onload = (event) => {
        const base64String = event.target.result;

        // 更新表单数据
        const imageKey = `image_0${index}`;
        // 重要：如果之前标记了删除，现在上传新图片，需要取消删除标记
        editForm.value[`delete_${imageKey}`] = false;

        // 清除旧的图片数据，确保不会有冲突
        editForm.value[imageKey] = null;

        // 设置新的图片数据
        editForm.value[`${imageKey}_mime_type`] = file.type;
        editForm.value[`${imageKey}_file_name`] = file.name;
        editForm.value[`${imageKey}_base64`] = base64String;

        // 更新图片缓存，立即显示上传的图片
        if (imageCache.value[index]) {
          URL.revokeObjectURL(imageCache.value[index]);
        }
        imageCache.value[index] = URL.createObjectURL(file);

        console.log(`Image ${index} uploaded successfully:`, {
          fileName: file.name,
          mimeType: file.type,
          hasBase64: !!base64String,
          deleteFlag: editForm.value[`delete_${imageKey}`]
        });

        // 重置加载状态
        imageLoading.value[index] = false;
      };

      reader.readAsDataURL(file);
    } catch (error) {
      console.error(`Failed to upload image ${index}:`, error);
      errorMessage.value = t('task.messages.uploadImageError');
      isError.value = true;
      setTimeout(() => {
        isError.value = false;
        errorMessage.value = '';
      }, 3000);

      // 重置加载状态
      imageLoading.value[index] = false;
    }
  };

  // 触发文件选择器
  input.click();
};

// 删除图片方法
const deleteImage = (index) => {
  // 确认删除
  if (confirm(t('task.messages.confirmDeleteImage'))) {
    // 更新表单数据，标记为删除
    const imageKey = `image_0${index}`;
    editForm.value[`delete_${imageKey}`] = true;

    // 清除图片缓存
    if (imageCache.value[index]) {
      URL.revokeObjectURL(imageCache.value[index]);
      imageCache.value[index] = null;
    }

    // 清除其他相关字段
    editForm.value[`${imageKey}_mime_type`] = null;
    editForm.value[`${imageKey}_file_name`] = null;
    editForm.value[`${imageKey}_base64`] = null;
  }
};

// 图像加载方法
const loadTaskImage = async (taskId, imageIndex) => {
  // 检查缓存
  if (imageCache.value[imageIndex]) {
    return imageCache.value[imageIndex];
  }

  // 设置加载状态
  imageLoading.value[imageIndex] = true;

  try {
    const imageBlob = await getTaskImage(taskId, imageIndex);
    const imageUrl = URL.createObjectURL(imageBlob);

    // 缓存图像URL
    imageCache.value[imageIndex] = imageUrl;

    return imageUrl;
  } catch (error) {
    // 如果是404错误，说明该索引位置没有图片，这是正常的
    if (error.response && error.response.status === 404) {
      console.log(`No image found at index ${imageIndex} - this is normal`);
      return null;
    }
    console.error(`Failed to load task image ${imageIndex}:`, error);
    throw error;
  } finally {
    imageLoading.value[imageIndex] = false;
  }
}

// 图像放大查看方法（更新版）
const openImageDialog = async (index) => {
  // 首先检查是否有缓存的图像
  if (imageCache.value[index]) {
    // 使用已缓存的图像
    currentImageIndex.value = index;
    currentImageSrc.value = imageCache.value[index];
    imageDialog.value = true;
  } else if (editingTask.value && editingTask.value.task_id) {
    // 从API加载图像
    try {
      // 显示加载对话框
      currentImageIndex.value = index;
      currentImageSrc.value = null; // 初始化为null，显示加载状态
      imageDialog.value = true;

      // 加载图像
      const imageUrl = await loadTaskImage(editingTask.value.task_id, index);

      // 更新图像源
      if (imageDialog.value && currentImageIndex.value === index) {
        currentImageSrc.value = imageUrl;
      }
    } catch (error) {
      // 如果是404错误，说明该索引位置没有图片，这是正常的
      if (error.response && error.response.status === 404) {
        console.log(`No image found at index ${index} - this is normal`);
        // 关闭对话框，但不显示错误消息
        imageDialog.value = false;
      } else {
        console.error(`Failed to open image dialog for image ${index}:`, error);
        // 显示错误消息
        errorMessage.value = t('task.messages.loadImageError');
        isError.value = true;
        setTimeout(() => {
          isError.value = false;
          errorMessage.value = '';
        }, 3000);

        // 关闭对话框
        imageDialog.value = false;
      }
    }
  } else {
    // 没有图像可显示
    console.log(`No image data available for index ${index}`);
  }
}

// 导入创建任务API
import { createTask as createTaskAPI } from '@/api/taskService'

const updateTask = async () => {
  isSaving.value = true
  try {
    console.log('Form data before update/create:', editForm.value)

    // 验证必填字段
    if (!editForm.value.task_name) {
      throw new Error(t('task.validation.nameRequired') || '作业名称不能为空')
    }
    // 作业描述可以为空，不需要验证
    if (!editForm.value.student_id) {
      throw new Error(t('task.validation.studentRequired') || '请选择学生')
    }
    if (!editForm.value.subject_id) {
      throw new Error(t('task.validation.subjectRequired') || '请选择学科')
    }
    if (!editForm.value.term_id) {
      throw new Error(t('task.validation.termRequired') || '请选择学期')
    }
    if (editForm.value.completion_percent === undefined || editForm.value.completion_percent === null) {
      throw new Error(t('task.validation.completionRequired') || '请输入完成度')
    }
    if (!editForm.value.start_date) {
      throw new Error(t('task.validation.startDateRequired') || '请选择开始日期')
    }
    if (!editForm.value.end_date) {
      throw new Error(t('task.validation.endDateRequired') || '请选择截止日期')
    }

    // 构建要发送的数据
    const taskData = {
      task_name: editForm.value.task_name,
      task_description: editForm.value.task_description,
      student_id: parseInt(editForm.value.student_id),
      subject_id: parseInt(editForm.value.subject_id),
      term_id: editForm.value.term_id ? parseInt(editForm.value.term_id) : null,
      start_date: new Date(editForm.value.start_date).toISOString(),
      end_date: new Date(editForm.value.end_date).toISOString(),
      completion_percent: parseInt(editForm.value.completion_percent)
    }

    // 添加图片上传和删除相关数据
    for (let i = 1; i <= 5; i++) {
      const imageKey = `image_0${i}`;

      // 处理图片上传 - 优先处理上传，因为上传会覆盖删除标记
      if (editForm.value[`${imageKey}_base64`]) {
        // 如果有新上传的图片，确保删除标记为false
        taskData[`delete_${imageKey}`] = false;

        // 添加图片数据
        taskData[`${imageKey}_mime_type`] = editForm.value[`${imageKey}_mime_type`];
        taskData[`${imageKey}_file_name`] = editForm.value[`${imageKey}_file_name`];
        taskData[`${imageKey}_base64`] = editForm.value[`${imageKey}_base64`];

        console.log(`Sending new image data for ${imageKey}`);
      }
      // 处理图片删除 - 只有在没有新上传图片的情况下才处理删除
      else if (editForm.value[`delete_${imageKey}`]) {
        taskData[`delete_${imageKey}`] = true;
        console.log(`Marking ${imageKey} for deletion`);
      }
    }

    console.log('Sending data:', taskData)

    let result;

    // 根据模式决定是创建还是更新任务
    if (isCreateMode.value) {
      // 创建新任务
      console.log('Creating new task...');
      result = await createTaskAPI(taskData);

      // 将新任务添加到任务列表
      tasks.value.push(result);
      console.log('Task created successfully:', result);
    } else {
      // 更新现有任务
      console.log('Updating existing task...');
      result = await updateTaskAPI(editingTask.value.task_id, taskData);

      // 更新本地列表中的任务
      const index = tasks.value.findIndex(t => t.task_id === editingTask.value.task_id);
      if (index !== -1) {
        tasks.value[index] = { ...tasks.value[index], ...result };
      }
      console.log('Task updated successfully:', result);
    }

    // 关闭对话框
    closeEditDialog();

  } catch (error) {
    console.error('Operation failed:', error);
    errorMessage.value = error.message || (isCreateMode.value ? '创建作业失败' : t('task.messages.updateError'));
    isError.value = true;
    // 不再使用setTimeout自动清除错误消息，而是让用户手动关闭或在对话框关闭时清除

    // 滚动到对话框顶部，确保错误消息可见
    setTimeout(() => {
      const dialogElement = document.querySelector('.v-dialog--active');
      if (dialogElement) {
        dialogElement.scrollTop = 0;
      }
    }, 100);
  } finally {
    isSaving.value = false;
  }
}

// 组件挂载
onMounted(() => {
  if (authStore && authStore.initializeAuth) {
    authStore.initializeAuth()
  }

  // 并行获取所有数据，初始加载时不使用筛选
  Promise.all([
    fetchTasks({}), // 传入空对象获取所有任务
    fetchStudents(),
    fetchSubjects(),
    fetchTerms()
  ])

  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 监听编辑表单中学生选择的变化，用于更新学期选项
watch(() => editForm.value.student_id, (newStudentId, oldStudentId) => {
  // 当学生选择发生变化时，如果当前选择的学期不属于新选择的学生，则重置学期选择
  if (newStudentId !== oldStudentId && editForm.value.term_id) {
    const termBelongsToStudent = terms.value.some(
      term => term.term_id === editForm.value.term_id && term.student_id === newStudentId
    )

    if (!termBelongsToStudent) {
      editForm.value.term_id = null
    }
  }
})
</script>

<style scoped>
.task-calendar {
  min-height: 600px;
}

.task-calendar :deep(.v-calendar-daily__day-interval) {
  cursor: pointer;
}

.task-calendar :deep(.v-calendar-event) {
  cursor: pointer;
  transition: all 0.2s;
}

.task-calendar :deep(.v-calendar-event:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 错误消息容器样式 */
.error-message-container {
  position: sticky;
  top: 0;
  z-index: 100;
  width: 100%;
}

/* 自定义事件样式 */
.custom-event {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #E0E0E0; /* 未完成部分使用灰色背景 */
  border: 1px solid transparent; /* 默认透明边框 */
  cursor: pointer;
  transform: scale(1);
  transition: all 0.2s;
}

/* 图片操作按钮样式 */
.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.2s;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 4px;
  padding: 2px;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

/* 图片下方操作按钮样式 */
.image-actions-bottom {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 8px;
}

.upload-placeholder {
  margin-top: 5px;
  font-size: 0.8rem;
  color: #666;
  text-align: center;
}

.custom-event:hover {
  transform: scale(1.1); /* 悬停时放大10% */
  border-color: #000000; /* 悬停时显示黑色边框 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10; /* 确保放大时在其他元素之上 */
}

.event-content {
  position: relative;
  z-index: 2;
  padding: 2px 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 0.8rem;
  font-weight: 500;
  color: #000000; /* 默认黑色文字 */
}

.subject-tag {
  margin-right: 4px;
}

.completion-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.completion-fill {
  height: 100%;
  transition: width 0.3s ease;
}

/* 图像容器样式 */
.image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fafafa;
}

.image-label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #616161;
}

.image-preview {
  width: 100%;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border-radius: 4px;
  background-color: #eeeeee;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.no-image {
  width: 100%;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #9e9e9e;
  font-style: italic;
  flex-direction: column;
}

/* 图像加载提示 */
.image-hint {
  font-size: 12px;
  margin-top: 8px;
  color: #1976d2;
  text-align: center;
}

/* 图像加载状态 */
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

/* 可点击的图像预览 */
.clickable {
  cursor: pointer;
  transition: transform 0.2s;
}

.clickable:hover {
  transform: scale(1.05);
}

/* 放大图像样式 */
.image-viewer-container {
  overflow: hidden;
  position: relative;
}

.image-zoom-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.enlarged-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  transition: transform 0.2s ease;
  transform-origin: center center;
  user-select: none;
}

/* 任务布局容器 */
.task-layout {
  height: calc(100vh - 270px);
  overflow: hidden;
}

/* 筛选面板容器 */
.filter-panel-container {
  width: 300px;
  min-width: 300px;
  max-width: 300px;
  transition: all 0.4s cubic-bezier(0.4, 0.0, 0.2, 1);
  overflow: hidden;
  margin-right: 16px;
}

.filter-panel-container.filter-panel-collapsed {
  width: 0;
  min-width: 0;
  max-width: 0;
  margin-right: 0;
  transform: translateX(-100%);
}

.filter-panel-card {
  width: 300px;
  min-width: 300px;
}

/* 日历容器 */
.calendar-container {
  flex: 1;
  transition: all 0.4s cubic-bezier(0.4, 0.0, 0.2, 1);
  min-width: 0;
}

.calendar-container.calendar-full-width {
  width: 100%;
}

/* 筛选器面板样式 */
.filter-panel {
  position: sticky;
  top: 20px;
}

/* 筛选器卡片高度自适应 */
.filter-panel .v-card {
  min-height: 100%;
}

/* 过渡动画 */
.transition-all {
  transition: all 0.3s ease-in-out;
}

/* 加载遮罩层样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  border-radius: 4px;
}

/* 全屏模式优化 */
.fullscreen-calendar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: white;
}

/* 响应式设计 */
@media (max-width: 960px) {
  .filter-panel {
    position: static;
    margin-bottom: 16px;
  }

  .task-layout {
    flex-direction: column;
    height: auto;
  }

  .filter-panel-container {
    width: 100%;
    max-width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
  }

  .filter-panel-container.filter-panel-collapsed {
    height: 0;
    margin-bottom: 0;
    transform: translateY(-100%);
  }

  .calendar-container {
    height: calc(100vh - 350px);
  }
}
</style>
