<template>
  <div class="classplan-container">
    <div class="page-wrapper">
      <!-- 搜索表单卡片 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              筛选条件
            </span>
          </div>
        </template>
        <el-form 
          :model="state.queryForm" 
          ref="searchFormRef" 
          :inline="true" 
          @keyup.enter="getDataList"
          class="search-form">
          <el-form-item label="学年" prop="schoolYear">
            <el-select 
              v-model="state.queryForm.schoolYear" 
              placeholder="请选择学年" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学期" prop="schoolTerm">
            <el-select 
              v-model="state.queryForm.schoolTerm" 
              placeholder="请选择学期" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="state.queryForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班号" prop="classNo">
            <el-select 
              v-model="state.queryForm.classNo" 
              placeholder="请选择班号" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select 
              v-model="state.queryForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              班级计划列表
            </span>
            <div class="header-actions">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                新增
              </el-button>
              <right-toolbar  
                v-model:showSearch="showSearch" 
                class="ml10"
                @queryTable="getDataList">
                <TableColumnControl
                  ref="columnControlRef"
                  :columns="tableColumns"
                  v-model="visibleColumns"
                  trigger-type="default"
                  trigger-circle
                  @change="handleColumnChange"
                  @order-change="handleColumnOrderChange"
                >
                  <template #trigger>
                    <el-tooltip class="item" effect="dark" content="列设置" placement="top">
                      <el-button circle style="margin-left: 0;">
                        <el-icon><Menu /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </template>
                </TableColumnControl>
              </right-toolbar>
            </div>
          </div>
        </template>

        <!-- 表格 -->
        <el-table 
          :data="state.dataList" 
          v-loading="state.loading"
          stripe
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index }">
              {{ $index + 1 + (state.pagination.current - 1) * state.pagination.size }}
            </template>
          </el-table-column>
          <template v-for="col in visibleColumnsSorted" :key="col.prop || col.label">
            <el-table-column 
              v-if="checkColumnVisible(col.prop || '') && col.prop !== '操作'"
              :prop="col.prop" 
              :label="col.label" 
              show-overflow-tooltip
              align="center"
              :min-width="col.minWidth"
              :width="col.width">
              <template #header>
                <el-icon><component :is="columnConfigMap[col.prop]?.icon || Calendar" /></el-icon>
                <span style="margin-left: 4px">{{ col.label }}</span>
              </template>
              <!-- 状态列特殊模板 -->
              <template v-if="col.prop === 'status'" #default="scope">
                <el-tag size="small" :type="getStatusTagType(scope.row.status)" effect="plain" round>
                  {{ formatStatus(scope.row.status) }}
                </el-tag>
              </template>
              <!-- 学期列特殊模板 -->
              <template v-else-if="col.prop === 'schoolTerm'" #default="scope">
                <el-tag size="small" type="primary" effect="plain" round>
                  {{ formatSchoolTerm(scope.row.schoolTerm) }}
                </el-tag>
              </template>
              <!-- 更新时间列特殊模板 -->
              <template v-else-if="col.prop === 'updateTime'" #default="scope">
                <span class="time-text">{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="EditPen" 
                link
                type="primary" 
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link
                type="danger" 
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" :image-size="120">
              <el-button type="primary" icon="FolderAdd" @click="formDialogRef.openDialog()">新增计划</el-button>
            </el-empty>
          </template>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <pagination 
            @size-change="sizeChangeHandle" 
            @current-change="currentChangeHandle" 
            v-bind="state.pagination" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑表单弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="ClassPlan">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/classplan";
import { getDeptList } from "/@/api/basic/basicclass";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getClassListByRole } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { parseTime } from "/@/utils/formatTime";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue'
import { List, OfficeBuilding, Calendar, CircleCheck, Clock, Grid, Document, User, Setting, Menu, Search, EditPen } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const route = useRoute()
const formDialogRef = ref()
const columnControlRef = ref<any>()
const searchFormRef = ref()
const showSearch = ref(true)
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const statusList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院' },
  { prop: 'schoolYear', label: '学年' },
  { prop: 'status', label: '状态' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'classNo', label: '班号' },
  { prop: 'title', label: '标题', minWidth: 200 },
  { prop: 'updateTime', label: '更新时间', width: 180 },
  { prop: 'createBy', label: '填报人' }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  deptName: { icon: OfficeBuilding },
  schoolYear: { icon: Calendar },
  status: { icon: CircleCheck },
  schoolTerm: { icon: Clock },
  classNo: { icon: Grid },
  title: { icon: Document },
  updateTime: { icon: Clock },
  createBy: { icon: User }
}

