<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <search-form 
        v-show="showSearch" 
        :model="search" 
        ref="searchFormRef"
        @keyup-enter="handleFilter"
      >
        <template #default="{ visible }">
          <template v-if="visible">
            <el-form-item label="审核状态" prop="state">
              <el-select
                v-model="search.state"
                clearable
                style="width: 200px"
                placeholder="请选择审核状态"
              >
                <el-option
                  v-for="item in professionalState"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="工号" prop="teacherNo">
              <el-input
                v-model="search.teacherNo"
                clearable
                style="width: 200px"
                placeholder="请输入工号"
              />
            </el-form-item>

            <el-form-item label="姓名" prop="teacherName">
              <el-input
                v-model="search.teacherName"
                clearable
                style="width: 200px"
                placeholder="请输入姓名"
              />
            </el-form-item>
          </template>
        </template>

        <!-- 操作按钮 -->
        <template #actions>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" icon="Search">查询</el-button>
            <el-button @click="resetQuery" icon="Refresh">重置</el-button>
          </el-form-item>
        </template>
      </search-form>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb15" style="width: 100%;">
          <el-button 
            type="primary"
            icon="FolderAdd"
            @click="handleAdd"
            v-if="permissions.professional_professionalteacherhonor_add">新 增
          </el-button>
          <el-button 
            type="success"
            icon="Download"
            @click="handleDownLoadWord"
            :loading="exportLoading">导出
          </el-button>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :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="state" label="审核状态" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.state === '1'" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.state === '-2'" type="danger">驳回</el-tag>
            <el-tag v-else-if="scope.row.state === '0'" type="warning">待审核</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="backReason" label="驳回理由" min-width="150" align="center" show-overflow-tooltip />
        
        <el-table-column prop="teacherNo" label="工号" min-width="120" align="center" show-overflow-tooltip />
        
        <el-table-column prop="teacherName" label="姓名" min-width="120" align="center" show-overflow-tooltip />
        
        <el-table-column prop="honor" label="荣誉" min-width="150" align="center" show-overflow-tooltip />
        
        <el-table-column prop="honorCompany" label="表彰单位" min-width="150" align="center" show-overflow-tooltip />
        
        <el-table-column prop="year" label="年份" width="100" align="center" />
        
        <el-table-column label="证明材料" width="120" align="center">
          <template #default="scope">
            <el-button 
              v-if="scope.row.attachment && scope.row.attachment !== ''" 
              type="primary"
              link
              @click="showEdvince(scope.row)">查  看
            </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 
              type="primary"
              link
              icon="Edit"
              v-if="permissions.professional_professionalteacherhonor_edit && (scope.row.state === '0' || scope.row.state === '-2')"
              @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button 
              type="success"
              link
              icon="Check"
              v-if="permissions.professional_professionalteacherhonor_exam && scope.row.state === '0'"
              @click="changeState(scope.row, 1)">通过
            </el-button>
            <el-button 
              type="danger"
              link
              icon="Close"
              v-if="permissions.professional_professionalteacherhonor_exam && (scope.row.state === '0' || scope.row.state === '1')"
              @click="changeState(scope.row, -2)">驳回
            </el-button>
            <el-button 
              type="danger"
              link
              icon="Delete"
              v-if="permissions.professional_professionalteacherhonor_del"
              @click="handleDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 子组件 -->
      <MultiDialog ref="multiDialogRef" @getList="getDataList" :page="state.pagination" :nowRow="null" />
      <ShowHonorEdvince ref="showHonorEdvinceRef" />
      <ProfessionalBackResaon ref="backReasonRef" @refreshData="handleFilter" />
      <DataForm ref="dataFormRef" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage } from '/@/hooks/message'
