<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="state.queryForm" 
          ref="searchFormRef" 
          :inline="true" 
          @keyup.enter="getDataList"
          class="search-form">
          <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="buildNo">
            <el-select 
              v-model="state.queryForm.buildNo" 
              placeholder="请选择楼号" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in buildingList"
                :key="item.buildingNo"
                :label="item.buildingNo"
                :value="item.buildingNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间号" prop="roomNo">
            <el-input 
              v-model="state.queryForm.roomNo" 
              placeholder="请输入房间号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="学号" prop="stuNo">
            <el-input 
              v-model="state.queryForm.stuNo" 
              placeholder="请输入学号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="点名类型" prop="type">
            <el-select 
              v-model="state.queryForm.type" 
              placeholder="请选择点名类型" 
              clearable
              style="width: 200px">
              <el-option label="普通住宿点名" value="1" />
              <el-option label="留宿点名" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="考勤状态" prop="sign">
            <el-select 
              v-model="state.queryForm.sign" 
              placeholder="请选择考勤状态" 
              clearable
              style="width: 200px">
              <el-option label="未到" :value="0" />
              <el-option label="已到" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="考勤日期" prop="date">
            <el-date-picker
              v-model="state.queryForm.date"
              type="date"
              placeholder="请选择考勤日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain 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>
              <el-button 
                icon="RefreshLeft" 
                type="warning" 
                class="ml10" 
                @click="handleInit">
                初始化
              </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) - 1) * (state.pagination?.size || 10) }}
            </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 === 'type'" #default="scope">
                <el-tag size="small" :type="scope.row.type === '1' ? 'primary' : 'success'" effect="plain">
                  {{ scope.row.type === '1' ? '普通住宿点名' : '留宿点名' }}
                </el-tag>
              </template>
              <!-- 考勤状态列特殊模板 -->
              <template v-else-if="col.prop === 'sign'" #default="scope">
                <el-tag size="small" :type="scope.row.sign === '1' || scope.row.sign === 1 ? 'success' : 'danger'" effect="plain">
                  {{ scope.row.sign === '1' || scope.row.sign === 1 ? '已到' : '未到' }}
                </el-tag>
              </template>
              <!-- 是否扫过脸列特殊模板 -->
              <template v-else-if="col.prop === 'isFace'" #default="scope">
                <el-tag size="small" :type="scope.row.isFace === '1' || scope.row.isFace === 1 ? 'success' : 'info'" effect="plain">
                  {{ scope.row.isFace === '1' || scope.row.isFace === 1 ? '是' : '否' }}
                </el-tag>
              </template>
              <!-- 是否请假列特殊模板 -->
              <template v-else-if="col.prop === 'isApply'" #default="scope">
                <el-tag size="small" :type="scope.row.isApply === '1' || scope.row.isApply === 1 ? 'warning' : 'info'" effect="plain">
                  {{ scope.row.isApply === '1' || scope.row.isApply === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </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="DormSignRecord">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, initDormStuInfoForAttendance } from "/@/api/stuwork/dormsignrecord";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { getDeptList } from "/@/api/basic/basicclass";
import { getBuildingList } from "/@/api/stuwork/dormbuilding";
import FormDialog from './form.vue'
import { Search, Document, List, Menu, RefreshLeft, OfficeBuilding, Grid, User, CreditCard, House, Check, Calendar, UserFilled } from '@element-plus/icons-vue'
import RightToolbar from '/@/components/RightToolbar/index.vue'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'
import { useRoute } from 'vue-router'

const route = useRoute()
const formDialogRef = ref()
const showSearch = ref(true)
const searchFormRef = ref()
const columnControlRef = ref<any>()
const deptList = ref<any[]>([])
const buildingList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院', minWidth: 120, icon: OfficeBuilding },
  { prop: 'className', label: '班级', minWidth: 120, icon: Grid },
  { prop: 'stuName', label: '姓名', width: 100, icon: User },
  { prop: 'stuNo', label: '学号', width: 120, icon: CreditCard },
  { prop: 'roomNo', label: '房间号', width: 100, icon: House },
  { prop: 'buildId', label: '楼号', width: 80, icon: OfficeBuilding },
  { prop: 'type', label: '点名类型', width: 120, icon: Document },
  { prop: 'sign', label: '考勤状态', width: 100, icon: Check },
  { prop: 'date', label: '考勤日期', width: 120, icon: Calendar },
  { prop: 'isFace', label: '是否扫过脸', width: 100, icon: UserFilled },
  { prop: 'isApply', label: '是否请假', width: 100, icon: Document }
]

// 使用表格列控制
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange,
  loadSavedConfig
} = useTableColumnControl(tableColumns, { storageKey: route.path })

// 立即加载配置
loadSavedConfig()

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    deptCode: '',
    buildNo: '',
    roomNo: '',
    stuNo: '',
    type: '',
    sign: '',
    date: ''
  },
  pageList: async (params: any) => {
    const res = await fetchList(params)
    const data = res?.data
    return {
      data: {
        records: data?.records ?? [],
        total: data?.total ?? 0
      }
    }
  },
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true,
  isPage: true
})

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

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.deptCode = ''
  state.queryForm.buildNo = ''
  state.queryForm.roomNo = ''
  state.queryForm.stuNo = ''
  state.queryForm.type = ''
  state.queryForm.sign = ''
  state.queryForm.date = ''
  getDataList()
}

// 初始化
const handleInit = async () => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要初始化宿舍学生信息用于考勤吗？')
    await initDormStuInfoForAttendance()
    useMessage().success('初始化成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || '初始化失败')
      }
    }
  }
}

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

// 获取楼号列表
const getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    buildingList.value = res?.data && Array.isArray(res.data) ? res.data : []
  } catch (err) {
    buildingList.value = []
  }
}

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

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