<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="deptCode">
            <el-select 
              v-model="searchForm.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="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="startDate">
            <el-date-picker
              v-model="searchForm.startDate"
              type="date"
              placeholder="选择开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="searchForm.endDate"
              type="date"
              placeholder="选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 200px" />
          </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">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                新增
              </el-button>
              <right-toolbar  
                v-model:showSearch="showSearch" 
                :export="'stuwork_classRoomHygieneDaily_export'"
                @exportExcel="exportExcel" 
                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"
          @sort-change="sortChangeHandle">
          <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 === 'score'" #default="scope">
                <el-tag v-if="scope.row.score !== undefined && scope.row.score !== null" size="small" type="danger" effect="plain" round>
                  {{ scope.row.score }}
                </el-tag>
                <span v-else>-</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="formDialogRef.openDialog(scope.row.id)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link
                type="danger" 
                @click="handleDelete([scope.row.id])">
                删除
              </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>

    <!-- 编辑、新增  -->
    <FormDialog ref="formDialogRef" @refresh="getDataList(false)" />
  </div>
</template>

<script setup lang="ts" name="ClassRoomHygieneDaily">
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/stuwork/classroomhygienedaily";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { getDeptList } from '/@/api/basic/basicclass'
import { getClassListByRole } from '/@/api/basic/basicclass'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, OfficeBuilding, Grid, Calendar, Minus, Document, Setting, Menu, Search, EditPen } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

// 定义变量内容
const formDialogRef = ref()
const searchFormRef = ref()
const columnControlRef = ref()
// 搜索变量
const showSearch = ref(true)
const deptList = ref<any[]>([])
const classList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院', icon: OfficeBuilding },
  { prop: 'classNo', label: '班号', icon: Grid },
  { prop: 'recordDate', label: '时间', icon: Calendar, width: 120 },
  { prop: 'score', label: '扣分', icon: Minus, width: 80 },
  { prop: 'note', label: '检查记录', icon: Document }
]

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

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

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

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

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

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

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

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

// 导出excel
const exportExcel = () => {
  downBlobFile(
    '/stuwork/classRoomHygieneDaily/export', 
    searchForm, 
    '教室卫生.xlsx'
  )
}

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }

  try {
    await delObjs(ids)
    getDataList()
    useMessage().success('删除成功')
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败')
  }
}

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

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