<script setup>
import { onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { getSubjects, updateSubject, createSubject, deleteSubject } from '@/api/subjectService.js'
import { COLOR_MAPPING, COLOR_KEYS } from '@/components/constants/colors'

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

const isLoading = ref(false)
const isError = ref(false)
const errorMessage = ref('')
const subjects = ref([])

// 编辑功能相关状态
const editDialog = ref(false)
const editingSubject = ref(null)
const editForm = ref({
  subject_name: '',
  enabled_flag: 'Y',
  primary_flag: 'N',
  calendar_color: '',
  sort_sequence: 0
})
const isSaving = ref(false)
const successMessage = ref('')
const saveErrorMessage = ref('')

// 新增功能相关状态
const createDialog = ref(false)
const createForm = ref({
  subject_name: '',
  enabled_flag: 'Y',
  primary_flag: 'N',
  calendar_color: '',
  sort_sequence: 0
})
const isCreating = ref(false)
const createErrorMessage = ref('')

// 删除功能相关状态
const deleteDialog = ref(false)
const subjectToDelete = ref(null)
const isDeleting = ref(false)

const headers = computed(() => [
  { title: t('subject.table.headers.subject_name'), value: 'subject_name', sortable: true, width: '20%' },
  {
    title: t('subject.table.headers.enabled_flag'),
    value: 'enabled_flag',
    sortable: true,
    width: '16%',
    sort: (a, b) => {
      // Y (启用) 排在前面，N (禁用) 排在后面
      if (a === 'Y' && b === 'N') return -1
      if (a === 'N' && b === 'Y') return 1
      return 0
    }
  },
  { title: t('subject.table.headers.primary_flag'), value: 'primary_flag', sortable: true, width: '16%' },
  { title: t('subject.table.headers.calendar_color'), value: 'calendar_color', sortable: false, width: '20%' },
  { title: t('subject.table.headers.sort_sequence'), value: 'sort_sequence', sortable: true, width: '16%' },
  { title: t('subject.table.headers.actions'), value: 'actions', sortable: false, align: 'end', width: '12%' },
])

// 日历颜色选项
const calendarColorOptions = computed(() =>
  COLOR_KEYS.map(colorKey => ({
    value: colorKey,
    title: t(`subject.calendarColors.${colorKey}`),
    color: COLOR_MAPPING[colorKey]
  }))
)

const fetchSubjects = async () => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const subjects_data = await getSubjects()
    console.log('Subjects data:', subjects_data)

    // 现在API返回的直接是数组（已经处理了所有分页）
    subjects.value = Array.isArray(subjects_data) ? subjects_data : []
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('subject.messages.loadError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  // 确保 axios 鉴权拦截器与头已设置
  if (authStore && authStore.initializeAuth) {
    authStore.initializeAuth()
  }
  fetchSubjects()
})

// 编辑功能方法
const openEditDialog = (subject) => {
  editingSubject.value = subject
  editForm.value = {
    subject_name: subject.subject_name || '',
    enabled_flag: subject.enabled_flag || 'Y',
    primary_flag: subject.primary_flag || 'N',
    calendar_color: subject.calendar_color || '',
    sort_sequence: subject.sort_sequence || 0
  }
  console.log('Editing subject data:', subject)
  console.log('Converted form data:', editForm.value)
  editDialog.value = true
}

const closeEditDialog = () => {
  editDialog.value = false
  editingSubject.value = null
  editForm.value = {
    subject_name: '',
    enabled_flag: 'Y',
    primary_flag: 'N',
    calendar_color: '',
    sort_sequence: 0
  }
}

// 新增功能方法
const openCreateDialog = () => {
  createForm.value = {
    subject_name: '',
    enabled_flag: 'Y',
    primary_flag: 'N',
    calendar_color: '',
    sort_sequence: 0
  }
  createErrorMessage.value = ''
  createDialog.value = true
}

const closeCreateDialog = () => {
  createDialog.value = false
  createForm.value = {
    subject_name: '',
    enabled_flag: 'Y',
    primary_flag: 'N',
    calendar_color: '',
    sort_sequence: 0
  }
  createErrorMessage.value = ''
}

