<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>部门管理</span>
          <el-button type="primary" v-permission="'department:create'" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增部门
          </el-button>
        </div>
      </template>

      <el-table
        :data="departmentTree"
        row-key="id"
        :tree-props="{ children: 'children' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="部门名称" min-width="200" />
        <el-table-column prop="code" label="部门编码" min-width="120" />
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="170" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" v-permission="'department:update'" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" v-permission="'department:create'" @click="handleAddChild(row)">添加子部门</el-button>
            <el-button link type="primary" v-permission="'department:assign_menu'" @click="handleAssignMenu(row)">分配菜单</el-button>
            <el-button link type="danger" v-permission="'department:delete'" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm" :destroy-on-close="true">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="departmentTreeForSelect"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            :render-after-expand="false"
            placeholder="请选择上级部门"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配菜单对话框 -->
    <el-dialog v-model="menuDialogVisible" title="分配部门菜单" width="500px">
      <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedMenuIds"
        :check-strictly="true"
      />
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMenus" :loading="menuSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { ElTree } from 'element-plus'
import {
  getDepartmentTree,
  createDepartment,
  updateDepartment,
  deleteDepartment,
  getDepartmentMenus,
  assignDepartmentMenus,
  type DepartmentTree
} from '@/api/department'
import { getMenuTree, type MenuTree } from '@/api/menu'

const loading = ref(false)
const departmentTree = ref<DepartmentTree[]>([])

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑部门' : '新增部门')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const formData = reactive({
  id: 0,
  parentId: 0,
  name: '',
  code: '',
  sortOrder: 0,
  status: 1
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { pattern: /^[a-z0-9_]+$/, message: '只能包含小写字母、数字和下划线', trigger: 'blur' }
  ]
}

// 用于选择上级部门的树（排除当前编辑的部门及其子部门）
const departmentTreeForSelect = computed(() => {
  if (!isEdit.value) {
    return [{ id: 0, name: '顶级部门', children: departmentTree.value }]
  }
  // 编辑时过滤掉自己及子部门
  const filterTree = (nodes: DepartmentTree[]): DepartmentTree[] => {
    return nodes
      .filter(n => n.id !== formData.id)
      .map(n => ({ ...n, children: filterTree(n.children || []) }))
  }
  return [{ id: 0, name: '顶级部门', children: filterTree(departmentTree.value) }]
})

// 菜单分配相关
const menuDialogVisible = ref(false)
const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const menuTree = ref<MenuTree[]>([])
const checkedMenuIds = ref<number[]>([])
const currentDepartmentId = ref(0)
const menuSubmitLoading = ref(false)

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDepartmentTree()
    departmentTree.value = res.data
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  formData.id = 0
  formData.parentId = 0
  formData.name = ''
  formData.code = ''
  formData.sortOrder = 0
  formData.status = 1
  formRef.value?.resetFields()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (row: DepartmentTree) => {
  isEdit.value = false
  resetForm()
  formData.parentId = row.id
  dialogVisible.value = true
}

const handleEdit = (row: DepartmentTree) => {
  isEdit.value = true
  formData.id = row.id
  formData.parentId = row.parentId
  formData.name = row.name
  formData.code = row.code
  formData.sortOrder = row.sortOrder
  formData.status = row.status
  dialogVisible.value = true
}

const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updateDepartment(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createDepartment(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row: DepartmentTree) => {
  try {
    await ElMessageBox.confirm(`确定要删除部门 "${row.name}" 吗？删除后其子部门也会被删除。`, '提示', { type: 'warning' })
    await deleteDepartment(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

const handleAssignMenu = async (row: DepartmentTree) => {
  currentDepartmentId.value = row.id
  // 加载菜单树
  if (menuTree.value.length === 0) {
    const res = await getMenuTree()
    menuTree.value = res.data
  }
  // 加载已分配菜单
  const res = await getDepartmentMenus(row.id)
  checkedMenuIds.value = res.data
  menuDialogVisible.value = true
}

const handleSubmitMenus = async () => {
  menuSubmitLoading.value = true
  try {
    const menuIds = menuTreeRef.value?.getCheckedKeys(false) as number[]
    await assignDepartmentMenus({ departmentId: currentDepartmentId.value, menuIds })
    ElMessage.success('分配成功')
    menuDialogVisible.value = false
  } finally {
    menuSubmitLoading.value = false
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