import { useMessageBox } from '/@/hooks/message'
import { useDict } from '/@/hooks/dict'
import { 
  fetchList, 
  putObj, 
  delObj
} from '/@/api/professional/professionaluser/professionalteacherhonor'
import { defineAsyncComponent } from 'vue'
const MultiDialog = defineAsyncComponent(() => import('/@/views/professional/teacherbase/multiDialog.vue'))
import ShowHonorEdvince from './showHonorEdvince.vue'
import ProfessionalBackResaon from '/@/views/professional/common/professional-back-resaon.vue'
import DataForm from './form.vue'

// 使用 Pinia store
const userInfoStore = useUserInfo()
const { userInfos } = storeToRefs(userInfoStore)

// 创建权限对象
const permissions = computed(() => {
  const perms: Record<string, boolean> = {}
  userInfos.value.authBtnList.forEach((perm: string) => {
    perms[perm] = true
  })
  return perms
})

// 消息提示 hooks
const message = useMessage()
const messageBox = useMessageBox()

// 字典数据
const { professional_state: professionalState } = useDict('professional_state')

// 表格引用
const tableRef = ref()
const searchFormRef = ref()
const multiDialogRef = ref()
const showHonorEdvinceRef = ref()
const backReasonRef = ref()
const dataFormRef = ref()
const showSearch = ref(true)

// 搜索表单数据
const search = reactive({
  state: '',
  teacherNo: '',
  teacherName: ''
})

// 导出加载状态
const exportLoading = ref(false)

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  pageList: async (params: any) => {
    const response = await fetchList(params)
    return {
      data: {
        records: response.data.records || [],
        total: response.data.total || 0
      }
    }
  },
  queryForm: search
})

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

// 查看证明材料
const showEdvince = (row: any) => {
  showHonorEdvinceRef.value?.init(row)
}

// 审核状态变更
const changeState = (row: any, val: number) => {
  if (val === 1) {
    // 通过
    const str = '通过'
    messageBox.confirm(`是否确认${str}${row.teacherName || row.realName}的申请`).then(async () => {
      try {
        await putObj({
          id: row.id,
          state: val
        })
        message.success('操作成功')
        getDataList()
      } catch (error) {
        // Failed to change state
      }
    }).catch(() => {})
  } else if (val === -2) {
    // 驳回
    const newRow = JSON.parse(JSON.stringify(row))
    newRow.realName = newRow.teacherName
    backReasonRef.value?.init(newRow, 'honor')
  }
}

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

// 重置查询
const resetQuery = () => {
  Object.assign(search, {
    state: '',
    teacherNo: '',
    teacherName: ''
  })
  getDataList()
}

// 打开新增窗口
const handleAdd = () => {
  multiDialogRef.value?.init(4)
}

// 打开编辑窗口
const handleEdit = (row: any) => {
  dataFormRef.value?.openDialog(row)
}

// 删除
const handleDel = (row: any) => {
  messageBox.confirm('是否确认删除该条记录').then(async () => {
    try {
      await delObj(row.id)
      message.success('删除成功')
      // 如果当前页只剩一条数据，且不是第一页，则跳转到上一页
      if (state.pagination && state.dataList && state.dataList.length === 1 && state.pagination.current && state.pagination.current > 1) {
        state.pagination.current = state.pagination.current - 1
      }
      getDataList()
    } catch (error) {
      // Failed to delete
    }
  }).catch(() => {})
}

// 导出
const handleDownLoadWord = async () => {
  exportLoading.value = true
  try {
    const response = await fetchList({
      current: 1,
      size: 999999,
      ...search
    })
    const data = response.data.records || []
    
    const tHeader = ['工号', '姓名', '荣誉', '表彰单位', '年份']
    const filterVal = ['teacherNo', 'teacherName', 'honor', 'honorCompany', 'year']
    
    // 动态导入导出工具
    const { export_json_to_excel } = await import('/@/excel/Export2Excel.js')
    const exportData = data.map((v: any) => filterVal.map((j: string) => v[j]))
    export_json_to_excel(tHeader, exportData, '综合表彰.xls')
    
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

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

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