<script setup>
import { onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDisplay } from 'vuetify'
import { useAuthStore } from '@/stores/auth'
import { getTerms, updateTerm, createTerm, deleteTerm } from '@/api/termService.js'
import { getStudents } from '@/api/studentService.js'

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

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

// 编辑功能相关状态
const editDialog = ref(false)
const editingTerm = ref(null)
const editForm = ref({
  student_id: '',
  term_name: '',
  term_start_date: '',
  term_end_date: '',
  tenant_id: 1
})
const isSaving = ref(false)
const successMessage = ref('')
const saveErrorMessage = ref('')

// 新增功能相关状态
const createDialog = ref(false)
const createForm = ref({
  student_id: '',
  term_name: '',
  term_start_date: '',
  term_end_date: '',
  tenant_id: 1
})
const isCreating = ref(false)
const createErrorMessage = ref('')

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

const headers = computed(() => [
  { title: t('term.table.headers.termName'), value: 'term_name', sortable: true },
  { title: t('term.table.headers.studentName'), value: 'student_name', sortable: true },
  { title: t('term.table.headers.startDate'), value: 'term_start_date', sortable: true },
  { title: t('term.table.headers.endDate'), value: 'term_end_date', sortable: true },
  { title: t('term.table.headers.actions'), value: 'actions', sortable: false, align: 'end' },
])

// 学生下拉选项（仅显示启用的学生）
const studentOptions = computed(() =>
  students.value
    .filter(student => student.enabled === 'Y' || student.enabled === true) // 过滤出启用的学生，兼容字符串和布尔值格式
    .map(student => ({
      title: student.student_name,
      value: student.student_id
    }))
)

const fetchTerms = async () => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const terms_data = await getTerms()
    console.log('Terms data:', terms_data)

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

    // 为每个term添加学生姓名（包括已禁用的学生）
    terms.value.forEach(term => {
      const student = students.value.find(s => s.student_id === term.student_id)
      term.student_name = student ? student.student_name : t('term.messages.unknownStudent')
    })
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('term.messages.loadError')
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

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 (e) {
    console.error('Failed to fetch students:', e)
  }
}

onMounted(async () => {
  if (authStore && authStore.initializeAuth) {
    authStore.initializeAuth()
  }
  await fetchStudents()
  await fetchTerms()
})

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 格式化日期为输入框格式
const formatDateForInput = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toISOString().split('T')[0]
}

// 编辑功能方法
const openEditDialog = (term) => {
  editingTerm.value = term
  editForm.value = {
    student_id: term.student_id || '',
    term_name: term.term_name || '',
    term_start_date: formatDateForInput(term.term_start_date),
    term_end_date: formatDateForInput(term.term_end_date),
    tenant_id: term.tenant_id || 1
  }
  console.log('Editing term data:', term)
  console.log('Converted form data:', editForm.value)
  editDialog.value = true
}

const closeEditDialog = () => {
  editDialog.value = false
  editingTerm.value = null
  editForm.value = {
    student_id: '',
    term_name: '',
    term_start_date: '',
    term_end_date: '',
    tenant_id: 1
  }
}

// 新增功能方法
const openCreateDialog = () => {
  createForm.value = {
    student_id: '',
    term_name: '',
    term_start_date: '',
    term_end_date: '',
    tenant_id: 1
  }
  createErrorMessage.value = ''
  createDialog.value = true
}

const closeCreateDialog = () => {
  createDialog.value = false
  createForm.value = {
    student_id: '',
    term_name: '',
    term_start_date: '',
    term_end_date: '',
    tenant_id: 1
  }
  createErrorMessage.value = ''
}

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

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

    const createData = {
      student_id: parseInt(createForm.value.student_id),
      term_name: createForm.value.term_name,
      term_start_date: new Date(createForm.value.term_start_date).toISOString(),
      term_end_date: new Date(createForm.value.term_end_date).toISOString(),
      tenant_id: createForm.value.tenant_id
    }

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

    const newTerm = await createTerm(createData)

    // 添加学生姓名到新创建的term
    const student = students.value.find(s => s.student_id === newTerm.student_id)
    newTerm.student_name = student ? student.student_name : t('term.messages.unknownStudent')

    terms.value.unshift(newTerm)

    successMessage.value = t('term.messages.createSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeCreateDialog()

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

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

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

const confirmDeleteTerm = async () => {
  if (!termToDelete.value?.term_id) {
    console.error('Unable to get term ID')
    return
  }

  isDeleting.value = true

  try {
    console.log('Deleting term:', termToDelete.value)

    await deleteTerm(termToDelete.value.term_id)

    const index = terms.value.findIndex(t => t.term_id === termToDelete.value.term_id)
    if (index !== -1) {
      terms.value.splice(index, 1)
    }

    successMessage.value = t('term.messages.deleteSuccess', { name: termToDelete.value.term_name })
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)

    closeDeleteDialog()
    closeEditDialog()

  } catch (error) {
    console.error('Deletion failed:', error)
    saveErrorMessage.value = error.message || t('term.messages.deleteError')
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isDeleting.value = false
  }
}