// 使用表格列控制hook
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns)

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    schoolYear: '',
    schoolTerm: '',
    deptCode: '',
    classNo: '',
    status: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle
} = useTable(state)

// 格式化学期
const formatSchoolTerm = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = schoolTermList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化状态
const formatStatus = (value: string) => {
  if (!value) return '-'
  const item = statusList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

// 获取状态标签类型
const getStatusTagType = (value: string) => {
  if (!value) return 'info'
  const item = statusList.value.find((item: any) => item.value === value)
  if (!item) return 'info'
  
  const label = item.label || item.dictLabel || item.name || ''
  // 已提交用蓝色
  if (label.includes('已提交') || label.includes('提交')) {
    return 'primary'
  }
  // 审核通过用绿色
  if (label.includes('审核通过') || label.includes('通过')) {
    return 'success'
  }
  // 其他状态默认用灰色
  return 'info'
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.schoolYear = ''
  state.queryForm.schoolTerm = ''
  state.queryForm.deptCode = ''
  state.queryForm.classNo = ''
  state.queryForm.status = ''
  getDataList()
}

// 编辑
const handleEdit = (row: any) => {
  formDialogRef.value?.openDialog('edit', row)
}

// 删除
const handleDelete = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要删除该班级计划吗？')
    await delObj([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    } else {
      schoolYearList.value = []
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期字典
const getSchoolTermDict = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      schoolTermList.value = []
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data && Array.isArray(res.data)) {
      deptList.value = res.data
    } else {
      deptList.value = []
    }
  } catch (err) {
    deptList.value = []
  }
}

// 获取班号列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data
    } else {
      classList.value = []
    }
  } catch (err) {
    classList.value = []
  }
}

// 获取状态字典
const getStatusDict = async () => {
  try {
    const res = await getDicts('status_type')
    if (res.data && Array.isArray(res.data)) {
      statusList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      statusList.value = []
    }
  } catch (err) {
    statusList.value = []
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getDeptListData()
  getClassListData()
  getStatusDict()
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
    }
  })
})
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';

.classplan-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

// 搜索卡片
.search-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  }

  :deep(.el-card__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f2f5;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

// 内容卡片
.content-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  }

  :deep(.el-card__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f2f5;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

// 卡片头部
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  
  .title-icon {
    margin-right: 8px;
    color: var(--el-color-primary);
    font-size: 18px;
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

// 搜索表单 - 保持原有宽度
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;
    margin-right: 20px;
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }

  // 确保表单项宽度保持200px
  :deep(.el-select) {
    width: 200px !important;
  }
}

// 现代化表格
.modern-table {
  border-radius: 8px;
  overflow: hidden;

  :deep(.el-table__header) {
    th {
      background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
      color: #606266;
      font-weight: 600;
      border-bottom: 2px solid #e4e7ed;
      padding: 14px 0;
    }
  }

  :deep(.el-table__body) {
    tr {
      transition: all 0.2s ease;

      &:hover {
        background-color: #f5f7ff;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      }
    }

    td {
      border-bottom: 1px solid #f0f2f5;
      padding: 16px 0;
    }
  }

  :deep(.el-table__row) {
    &:nth-child(even) {
      background-color: #fafbfc;
    }
  }
}

// 时间文本样式
.time-text {
  color: #909399;
  font-size: 13px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

// 分页包装器
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
}

// 响应式设计
@media (max-width: 768px) {
  .classplan-container {
    padding: 12px;
  }

  .page-wrapper {
    gap: 12px;
  }

  .search-card,
  .content-card {
    :deep(.el-card__header) {
      padding: 12px 16px;
    }

    :deep(.el-card__body) {
      padding: 16px;
    }
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: space-between;
  }

  // 移动端保持表单宽度
  .search-form {
    :deep(.el-form-item) {
      margin-right: 0;
      width: 100%;
    }

    :deep(.el-select) {
      width: 100% !important;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.search-card,
.content-card {
  animation: fadeIn 0.3s ease-out;
}

// 按钮样式优化
:deep(.el-button) {
  border-radius: 6px;
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateY(0);
  }
}

// 表格空状态优化
:deep(.el-empty) {
  padding: 40px 0;
}
</style>
