<template>
  <div class="modern-page-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="searchForm"
          ref="searchFormRef"
          :inline="true"
          @keyup.enter="handleSearch"
          class="search-form">
          <el-form-item label="学生姓名" prop="stuName">
            <el-input
              v-model="searchForm.stuName"
              placeholder="请输入学生姓名"
              clearable
              style="width: 180px" />
          </el-form-item>
          <el-form-item label="学号" prop="stuNo">
            <el-input
              v-model="searchForm.stuNo"
              placeholder="请输入学号"
              clearable
              style="width: 180px" />
          </el-form-item>
          <el-form-item label="班号" prop="classNo">
            <el-input
              v-model="searchForm.classNo"
              placeholder="请输入班号"
              clearable
              style="width: 180px" />
          </el-form-item>
          <el-form-item label="处理状态" prop="dealStatus">
            <el-select
              v-model="searchForm.dealStatus"
              placeholder="请选择处理状态"
              clearable
              style="width: 150px">
              <el-option label="待处理" value="0" />
              <el-option label="已处理" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="考勤类型" prop="attendanceType">
            <el-select
              v-model="searchForm.attendanceType"
              placeholder="请选择考勤类型"
              clearable
              style="width: 150px">
              <el-option label="旷课" value="5" />
              <el-option label="失联" value="6" />
            </el-select>
          </el-form-item>
          <el-form-item label="点名类型" prop="orderType">
            <el-select
              v-model="searchForm.orderType"
              placeholder="请选择点名类型"
              clearable
              style="width: 150px">
              <el-option label="早自习" value="1" />
              <el-option label="晚自习" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">查询</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">
              <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="dataList"
          v-loading="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 }">
              {{ (page.currentPage - 1) * page.pageSize + $index + 1 }}
            </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"
              :width="col.width"
              :min-width="col.minWidth"
              :show-overflow-tooltip="col.showOverflowTooltip !== false"
              :align="col.align || 'center'">
              <template #header>
                <el-icon v-if="col.icon"><component :is="col.icon" /></el-icon>
                <span :style="{ marginLeft: col.icon ? '4px' : '0' }">{{ col.label }}</span>
              </template>
              <!-- 处理状态列特殊模板 -->
              <template v-if="col.prop === 'dealStatus'" #default="scope">
                <el-tag
                  :type="scope.row.dealStatus === '1' ? 'success' : 'warning'"
                  size="small"
                  round>
                  {{ scope.row.dealStatusName || (scope.row.dealStatus === '1' ? '已处理' : '待处理') }}
                </el-tag>
              </template>
              <!-- 考勤类型列特殊模板 -->
              <template v-else-if="col.prop === 'attendanceType'" #default="scope">
                <el-tag
                  :type="scope.row.attendanceType === '6' ? 'danger' : 'warning'"
                  size="small"
                  round>
                  {{ scope.row.attendanceTypeName || (scope.row.attendanceType === '6' ? '失联' : '旷课') }}
                </el-tag>
              </template>
              <!-- 点名类型列特殊模板 -->
              <template v-else-if="col.prop === 'orderType'" #default="scope">
                <el-tag type="info" size="small" round>
                  {{ scope.row.orderTypeName || (scope.row.orderType === '1' ? '早自习' : '晚自习') }}
                </el-tag>
              </template>
              <!-- 最晚处理时间列特殊模板 -->
              <template v-else-if="col.prop === 'dealDeadline'" #default="scope">
                <span :class="{ 'text-danger': isOverdue(scope.row.dealDeadline) && scope.row.dealStatus === '0' }">
                  {{ formatDateTime(scope.row.dealDeadline) }}
                </span>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button
                v-if="scope.row.dealStatus === '0'"
                icon="Check"
                link
                type="primary"
                @click="handleDeal(scope.row)">
                处理
              </el-button>
              <el-button
                icon="View"
                link
                type="primary"
                @click="handleView(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" :image-size="120" />
          </template>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="page.currentPage"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-card>
    </div>

    <!-- 处理弹窗 -->
    <el-dialog
      v-model="dealDialogVisible"
      title="处理跟踪情况"
      width="500px"
      :close-on-click-modal="false">
      <el-form :model="dealForm" ref="dealFormRef" label-width="100px">
        <el-form-item label="学生姓名">
          <span>{{ currentRow.stuName }}</span>
        </el-form-item>
        <el-form-item label="学号">
          <span>{{ currentRow.stuNo }}</span>
        </el-form-item>
        <el-form-item label="考勤类型">
          <el-tag :type="currentRow.attendanceType === '6' ? 'danger' : 'warning'" size="small">
            {{ currentRow.attendanceTypeName || (currentRow.attendanceType === '6' ? '失联' : '旷课') }}
          </el-tag>
        </el-form-item>
        <el-form-item label="考勤日期">
          <span>{{ currentRow.attendanceDay }}</span>
        </el-form-item>
        <el-form-item label="处理说明" prop="dealContent" :rules="[{ required: true, message: '请输入处理说明', trigger: 'blur' }]">
          <el-input
            v-model="dealForm.dealContent"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dealDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDeal" :loading="dealLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="跟踪情况详情"
      width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学生姓名">{{ currentRow.stuName }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ currentRow.stuNo }}</el-descriptions-item>
        <el-descriptions-item label="班主任姓名">{{ currentRow.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="班主任工号">{{ currentRow.teacherNo }}</el-descriptions-item>
        <el-descriptions-item label="学院">{{ currentRow.deptName }}</el-descriptions-item>
        <el-descriptions-item label="班号">{{ currentRow.classNo }}</el-descriptions-item>
        <el-descriptions-item label="考勤类型">
          <el-tag :type="currentRow.attendanceType === '6' ? 'danger' : 'warning'" size="small">
            {{ currentRow.attendanceTypeName || (currentRow.attendanceType === '6' ? '失联' : '旷课') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="点名类型">
          <el-tag type="info" size="small">
            {{ currentRow.orderTypeName || (currentRow.orderType === '1' ? '早自习' : '晚自习') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="考勤日期">{{ currentRow.attendanceDay }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="currentRow.dealStatus === '1' ? 'success' : 'warning'" size="small">
            {{ currentRow.dealStatusName || (currentRow.dealStatus === '1' ? '已处理' : '待处理') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最晚处理时间">{{ formatDateTime(currentRow.dealDeadline) }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ formatDateTime(currentRow.dealTime) }}</el-descriptions-item>
        <el-descriptions-item label="处理说明" :span="2">{{ currentRow.dealContent || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDateTime(currentRow.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ClassMasterTracking">
import { reactive, ref, onMounted } from 'vue'
import { fetchList, dealTracking } from '/@/api/stuwork/classmastertracking'
import { useMessage } from '/@/hooks/message'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, CreditCard, Avatar, User, Timer, Calendar, Clock, Document, Setting, Menu, Search, Check, View } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const searchFormRef = ref()
const dealFormRef = ref()
const columnControlRef = ref()
const showSearch = ref(true)
const loading = ref(false)
const dealLoading = ref(false)
const dataList = ref<any[]>([])
const dealDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentRow = ref<any>({})
const dealForm = reactive({
  id: '',
  dealContent: ''
})

// 分页
const page = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格列配置
const tableColumns = [
  { prop: 'stuNo', label: '学号', icon: CreditCard, minWidth: 120 },
  { prop: 'stuName', label: '学生姓名', icon: Avatar, minWidth: 100 },
  { prop: 'classNo', label: '班号', icon: Document, minWidth: 120 },
  { prop: 'teacherName', label: '班主任', icon: User, minWidth: 100 },
  { prop: 'deptName', label: '学院', icon: Document, minWidth: 150 },
  { prop: 'attendanceType', label: '考勤类型', icon: Document, minWidth: 100 },
  { prop: 'orderType', label: '点名类型', icon: Clock, minWidth: 100 },
  { prop: 'attendanceDay', label: '考勤日期', icon: Calendar, minWidth: 120 },
  { prop: 'dealStatus', label: '处理状态', icon: Check, minWidth: 100 },
  { prop: 'dealDeadline', label: '最晚处理时间', icon: Timer, minWidth: 160 },
  { prop: 'dealTime', label: '处理时间', icon: Timer, minWidth: 160 },
  { prop: 'dealContent', label: '处理说明', icon: Document, minWidth: 200 }
]

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

// 搜索表单
const searchForm = reactive({
  stuNo: '',
  stuName: '',
  classNo: '',
  dealStatus: '',
  attendanceType: '',
  orderType: ''
})

// 表格样式
const tableStyle = {
  cellStyle: { textAlign: 'center' },
  headerCellStyle: {
    textAlign: 'center',
    background: 'var(--el-table-row-hover-bg-color)',
    color: 'var(--el-text-color-primary)'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dateTime.replace('T', ' ').substring(0, 19)
}

// 判断是否超期
const isOverdue = (deadline: string) => {
  if (!deadline) return false
  return new Date(deadline) < new Date()
}

// 查询
const handleSearch = () => {
  page.currentPage = 1
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  Object.assign(searchForm, {
    stuNo: '',
    stuName: '',
    classNo: '',
    dealStatus: '',
    attendanceType: '',
    orderType: ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.pageSize = val
  getDataList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  page.currentPage = val
  getDataList()
}

// 获取数据列表
const getDataList = async () => {
  loading.value = true
  try {
    const params: any = {
      current: page.currentPage,
      size: page.pageSize,
      ...searchForm
    }

    const res = await fetchList(params)
    if (res.data && res.data.records) {
      dataList.value = res.data.records
      page.total = res.data.total
    } else {
      dataList.value = []
      page.total = 0
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取数据列表失败')
    dataList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

// 处理
const handleDeal = (row: any) => {
  currentRow.value = row
  dealForm.id = row.id
  dealForm.dealContent = ''
  dealDialogVisible.value = true
}

// 提交处理
const submitDeal = async () => {
  if (!dealForm.dealContent) {
    useMessage().warning('请输入处理说明')
    return
  }
  dealLoading.value = true
  try {
    await dealTracking(dealForm)
    useMessage().success('处理成功')
    dealDialogVisible.value = false
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '处理失败')
  } finally {
    dealLoading.value = false
  }
}

// 查看详情
const handleView = (row: any) => {
  currentRow.value = row
  detailDialogVisible.value = true
}

// 初始化
onMounted(() => {
  getDataList()
})
</script>

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

.text-danger {
  color: var(--el-color-danger);
  font-weight: bold;
}
</style>