<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="classCode">
            <el-select 
              v-model="searchForm.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="点名类型" prop="orderType">
            <el-select 
              v-model="searchForm.orderType" 
              placeholder="请选择点名类型" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in orderTypeList"
                :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="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 }">
              {{ $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 === 'stuStatus'" #default="scope">
                <el-tag size="small" type="info" effect="plain" round>
                  {{ formatStudentStatus(scope.row.stuStatus) }}
                </el-tag>
              </template>
              <!-- 考勤类型列特殊模板 -->
              <template v-else-if="col.prop === 'attendanceType'" #default="scope">
                <el-tag size="small" type="warning" effect="plain" round>
                  {{ formatAttendanceType(scope.row.attendanceType) }}
                </el-tag>
              </template>
              <!-- 是否住宿列特殊模板 -->
              <template v-else-if="col.prop === 'isRoom'" #default="scope">
                <StatusTag 
                  :value="scope.row.isRoom"
                  :options="[{ label: '是', value: '1' }, { label: '否', value: '0' }]"
                  :type-map="{ '1': { type: 'success', effect: 'light' }, '0': { type: 'info', effect: 'light' } }"
                />
              </template>
              <!-- 是否扫脸列特殊模板 -->
              <template v-else-if="col.prop === 'isDeviceIn'" #default="scope">
                <el-tag :type="scope.row.isDeviceIn === '1' ? 'success' : 'danger'" size="small" round>
                  {{ scope.row.isDeviceIn === '1' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="100" 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>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" :image-size="120">
            </el-empty>
          </template>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts" name="ClassAttendance">
import { reactive, ref, onMounted } from 'vue'
import { fetchList, queryMyClassList } from '/@/api/stuwork/classattendance'
import { getDicts } from '/@/api/admin/dict'
import { useMessage } from '/@/hooks/message'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, CreditCard, Avatar, Phone, CircleCheck, Collection, House, Camera, Setting, Menu, Search, Document, EditPen } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'
import { defineAsyncComponent } from 'vue'
const StatusTag = defineAsyncComponent(() => import('/@/components/StatusTag/index.vue'))

// 定义变量内容
const searchFormRef = ref()
const columnControlRef = ref()
const showSearch = ref(true)
const loading = ref(false)
const dataList = ref<any[]>([])
const classList = ref<any[]>([])
const orderTypeList = ref<any[]>([])
const studentStatusList = ref<any[]>([])
const attendanceTypeList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'stuNo', label: '学号', icon: CreditCard },
  { prop: 'realName', label: '姓名', icon: Avatar },
  { prop: 'phone', label: '联系电话', icon: Phone },
  { prop: 'parentPhoneA', label: '家长联系电话1', icon: Phone },
  { prop: 'parentPhoneB', label: '家长联系电话2', icon: Phone },
  { prop: 'stuStatus', label: '学生状态', icon: CircleCheck },
  { prop: 'attendanceType', label: '考勤类型', icon: Collection },
  { prop: 'isRoom', label: '是否住宿', icon: House },
  { prop: 'roomNo', label: '宿舍号', icon: House },
  { prop: 'isDeviceIn', label: '是否扫脸', icon: Camera }
]

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

// 搜索表单
const searchForm = reactive({
  classCode: '',
  orderType: ''
})

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

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

// 格式化考勤类型
const formatAttendanceType = (value: string) => {
  if (!value) return '-'
  const item = attendanceTypeList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

// 查询
const handleSearch = () => {
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.classCode = ''
  searchForm.orderType = ''
  getDataList()
}

// 编辑
const handleEdit = (row: any) => {
  useMessage().info('编辑功能待实现')
}

// 获取数据列表
const getDataList = async () => {
  loading.value = true
  try {
    const params: any = {
      classCode: searchForm.classCode || undefined,
      orderType: searchForm.orderType || undefined
    }
    
    const res = await fetchList(params)
    if (res.data && Array.isArray(res.data)) {
      dataList.value = res.data
    } else {
      dataList.value = []
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取数据列表失败')
    dataList.value = []
  } finally {
    loading.value = false
  }
}

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

// 获取点名类型字典
const getOrderTypeDict = async () => {
  try {
    orderTypeList.value = [
      { label: '早读', value: '1' },
      { label: '上午', value: '2' },
      { label: '下午', value: '3' },
      { label: '晚自习', value: '4' }
    ]
  } catch (err) {
    orderTypeList.value = []
  }
}

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

// 获取考勤类型字典
const getAttendanceTypeDict = async () => {
  try {
    const res = await getDicts('attend_type')
    if (res.data && Array.isArray(res.data)) {
      attendanceTypeList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      attendanceTypeList.value = []
    }
  } catch (err) {
    attendanceTypeList.value = []
  }
}

// 初始化
onMounted(() => {
  getClassListData()
  getOrderTypeDict()
  getStudentStatusDict()
  getAttendanceTypeDict()
})
</script>

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