<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { approvalTemplateApi } from '@/api/office.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增审批模板')
const submitLoading = ref(false)
const isEdit = ref(false)

const searchForm = reactive({ type: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, name: '', type: '', form_fields: '', flow_nodes: '', status: 1, sort: 0
})

const typeMap = { 1: '请假', 2: '采购', 3: '合同', 4: '退款', 5: '换房' }

const formRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择模板类型', trigger: 'change' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await approvalTemplateApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { type: '', status: '' })
  handleSearch()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增审批模板'
  Object.assign(form, { id: null, name: '', type: '', form_fields: '', flow_nodes: '', status: 1, sort: 0 })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑审批模板'
  const res = await approvalTemplateApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, {
    id: d.id, name: d.name, type: d.type,
    form_fields: d.form_fields ? (typeof d.form_fields === 'string' ? d.form_fields : JSON.stringify(d.form_fields, null, 2)) : '',
    flow_nodes: d.flow_nodes ? (typeof d.flow_nodes === 'string' ? d.flow_nodes : JSON.stringify(d.flow_nodes, null, 2)) : '',
    status: d.status, sort: d.sort || 0
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { ...form }
      if (payload.form_fields) {
        try { payload.form_fields = JSON.parse(payload.form_fields) } catch { /* keep string */ }
      }
      if (payload.flow_nodes) {
        try { payload.flow_nodes = JSON.parse(payload.flow_nodes) } catch { /* keep string */ }
      }
      if (isEdit.value) {
        await approvalTemplateApi.update(form.id, payload)
        ElMessage.success('更新成功')
      } else {
        await approvalTemplateApi.create(payload)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除审批模板「${row.name}」吗？`, '删除确认', { type: 'warning' })
  await approvalTemplateApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList() })
</script>

<template>
  <div class="page-container">
    <div class="search-bar">
      <el-select v-model="searchForm.type" placeholder="模板类型" clearable style="width:140px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option label="启用" :value="1" />
        <el-option label="停用" :value="0" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="table-container">
      <div class="table-actions">
        <el-button type="primary" @click="handleAdd">新增模板</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData" border stripe style="width:100%">
        <el-table-column prop="name" label="模板名称" min-width="160" />
        <el-table-column label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small">{{ typeMap[row.type] || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width:100%">
            <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="表单字段">
          <el-input v-model="form.form_fields" type="textarea" :rows="4" placeholder="JSON格式，如：[{&quot;label&quot;:&quot;天数&quot;,&quot;type&quot;:&quot;number&quot;}]" />
        </el-form-item>
        <el-form-item label="审批节点">
          <el-input v-model="form.flow_nodes" type="textarea" :rows="4" placeholder="JSON格式，如：[{&quot;name&quot;:&quot;主管审批&quot;,&quot;role&quot;:&quot;manager&quot;}]" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="9999" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
