<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 操作按钮 -->
      <el-row>
        <div class="mb15" style="width: 100%;">
          <el-button
            v-if="hasAuth('professional_professionalteachingmaterialconfig_add')"
            type="primary"
            icon="FolderAdd"
            @click="handleAdd">新 增
          </el-button>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :data="state.dataList"
        v-loading="state.loading"
        border
        row-key="id"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="typeName" label="类型名称" min-width="150" align="center" show-overflow-tooltip />
        
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />
        
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        
        <el-table-column prop="remarks" label="备注" min-width="200" align="center" show-overflow-tooltip />
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="hasAuth('professional_professionalteachingmaterialconfig_edit')"
              icon="edit-pen"
              link
              type="primary"
              @click="handleEdit(scope.row)">修改
            </el-button>
            <el-button
              v-if="hasAuth('professional_professionalteachingmaterialconfig_del')"
              icon="delete"
              link
              type="danger"
              style="margin-left: 12px"
              @click="handleDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑' : '新增'"
        width="600px"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="类型名称" prop="typeName">
            <el-input
              v-model="form.typeName"
              placeholder="请输入类型名称"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              placeholder="请输入排序"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              clearable
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useAuth } from '/@/hooks/auth'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage } from '/@/hooks/message'
import { useMessageBox } from '/@/hooks/message'
import { fetchList, addObj, putObj, delObj } from '/@/api/professional/rsbase/professionalteachingmaterialconfig'

const { hasAuth } = useAuth()
// 消息提示 hooks
const message = useMessage()
const messageBox = useMessageBox()

// 表格引用
const tableRef = ref()
const formRef = ref()

// 弹窗状态
const dialogVisible = ref(false)
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: '',
  typeName: '',
  sort: 0,
  remarks: ''
})

// 表单验证规则
const formRules = {
  typeName: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 配置 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: {}
})

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

// 打开新增窗口
const handleAdd = () => {
  Object.assign(form, {
    id: '',
    typeName: '',
    sort: 0,
    remarks: ''
  })
  dialogVisible.value = true
}

// 打开编辑窗口
const handleEdit = async (row: any) => {
  Object.assign(form, {
    id: row.id,
    typeName: row.typeName || '',
    sort: row.sort || 0,
    remarks: row.remarks || ''
  })
  dialogVisible.value = true
}

// 删除
const handleDel = (row: any) => {
  messageBox.confirm('是否确认删除该条记录').then(async () => {
    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(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await putObj(form)
          message.success('修改成功')
        } else {
          await addObj(form)
          message.success('添加成功')
        }
        dialogVisible.value = false
        getDataList()
      } catch (error: any) {
        // 处理业务错误
        
      } finally {
        submitLoading.value = false
      }
    }
  })
}

</script>

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