<template>
  <div>
    <h1 class="text-xl font-bold text-gray-800 mb-4">审批配置</h1>

    <!-- 部门审批配置 -->
    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
      <div class="px-4 py-3 border-b flex items-center justify-between">
        <div>
          <h2 class="text-base font-semibold text-gray-700">部门审批配置</h2>
          <p class="text-xs text-gray-400 mt-0.5">为每个部门配置「指定审批人」和「分管领导」</p>
        </div>
      </div>
      <el-table :data="departments" stripe class="w-full">
        <el-table-column prop="name" label="部门名称" min-width="140" />
        <el-table-column label="部门负责人" min-width="120">
          <template #default="{ row }">{{ row.leader_name || '未设置' }}</template>
        </el-table-column>
        <el-table-column label="指定审批人（节点2）" min-width="200">
          <template #default="{ row }">
            <template v-if="parsedArr(row.approver_user_ids).length">
              <el-tag v-for="uid in parsedArr(row.approver_user_ids)" :key="uid" type="success" size="small" class="mr-1">{{ getUserName(uid) }}</el-tag>
            </template>
            <span v-else class="text-gray-400 text-sm">未配置（将跳过该节点）</span>
          </template>
        </el-table-column>
        <el-table-column label="分管领导（节点3）" min-width="200">
          <template #default="{ row }">
            <template v-if="parsedArr(row.vp_user_ids).length">
              <el-tag v-for="uid in parsedArr(row.vp_user_ids)" :key="uid" type="primary" size="small" class="mr-1">{{ getUserName(uid) }}</el-tag>
            </template>
            <span v-else class="text-gray-400 text-sm">未配置（将跳过该节点）</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 全局兜底审批人 -->
    <div class="bg-white rounded-xl shadow-sm border overflow-hidden mt-6">
      <div class="px-4 py-3 border-b flex items-center justify-between">
        <div>
          <h2 class="text-base font-semibold text-gray-700">全局兜底审批人</h2>
          <p class="text-xs text-gray-400 mt-0.5">未匹配到员工或部门未配置审批人时，推送给这些人审批</p>
        </div>
        <el-button type="primary" size="small" @click="globalDialogVisible = true">+ 添加</el-button>
      </div>
      <el-table :data="globalApprovers" stripe class="w-full">
        <el-table-column label="姓名" min-width="200">
          <template #default="{ row }">
            {{ row.user?.real_name || row.user?.nickname || `#${row.user_id}` }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" type="danger" :loading="deletingId === row.id" @click="handleGlobalDelete(row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑部门弹窗 -->
    <el-dialog v-model="dialogVisible" :title="'审批配置 — ' + (currentDept?.name || '')" width="580px">
      <el-form label-position="top">
        <el-form-item label="指定审批人（节点2）">
          <el-select v-model="approverUserIds" multiple filterable placeholder="可选择多人（会签审批）" class="w-full" collapse-tags collapse-tags-tooltip :max-collapse-tags="5">
            <el-option v-for="e in employees" :key="e.id" :label="`${displayName(e)}（${[e.department_name, e.position].filter(Boolean).join(' · ') || '未分配'}）`" :value="e.id" />
          </el-select>
          <div class="text-xs text-gray-400 mt-1">不选择时将跳过该节点</div>
        </el-form-item>
        <el-form-item label="分管领导（节点3）">
          <el-select v-model="vpUserIds" multiple filterable placeholder="可选择多人（会签审批）" class="w-full" collapse-tags collapse-tags-tooltip :max-collapse-tags="5">
            <el-option v-for="e in employees" :key="e.id" :label="`${displayName(e)}（${[e.department_name, e.position].filter(Boolean).join(' · ') || '未分配'}）`" :value="e.id" />
          </el-select>
          <div class="text-xs text-gray-400 mt-1">不选择时将跳过该节点</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加兜底审批人弹窗 -->
    <el-dialog v-model="globalDialogVisible" title="添加兜底审批人" width="480px">
      <el-form label-position="top">
        <el-form-item label="选择员工">
          <el-select v-model="globalUserId" filterable placeholder="请选择员工" class="w-full">
            <el-option v-for="e in employees" :key="e.id" :label="`${displayName(e)}（${[e.department_name, e.position].filter(Boolean).join(' · ') || '未分配'}）`" :value="e.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="globalDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="globalSaving" @click="handleGlobalAdd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  setDepartmentApprover,
  setDepartmentVPs,
  getEmployees,
  listAllDepartments,
  getGlobalApprovers,
  createGlobalApprover,
  deleteGlobalApprover,
} from '@/api'

const departments = ref<any[]>([])
const employees = ref<any[]>([])
const saving = ref(false)

// ===== 部门编辑 =====
const dialogVisible = ref(false)
const currentDept = ref<any>(null)
const approverUserIds = ref<number[]>([])
const vpUserIds = ref<number[]>([])

function openEdit(dept: any) {
  currentDept.value = dept
  approverUserIds.value = parsedArr(dept.approver_user_ids)
  vpUserIds.value = parsedArr(dept.vp_user_ids)
  dialogVisible.value = true
}

async function handleSave() {
  if (!currentDept.value) return
  saving.value = true
  try {
    await Promise.all([
      setDepartmentApprover(currentDept.value.id, approverUserIds.value),
      setDepartmentVPs(currentDept.value.id, vpUserIds.value),
    ])
    ElMessage.success('保存成功')
    dialogVisible.value = false
    await loadDepartments()
  } catch { /* request.ts handled */ }
  finally { saving.value = false }
}

// ===== 全局兜底 =====
const globalApprovers = ref<any[]>([])
const globalDialogVisible = ref(false)
const globalUserId = ref<number | null>(null)
const globalSaving = ref(false)
const deletingId = ref<number | null>(null)

async function loadGlobalApprovers() {
  const res = await getGlobalApprovers() as any
  globalApprovers.value = res?.data || []
}

async function handleGlobalAdd() {
  if (!globalUserId.value) { ElMessage.warning('请选择员工'); return }
  globalSaving.value = true
  try {
    await createGlobalApprover(globalUserId.value)
    ElMessage.success('添加成功')
    globalDialogVisible.value = false
    globalUserId.value = null
    await loadGlobalApprovers()
  } catch { /* request.ts handled */ }
  finally { globalSaving.value = false }
}

async function handleGlobalDelete(row: any) {
  await ElMessageBox.confirm(`确定移除 ${row.user?.real_name || row.user?.nickname || ''}？`)
  deletingId.value = row.id
  try {
    await deleteGlobalApprover(row.id)
    ElMessage.success('已移除')
    await loadGlobalApprovers()
  } catch { /* request.ts handled */ }
  finally { deletingId.value = null }
}

// ===== 工具 =====
function displayName(e: any): string {
  return e.real_name || e.nickname || e.name || `#${e.id}`
}
function getUserName(id: number): string {
  const emp = employees.value.find((e) => e.id === id)
  return emp ? displayName(emp) : `#${id}`
}
function parsedArr(str: string | null | undefined): number[] {
  if (!str) return []
  try { return JSON.parse(str) } catch { return [] }
}

async function loadDepartments() {
  const res = await listAllDepartments() as any
  // 过滤掉根节点（四川凌空，无实际部门审批意义）
  departments.value = (res?.data || []).filter((d: any) => d.id !== 1)
}
async function loadEmployees() {
  const res = await getEmployees() as any
  employees.value = res?.data || []
}

async function load() {
  await Promise.all([loadDepartments(), loadEmployees(), loadGlobalApprovers()])
}

onMounted(load)
</script>
