<template>
  <section class="space-y-6">
    <header class="flex items-center justify-between">
      <div>
        <h1 class="mos-title text-2xl font-semibold">部门管理</h1>
        <p class="mos-muted text-sm">管理系统部门组织架构。</p>
      </div>
      <button class="mos-btn mos-btn-accent" @click="openCreateDialog(0 as number)">
        新建部门
      </button>
    </header>

    <!-- 部门树形列表 -->
    <div class="mos-card p-5">
      <div v-if="loading" class="py-8 text-center text-mosquito-ink/60">
        加载中...
      </div>
      <div v-else-if="!treeData.length" class="py-8 text-center text-mosquito-ink/60">
        暂无部门数据
      </div>
      <div v-else class="space-y-1">
        <div
          v-for="dept in treeData"
          :key="dept.id"
          class="border border-mosquito-line rounded-lg overflow-hidden"
        >
          <div class="px-4 py-3 hover:bg-mosquito-bg/50">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <span class="font-semibold">{{ dept.deptName }}</span>
                <span class="text-xs text-mosquito-ink/50">{{ dept.deptCode }}</span>
              </div>
              <div class="flex gap-2">
                <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="openCreateDialog(dept.id || 0)">
                  添加子部门
                </button>
                <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="openEditDialog(dept)">
                  编辑
                </button>
                <button class="mos-btn mos-btn-danger !py-1 !px-2 !text-xs" @click="handleDelete(dept)">
                  删除
                </button>
              </div>
            </div>
            <!-- 子部门 -->
            <div v-if="dept.children?.length" class="mt-2 pl-6 space-y-1 bg-mosquito-bg/30 rounded-lg p-2">
              <div
                v-for="child in dept.children"
                :key="child.id"
                class="flex items-center justify-between py-2 px-3 bg-white rounded border border-mosquito-line"
              >
                <div class="flex items-center gap-2">
                  <span>{{ child.deptName }}</span>
                  <span class="text-xs text-mosquito-ink/50">{{ child.deptCode }}</span>
                </div>
                <div class="flex gap-2">
                  <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="openEditDialog(child)">编辑</button>
                  <button class="mos-btn mos-btn-danger !py-1 !px-2 !text-xs" @click="handleDelete(child)">删除</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑对话框 -->
    <div v-if="dialogVisible" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div class="mos-card w-[500px] p-6">
        <h2 class="text-lg font-semibold mb-4">{{ isEdit ? '编辑部门' : '新建部门' }}</h2>
        <div class="space-y-4">
          <div>
            <label class="text-xs font-semibold text-mosquito-ink/70">部门名称</label>
            <input v-model="form.deptName" class="mos-input mt-2 w-full" placeholder="如: 运营部" />
          </div>
          <div>
            <label class="text-xs font-semibold text-mosquito-ink/70">部门编码</label>
            <input v-model="form.deptCode" class="mos-input mt-2 w-full" placeholder="如: DEPT001" />
          </div>
          <div>
            <label class="text-xs font-semibold text-mosquito-ink/70">排序</label>
            <input v-model.number="form.sortOrder" type="number" class="mos-input mt-2 w-full" placeholder="0" />
          </div>
          <div v-if="isEdit">
            <label class="text-xs font-semibold text-mosquito-ink/70">状态</label>
            <select v-model="form.status" class="mos-input mt-2 w-full">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>
        </div>
        <div class="flex justify-end gap-2 mt-6">
          <button class="mos-btn mos-btn-secondary" @click="dialogVisible = false">取消</button>
          <button class="mos-btn mos-btn-accent" @click="handleSubmit">
            {{ isEdit ? '保存' : '创建' }}
          </button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { type Department } from '../services/department'
import departmentService from '../services/department'

interface DepartmentWithChildren extends Department {
  children?: DepartmentWithChildren[]
}

const loading = ref(false)
const departments = ref<Department[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)

const form = ref({
  id: 0,
  parentId: 0,
  deptName: '',
  deptCode: '',
  sortOrder: 0,
  status: 1
})

// 树形结构
const treeData = computed(() => {
  const deptMap = new Map<number, DepartmentWithChildren>()
  const roots: DepartmentWithChildren[] = []

  departments.value.forEach(dept => {
    deptMap.set(dept.id!, { ...dept, children: [] })
  })

  departments.value.forEach(dept => {
    const node = deptMap.get(dept.id!)!
    if (dept.parentId && dept.parentId > 0 && deptMap.has(dept.parentId)) {
      deptMap.get(dept.parentId)!.children!.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
})

const loadDepartments = async () => {
  loading.value = true
  try {
    departments.value = await departmentService.getDepartments()
  } catch (error) {
    console.error('加载部门失败:', error)
  } finally {
    loading.value = false
  }
}

const openCreateDialog = (parentId: number) => {
  isEdit.value = false
  form.value = {
    id: 0,
    parentId,
    deptName: '',
    deptCode: '',
    sortOrder: 0,
    status: 1
  }
  dialogVisible.value = true
}

const openEditDialog = (dept: Department) => {
  isEdit.value = true
  form.value = {
    id: dept.id!,
    parentId: dept.parentId || 0,
    deptName: dept.deptName,
    deptCode: dept.deptCode || '',
    sortOrder: dept.sortOrder || 0,
    status: dept.status
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      await departmentService.updateDepartment(form.value.id, form.value)
      alert('部门更新成功')
    } else {
      await departmentService.createDepartment(form.value)
      alert('部门创建成功')
    }
    dialogVisible.value = false
    await loadDepartments()
  } catch (error) {
    alert(error instanceof Error ? error.message : '操作失败')
  }
}

const handleDelete = async (dept: Department) => {
  if (!confirm(`确定要删除部门 ${dept.deptName} 吗？`)) return
  try {
    if (dept.id) {
      await departmentService.deleteDepartment(dept.id)
      alert('部门删除成功')
      await loadDepartments()
    }
  } catch (error) {
    alert(error instanceof Error ? error.message : '删除失败')
  }
}

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