const saveTerm = async () => {
  if (!editingTerm.value?.term_id) {
    saveErrorMessage.value = t('common.messages.error.general')
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
    return
  }

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

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

    const updateData = {
      student_id: parseInt(editForm.value.student_id),
      term_name: editForm.value.term_name,
      term_start_date: new Date(editForm.value.term_start_date).toISOString(),
      term_end_date: new Date(editForm.value.term_end_date).toISOString(),
      tenant_id: editForm.value.tenant_id
    }

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

    await updateTerm(editingTerm.value.term_id, updateData)

    const index = terms.value.findIndex(t => t.term_id === editingTerm.value.term_id)
    if (index !== -1) {
      const updatedTerm = {
        ...terms.value[index],
        student_id: editForm.value.student_id,
        term_name: editForm.value.term_name,
        term_start_date: new Date(editForm.value.term_start_date).toISOString(),
        term_end_date: new Date(editForm.value.term_end_date).toISOString(),
        tenant_id: editForm.value.tenant_id
      }

      // 更新学生姓名
      const student = students.value.find(s => s.student_id === parseInt(editForm.value.student_id))
      updatedTerm.student_name = student ? student.student_name : t('term.messages.unknownStudent')

      terms.value[index] = updatedTerm
    }

    successMessage.value = t('term.messages.updateSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeEditDialog()

  } catch (error) {
    console.error('Save failed:', error)
    saveErrorMessage.value = error.message || t('term.messages.updateError')
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isSaving.value = false
  }
}
</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('term.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('term.buttons.addTerm') }}
        </v-btn>
        <v-btn color="primary" prepend-icon="mdi-refresh" :loading="isLoading" @click="fetchTerms">
          {{ $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="terms"
      item-key="term_id"
      :items-per-page="10"
      class="elevation-1 text-no-wrap"
      :sort-by="[{ key: 'term_start_date', order: 'desc' }]"
      multi-sort
      :items-per-page-text="$t('term.table.pagination.itemsPerPage')"
      :no-data-text="$t('term.table.pagination.noDataText')"
      :loading-text="$t('term.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('term.table.pagination.itemsPerPageAll') }
      ]"
      :hide-default-footer="false"
      :height="xs ? undefined : 'calc(100dvh - 360px)'"
      :fixed-header="!xs"
      :density="xs ? 'compact' : 'comfortable'"
    >
      <template v-slot:[`item.term_start_date`]="{ item }">
        {{ formatDate(item.term_start_date) }}
      </template>
      <template v-slot:[`item.term_end_date`]="{ item }">
        {{ formatDate(item.term_end_date) }}
      </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('term.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>
              <v-col cols="12">
                <v-select
                  v-model="editForm.student_id"
                  :items="studentOptions"
                  :label="$t('term.form.student')"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.term_name"
                  :label="$t('term.form.termName')"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="editForm.term_start_date"
                  :label="$t('term.form.startDate')"
                  type="date"
                  variant="outlined"
                  required
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="editForm.term_end_date"
                  :label="$t('term.form.endDate')"
                  type="date"
                  variant="outlined"
                  required
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-btn
            color="error"
            variant="outlined"
            prepend-icon="mdi-delete"
            @click="openDeleteDialog(editingTerm)"
            :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="saveTerm"
          >
            {{ $t('common.buttons.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 新增对话框 -->
    <v-dialog v-model="createDialog" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('term.dialog.add') }}
        </v-card-title>
        <v-card-text>
          <v-container>
            <v-alert v-if="createErrorMessage" type="error" class="mb-4" closable @click:close="createErrorMessage = ''">
              {{ createErrorMessage }}
            </v-alert>

            <v-row>
              <v-col cols="12">
                <v-select
                  v-model="createForm.student_id"
                  :items="studentOptions"
                  :label="$t('term.form.student') + ' *'"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="createForm.term_name"
                  :label="$t('term.form.termName') + ' *'"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="createForm.term_start_date"
                  :label="$t('term.form.startDate') + ' *'"
                  type="date"
                  variant="outlined"
                  required
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="createForm.term_end_date"
                  :label="$t('term.form.endDate') + ' *'"
                  type="date"
                  variant="outlined"
                  required
                />
              </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="createNewTerm"
          >
            {{ $t('common.buttons.create') }}
          </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('term.dialog.delete') }}
        </v-card-title>
        <v-card-text>
          <div class="text-body-1 mb-4">
            {{ $t('term.deleteConfirmation.message') }}
          </div>
          <div v-if="termToDelete" class="bg-grey-lighten-4 pa-3 rounded">
            <div class="font-weight-medium">{{ termToDelete.term_name }}</div>
            <div class="text-caption text-medium-emphasis">
              {{ termToDelete.student_name }} | {{ formatDate(termToDelete.term_start_date) }} - {{ formatDate(termToDelete.term_end_date) }}
            </div>
          </div>
          <div class="text-body-2 text-error mt-4">
            <v-icon icon="mdi-alert-circle" size="small" class="mr-1" />
            {{ $t('term.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="confirmDeleteTerm"
          >
            {{ $t('common.buttons.confirm') + ' ' + $t('common.buttons.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<style scoped>
</style>
