<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList">
          <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="classCode">
            <el-select 
              v-model="state.queryForm.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="recordDate">
            <el-date-picker
              v-model="state.queryForm.recordDate"
              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" plain icon="Search" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="Plus" 
            type="primary" 
            class="ml10" 
            @click="formDialogRef.openDialog()">
            新增
          </el-button>
          <el-button 
            icon="Download" 
            type="primary" 
            class="ml10" 
            @click="handleExport">
            导出
          </el-button>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            class="ml10 mr20"
            style="float: right;"
            @queryTable="getDataList">
          </right-toolbar>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-table 
        :data="state.dataList" 
        v-loading="state.loading"
        border 
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="schoolYear" label="学年" show-overflow-tooltip align="center" />
        <el-table-column prop="schoolTerm" label="学期" show-overflow-tooltip align="center">
          <template #default="scope">
            <span>{{ formatSchoolTerm(scope.row.schoolTerm) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="classNo" label="班号" show-overflow-tooltip align="center" />
        <el-table-column prop="themeName" label="活动主题" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="author" label="主持人" show-overflow-tooltip align="center" />
        <el-table-column prop="address" label="活动地点" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="recordDate" label="活动时间" show-overflow-tooltip align="center" width="120" />
        <el-table-column prop="attendNum" label="参加人数" show-overflow-tooltip align="center" />
        <el-table-column prop="attachment" label="活动照片" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.attachment"
              icon="Picture"
              text
              type="primary"
              size="small"
              @click="handleViewImage(scope.row.attachment)">
              查看
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="attachment2" label="活动照片2" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.attachment2"
              icon="Picture"
              text
              type="primary"
              size="small"
              @click="handleViewImage(scope.row.attachment2)">
              查看
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleView(scope.row)">
              查看详情
            </el-button>
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button 
              icon="Delete" 
              text 
              type="danger" 
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

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

<script setup lang="ts" name="ClassSafeEdu">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, exportExcel } from "/@/api/stuwork/classsafeedu";
import { getClassListByRole } from "/@/api/basic/basicclass";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import FormDialog from './form.vue'
import DetailDialog from './detail.vue'

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

// 表格样式
const tableStyle = {
  cellStyle: { padding: '8px 0' },
  headerCellStyle: { background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }
}

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    schoolYear: '',
    schoolTerm: '',
    classCode: '',
    recordDate: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true // 页面加载时自动获取数据
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle: _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 handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.schoolYear = ''
  state.queryForm.schoolTerm = ''
  state.queryForm.classCode = ''
  state.queryForm.recordDate = ''
  getDataList()
}

// 查看图片
const handleViewImage = (url: string) => {
  if (url) {
    const urls = typeof url === 'string' ? url.split(',') : [url]
    urls.forEach((imgUrl: string) => {
      if (imgUrl.trim()) {
        window.open(imgUrl.trim(), '_blank')
      }
    })
  }
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportExcel(state.queryForm)
    
    // 创建blob对象
    const blob = new Blob([res], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 设置文件名
    const fileName = `安全教育_${new Date().getTime()}.xlsx`
    link.setAttribute('download', fileName)
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    useMessage().success('导出成功')
  } catch (err: any) {
    console.error('导出失败', err)
    useMessage().error(err.msg || '导出失败')
  }
}

// 查看详情
const handleView = (row: any) => {
  detailDialogRef.value?.openDialog(row)
}

// 编辑
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) {
    console.error('获取学年列表失败', 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) {
    console.error('获取学期字典失败', err)
    schoolTermList.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) {
    console.error('获取班级列表失败', err)
    classList.value = []
  }
}

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

<style scoped lang="scss">
</style>

