<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row shadow="hover" v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="单位名称" prop="companyName">
            <el-input 
              v-model="state.queryForm.companyName" 
              placeholder="请输入单位名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb15" style="width: 100%;">
          <el-button
            v-if="hasAuth('professional_outercompany_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="companyName" label="单位名称" min-width="200" align="center" show-overflow-tooltip />
        
        <el-table-column label="允许时段" min-width="250" align="center">
          <template #default="scope">
            <span v-if="scope.row.allowStartTime && scope.row.allowEndTime">
              {{ scope.row.allowStartTime }} - {{ scope.row.allowEndTime }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" />
        
        <el-table-column label="操作" min-width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="hasAuth('professional_outercompany_edit')"
              icon="edit-pen"
              link
              type="primary"
              @click="handleEdit(scope.row)">修改
            </el-button>
            <el-button
              v-if="hasAuth('professional_outercompany_del')"
              icon="delete"
              link
              type="danger"
              @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="companyName">
            <el-input
              v-model="form.companyName"
              placeholder="请输入单位名称"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="开始时段" prop="allowStartTime">
            <el-date-picker
              v-model="form.allowStartTime"
              type="date"
              placeholder="请选择开始时段"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="截止时段" prop="allowEndTime">
            <el-date-picker
              v-model="form.allowEndTime"
              type="date"
              placeholder="请选择截止时段"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </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, getObj } from '/@/api/professional/stayschool/outercompany'

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

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

// 搜索显示
const showSearch = ref(true)

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

// 表单数据
const form = reactive({
  id: '',
  companyName: '',
  allowStartTime: '',
  allowEndTime: '',
  companyType: '0'
})

// 表单验证规则
const formRules = {
  companyName: [
    { required: true, message: '请输入单位名称', trigger: 'blur' }
  ]
}

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

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

// 重置查询
const resetQuery = () => {
  queryRef.value?.resetFields()
  getDataList()
}

// 打开新增窗口
const handleAdd = () => {
  Object.assign(form, {
    id: '',
    companyName: '',
    allowStartTime: '',
    allowEndTime: '',
    companyType: '0'
  })
  dialogVisible.value = true
}

// 打开编辑窗口
const handleEdit = async (row: any) => {
  try {
    const response = await getObj(row.id)
    Object.assign(form, {
      id: response.data.id,
      companyName: response.data.companyName || '',
      allowStartTime: response.data.allowStartTime || '',
      allowEndTime: response.data.allowEndTime || '',
      companyType: response.data.companyType || '0'
    })
    dialogVisible.value = true
  } catch (error) {
    // 获取详情失败
  }
}

// 删除
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) {
        // 处理业务错误
        message.error(error.msg)
      } finally {
        submitLoading.value = false
      }
    }
  })
}
</script>

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