const createNewSubject = async () => {
  isCreating.value = true
  createErrorMessage.value = ''
  successMessage.value = ''

  try {
    console.log('Form data before creation:', createForm.value)

    // 构建要发送的数据
    const createData = {
      subject_name: createForm.value.subject_name,
      enabled_flag: createForm.value.enabled_flag,
      primary_flag: createForm.value.primary_flag,
      calendar_color: createForm.value.calendar_color,
      sort_sequence: createForm.value.sort_sequence
    }

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

    // 1. 调用API创建学科
    const newSubject = await createSubject(createData)

    // 2. 创建成功后，将新学科添加到本地列表
    const subjectToAdd = {
      ...newSubject,
      ...createData
    }

    subjects.value.unshift(subjectToAdd) // 在列表顶部添加新学科

    // 3. 显示成功消息
    successMessage.value = t('subject.messages.createSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeCreateDialog()

  } catch (error) {
    console.error('Creation failed:', error)
    createErrorMessage.value = error.message || t('subject.messages.createError')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
  } finally {
    isCreating.value = false
  }
}

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

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

const confirmDeleteSubject = async () => {
  if (!subjectToDelete.value?.subject_id) {
    console.error('Unable to get subject ID')
    return
  }

  isDeleting.value = true

  try {
    console.log('Deleting subject:', subjectToDelete.value)

    // 1. 调用API删除学科
    await deleteSubject(subjectToDelete.value.subject_id)

    // 2. 从本地列表中移除学科
    const index = subjects.value.findIndex(s => s.subject_id === subjectToDelete.value.subject_id)
    if (index !== -1) {
      subjects.value.splice(index, 1)
    }

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

    closeDeleteDialog()
    closeEditDialog() // 自动关闭编辑对话框

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

const saveSubject = async () => {
  if (!editingSubject.value?.subject_id) {
    saveErrorMessage.value = t('common.messages.error.general')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
    return
  }

  isSaving.value = true
  saveErrorMessage.value = ''
  successMessage.value = ''

  try {
    console.log('Form data before saving:', editForm.value)

    // 构建要发送的数据
    const updateData = {
      subject_name: editForm.value.subject_name,
      enabled_flag: editForm.value.enabled_flag,
      primary_flag: editForm.value.primary_flag,
      calendar_color: editForm.value.calendar_color,
      sort_sequence: editForm.value.sort_sequence
    }

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

    // 1. 调用API保存到服务器
    await updateSubject(editingSubject.value.subject_id, updateData)

    // 2. API调用成功后，更新本地数据
    const index = subjects.value.findIndex(s => s.subject_id === editingSubject.value.subject_id)
    if (index !== -1) {
      const updatedSubject = {
        ...subjects.value[index],
        subject_name: editForm.value.subject_name,
        enabled_flag: editForm.value.enabled_flag,
        primary_flag: editForm.value.primary_flag,
        calendar_color: editForm.value.calendar_color,
        sort_sequence: editForm.value.sort_sequence
      }

      subjects.value[index] = updatedSubject
    }

    // 3. 显示成功消息
    successMessage.value = t('subject.messages.updateSuccess')
    // 3秒后自动隐藏成功消息
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeEditDialog()

  } catch (error) {
    // 4. API失败时不更新本地数据，显示错误消息
    console.error('Save failed:', error)
    saveErrorMessage.value = error.message || t('subject.messages.updateError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isSaving.value = false
  }
}

// 获取日历颜色的显示名称和颜色值
const getCalendarColorName = (colorCode) => {
  const colorOption = calendarColorOptions.value.find(option => option.value === colorCode)
  return colorOption ? colorOption.title : colorCode || '--'
}

// 获取日历颜色的CSS颜色值
const getCalendarColorValue = (colorCode) => {
  return COLOR_MAPPING[colorCode] || '#e0e0e0'
}
</script>

<template>
  <v-container fluid>
    <v-row class="mb-4" align="center" justify="space-between">
      <v-col cols="12" sm="6">
        <h2 class="text-h5">{{ $t('subject.title') }}</h2>
      </v-col>
      <v-col cols="12" sm="6" class="text-sm-right text-right">
        <v-btn
          color="success"
          prepend-icon="mdi-plus"
          class="mr-2"
          @click="openCreateDialog"
        >
          {{ $t('subject.buttons.addSubject') }}
        </v-btn>
        <v-btn color="primary" prepend-icon="mdi-refresh" :loading="isLoading" @click="fetchSubjects">
          {{ $t('common.buttons.refresh') }}
        </v-btn>
      </v-col>
    </v-row>

    <v-alert v-if="isError" type="error" class="mb-4" closable>
      {{ errorMessage }}
    </v-alert>

    <!-- 成功消息 -->
    <v-alert v-if="successMessage" type="success" class="mb-4" closable @click:close="successMessage = ''">
      {{ successMessage }}
    </v-alert>

    <v-progress-linear v-if="isLoading" indeterminate color="primary" class="mb-4"></v-progress-linear>

    <v-data-table
      :headers="headers"
      :items="subjects"
      item-key="subject_id"
      :items-per-page="10"
      class="elevation-1"
      :sort-by="[{ key: 'sort_sequence', order: 'asc' }]"
      multi-sort
      :items-per-page-text="$t('subject.table.pagination.itemsPerPage')"
      :no-data-text="$t('subject.table.pagination.noDataText')"
      :loading-text="$t('subject.table.pagination.loadingText')"
      :items-per-page-options="[
        { value: 5, title: '5' },
        { value: 10, title: '10' },
        { value: 25, title: '25' },
        { value: 50, title: '50' },
        { value: -1, title: $t('subject.table.pagination.itemsPerPageAll') }
      ]"
      :hide-default-footer="false"
      height="calc(100vh - 360px)"
      fixed-header
    >
        <template v-slot:[`item.enabled_flag`]="{ item }">
          <v-chip :color="item.enabled_flag === 'Y' ? 'success' : 'error'" text-color="white" size="small">
            {{ item.enabled_flag === 'Y' ? $t('subject.status.enabled') : $t('subject.status.disabled') }}
          </v-chip>
        </template>
        <template v-slot:[`item.primary_flag`]="{ item }">
          <v-chip :color="item.primary_flag === 'Y' ? 'primary' : 'default'" text-color="white" size="small">
            {{ item.primary_flag === 'Y' ? $t('subject.status.primary') : $t('subject.status.notPrimary') }}
          </v-chip>
        </template>
        <template v-slot:[`item.calendar_color`]="{ item }">
          <div class="d-flex align-center">
            <v-avatar size="16" :color="getCalendarColorValue(item.calendar_color)" class="mr-2"></v-avatar>
            <span class="text-caption text-truncate" style="max-width: 100px;">{{ getCalendarColorName(item.calendar_color) }}</span>
          </div>
        </template>
        <template v-slot:[`item.actions`]="{ item }">
          <v-btn
            icon="mdi-pencil"
            size="small"
            color="primary"
            variant="text"
            @click="openEditDialog(item)"
          >
          </v-btn>
        </template>
      </v-data-table>

    <!-- 编辑对话框 -->
    <v-dialog v-model="editDialog" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('subject.dialog.edit') }}
        </v-card-title>
        <v-card-text>
          <v-container>
            <!-- 保存错误消息 -->
            <v-alert v-if="saveErrorMessage" type="error" class="mb-4" closable @click:close="saveErrorMessage = ''">
              {{ saveErrorMessage }}
            </v-alert>

            <v-row>
              <!-- Form fields -->
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.subject_name"
                  :label="$t('subject.form.subject_name')"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="editForm.sort_sequence"
                  :label="$t('subject.form.sort_sequence')"
                  type="number"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-select
                  v-model="editForm.calendar_color"
                  :label="$t('subject.form.calendar_color')"
                  :items="calendarColorOptions"
                  variant="outlined"
                  clearable
                >
                  <template v-slot:item="{ props, item }">
                    <v-list-item v-bind="props" :title="item.title">
                      <template v-slot:prepend>
                        <div
                          class="color-dot"
                          :style="{ backgroundColor: item.raw?.color || item.color || '#e0e0e0' }"
                        ></div>
                      </template>
                    </v-list-item>
                  </template>
                  <template v-slot:selection="{ item }">
                    <div class="d-flex align-center">
                      <div
                        class="color-dot"
                        :style="{ backgroundColor: item.raw?.color || item.color || '#e0e0e0' }"
                      ></div>
                      <span>{{ item.raw?.title || item.title }}</span>
                    </div>
                  </template>
                </v-select>
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="editForm.enabled_flag"
                  :label="$t('subject.form.enabled_flag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="editForm.primary_flag"
                  :label="$t('subject.form.primary_flag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-btn
            color="error"
            variant="outlined"
            prepend-icon="mdi-delete"
            @click="openDeleteDialog(editingSubject)"
            :disabled="isSaving"
          >
            {{ $t('common.buttons.delete') }}
          </v-btn>
          <v-spacer />
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="closeEditDialog"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="primary"
            variant="text"
            :loading="isSaving"
            :disabled="isSaving"
            @click="saveSubject"
          >
            {{ $t('common.buttons.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Add Subject Dialog -->
    <v-dialog v-model="createDialog" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('subject.dialog.add') }}
        </v-card-title>
        <v-card-text>
          <v-container>
            <!-- Error messages -->
            <v-alert v-if="createErrorMessage" type="error" class="mb-4" closable @click:close="createErrorMessage = ''">
              {{ createErrorMessage }}
            </v-alert>

            <v-row>
              <!-- Form fields -->
              <v-col cols="12">
                <v-text-field
                  v-model="createForm.subject_name"
                  :label="$t('subject.form.subject_name') + ' *'"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="createForm.sort_sequence"
                  :label="$t('subject.form.sort_sequence')"
                  type="number"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-select
                  v-model="createForm.calendar_color"
                  :label="$t('subject.form.calendar_color')"
                  :items="calendarColorOptions"
                  variant="outlined"
                  clearable
                >
                  <template v-slot:item="{ props, item }">
                    <v-list-item v-bind="props" :title="item.title">
                      <template v-slot:prepend>
                        <div
                          class="color-dot"
                          :style="{ backgroundColor: item.raw?.color || item.color || '#e0e0e0' }"
                        ></div>
                      </template>
                    </v-list-item>
                  </template>
                  <template v-slot:selection="{ item }">
                    <div class="d-flex align-center">
                      <div
                        class="color-dot"
                        :style="{ backgroundColor: item.raw?.color || item.color || '#e0e0e0' }"
                      ></div>
                      <span>{{ item.raw?.title || item.title }}</span>
                    </div>
                  </template>
                </v-select>
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="createForm.enabled_flag"
                  :label="$t('subject.form.enabled_flag') + ' *'"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="createForm.primary_flag"
                  :label="$t('subject.form.primary_flag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="closeCreateDialog"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="success"
            variant="text"
            :loading="isCreating"
            :disabled="isCreating"
            @click="createNewSubject"
          >
            {{ $t('common.buttons.create') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Delete Confirmation 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('subject.dialog.delete') }}
        </v-card-title>
        <v-card-text>
          <div class="text-body-1 mb-4">
            {{ $t('subject.deleteConfirmation.message') }}
          </div>
          <div v-if="subjectToDelete" class="bg-grey-lighten-4 pa-3 rounded">
            <div class="font-weight-medium">{{ subjectToDelete.subject_name }}</div>
            <div class="text-caption text-medium-emphasis">
              {{ $t('subject.deleteConfirmation.subjectInfo', {
                name: subjectToDelete.subject_name,
                sort: subjectToDelete.sort_sequence
              }) }}
            </div>
          </div>
          <div class="text-body-2 text-error mt-4">
            <v-icon icon="mdi-alert-circle" size="small" class="mr-1" />
            {{ $t('subject.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="confirmDeleteSubject"
          >
            {{ $t('common.buttons.confirm') + ' ' + $t('common.buttons.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<style scoped>
.color-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 8px;
  border: 1px solid #ddd;
  display: inline-block;
  flex-shrink: 0;
}
</style>
