<template>
  <div>
    <div class="flex items-center justify-between mb-4">
      <h1 class="text-xl font-bold text-gray-800">组织架构</h1>
      <el-button type="primary" size="small" @click="openAddDept(null)">+ 新增根部门</el-button>
    </div>

    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
      <!-- 搜索栏 -->
      <div class="flex items-center gap-3 px-4 py-3 border-b">
        <el-input v-model="search" placeholder="搜索部门名称" clearable class="max-w-xs" size="small" @clear="onSearch" @input="onSearch" />
        <el-button size="small" @click="loadData">
          <template #icon><span class="i-carbon-refresh" /></template>
          刷新
        </el-button>
      </div>

      <!-- 部门表格（可展开行） -->
      <div v-loading="loading">
        <el-table ref="tableRef" :data="flatDepts" row-key="id" border stripe class="w-full" @expand-change="onExpandChange" @row-click="onRowClick">
          <el-table-column type="expand" width="50">
            <template #default="{ row }">
              <!-- 展开后显示该部门的员工列表（迷你表格） -->
              <div class="px-6 py-4" v-if="row._empList && row._empList.length">
                <el-table :data="row._empList" size="small" stripe class="w-full">
                  <el-table-column label="姓名" min-width="100">
                    <template #default="{ row: emp }">
                      <div class="flex items-center gap-2">
                        <span class="i-carbon-user text-blue-400 text-sm shrink-0" />
                        <span class="text-gray-700 font-medium">{{ emp.name }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="职位" min-width="100">
                    <template #default="{ row: emp }">
                      <span class="text-gray-500">{{ emp.position || '-' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="员工类型" min-width="110">
                    <template #default="{ row: emp }">
                      <el-tag v-if="emp.employeeType === 'department_leader'" size="small" type="warning">部门负责人</el-tag>
                      <el-tag v-else-if="emp.employeeType === 'deputy_leader'" size="small">副负责人</el-tag>
                      <el-tag v-else size="small" type="info">{{ emp.employeeTypeLabel || '员工' }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80" fixed="right">
                    <template #default="{ row: emp }">
                      <el-button size="small" type="danger" link @click="handleEmpRemove(emp)">移出</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-else class="px-6 py-3 text-sm text-gray-400">暂无员工</div>
            </template>
          </el-table-column>

          <el-table-column label="部门名称" min-width="220">
            <template #default="{ row }">
              <div class="flex items-center gap-2" :style="{ paddingLeft: row._depth * 24 + 'px' }">
                <span class="i-carbon-folder text-yellow-500 text-sm shrink-0" />
                <span class="font-medium text-gray-700">{{ row.name }}</span>
                <span class="text-gray-400 text-xs">（{{ row._empCount }}人）</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="340">
            <template #default="{ row }">
              <div class="flex items-center gap-1">
                <el-button size="small" type="primary" link @click="openAddDept(row)">新增子部门</el-button>
                <el-button size="small" type="primary" link @click="openEmpManage(row)">管理员工</el-button>
                <el-button size="small" type="primary" link @click="openEditDept(row)">编辑</el-button>
                <el-button size="small" type="danger" link @click="handleDeleteDept(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!flatDepts.length && !loading" class="text-center text-gray-400 py-12">暂无部门数据</div>
      </div>
    </div>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog v-model="deptDialogVisible" :title="deptEditId ? '编辑部门' : '新增部门'" width="450px" :close-on-click-modal="false">
      <el-form :model="deptForm" label-width="100px">
        <el-form-item label="部门名称">
          <el-input v-model="deptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item v-if="deptForm.parent_id" label="上级部门">
          <span class="text-gray-500">{{ getDeptName(deptForm.parent_id) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deptDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="deptSaving" @click="handleSaveDept">保存</el-button>
      </template>
    </el-dialog>

    <!-- ============ 员工管理对话框 ============ -->
    <el-dialog v-model="empManageVisible" :title="'管理员工 — ' + (empManageDept?.name || '')" width="500px" :close-on-click-modal="false">
      <div v-loading="empManageLoading">
        <div class="text-sm font-medium text-gray-700 mb-2">当前部门员工</div>
        <div v-if="empManageList.length === 0" class="text-gray-400 text-sm py-3">暂无员工</div>
        <div v-for="emp in empManageList" :key="emp.id"
          class="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-gray-50">
          <div>
            <span class="text-sm text-gray-700">{{ emp.real_name || emp.nickname || emp.name }}</span>
            <span v-if="emp.position" class="text-xs text-gray-400 ml-2">{{ emp.position }}</span>
          </div>
          <el-button size="small" type="danger" plain @click="handleEmpRemove(emp)">移出</el-button>
        </div>

        <el-divider />

        <div class="text-sm font-medium text-gray-700 mb-2">添加员工</div>
        <div class="flex gap-2 items-start">
          <div class="flex-1 space-y-2">
            <el-select v-model="empManageNewId" filterable placeholder="选择员工添加" class="w-full" size="default">
              <el-option
                v-for="e in availableEmployees"
                :key="e.id"
                :label="(e.real_name || e.nickname || e.name) + (e.position ? '（' + e.position + '）' : '')"
                :value="e.id"
              />
            </el-select>
            <el-input v-model="empManageNewPosition" placeholder="职位（如：前端工程师）" size="default" />
          </div>
          <el-button type="primary" :disabled="!empManageNewId" :loading="empManageAdding" @click="handleEmpAdd" class="mt-0">添加</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="empManageVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDepartmentTree,
  createDepartment,
  updateDepartment,
  deleteDepartment,
  getEmployees,
  getEmployeeDepartments,
  setEmployeeDepartment,
  clearEmployeeDepartment,
} from '@/api'

// ============ 状态 ============

const loading = ref(false)
const search = ref('')
const tableRef = ref<any>(null)

/** 平铺后的部门列表（含层级 depth） */
const flatDepts = ref<any[]>([])

// 部门表单
const deptDialogVisible = ref(false)
const deptEditId = ref<number | null>(null)
const deptSaving = ref(false)
const deptForm = ref<{ name: string; parent_id: number | null }>({
  name: '',
  parent_id: null,
})

// 原始数据缓存
let rawTree: any[] = []
let flatDeptMap = new Map<number, any>()
let allEmployees: any[] = []

// ============ 数据加载 ============

async function loadData() {
  loading.value = true

  const [treeRes, empRes, mappingRes] = await Promise.all([
    getDepartmentTree().catch(() => null),
    getEmployees().catch(() => null),
    getEmployeeDepartments().catch(() => null),
  ])

  rawTree = (treeRes as any)?.data || []

  const empList: any[] = (empRes as any)?.data?.list || (empRes as any)?.data || []
  const empInfoMap: Record<number, any> = {}
  for (const e of empList) {
    empInfoMap[e.id || e.user_id] = e
  }

  const mappingList: any[] = (mappingRes as any)?.data?.list || (mappingRes as any)?.data || []

  // 关联表映射：user_id → { department_id, department_name }
  const mappingByUser: Record<number, any> = {}
  for (const m of mappingList) {
    mappingByUser[m.user_id] = m
  }

  // 所有员工（含未分配部门的），department_id/position 优先从关联表取
  allEmployees = empList.map((e: any) => {
    const uid = e.id || e.user_id
    const map = mappingByUser[uid]
    return {
      id: uid,
      real_name: e.name || e.real_name || '',
      name: e.name || e.real_name || '',
      position: map?.position || e.position || '',
      employee_type: e.employee_type || '',
      department_id: map?.department_id ?? null,
      department_name: map?.department_name || '',
    }
  })

  rebuildFlatList()

  loading.value = false
}

/** 将部门树平铺为一维数组，附带 depth 和员工列表 */
function rebuildFlatList() {
  flatDeptMap.clear()
  const result: any[] = []

  function flatten(nodes: any[], depth: number) {
    for (const dept of nodes) {
      flatDeptMap.set(dept.id, dept)

      // 该部门的直属员工
      const empList = allEmployees
        .filter((e) => e.department_id === dept.id)
        .map((e) => ({
          id: e.id,
          name: e.real_name || e.nickname || e.name || `#${e.id}`,
          position: e.position || '',
          employeeType: e.employee_type || '',
          employeeTypeLabel: e.employee_type === 'department_leader' ? '部门负责人'
            : e.employee_type === 'deputy_leader' ? '副负责人'
            : e.employee_type === 'vice_president' ? '副总裁'
            : e.employee_type === 'general_manager' ? '总经理'
            : '员工',
        }))

      // 子孙部门员工总数
      function countSub(n: any[]): number {
        let c = 0
        for (const d of n) {
          c += allEmployees.filter((e) => e.department_id === d.id).length
          if (d.children?.length) c += countSub(d.children)
        }
        return c
      }
      const subCount = dept.children?.length ? countSub(dept.children) : 0
      const empCount = empList.length + subCount

      result.push({
        id: dept.id,
        name: dept.name,
        parent_id: dept.parent_id,
        _depth: depth,
        _empList: empList,
        _empCount: empCount,
        _children: dept.children || [],
      })

      if (dept.children?.length) {
        flatten(dept.children, depth + 1)
      }
    }
  }

  flatten(rawTree, 0)
  flatDepts.value = result
}

// ============ 搜索 ============

function onSearch() {
  // 简单的前端过滤：搜索时只显示名称匹配的部门
  if (!search.value) {
    rebuildFlatList()
    return
  }
  const kw = search.value.toLowerCase()
  flatDepts.value = flatDepts.value.filter((d) => d.name.toLowerCase().includes(kw))
}

/** 展开/收起某行时 */
function onExpandChange(row: any, expanded: boolean) {
  // 暂不需要额外逻辑
}

/** 点击行切换展开/折叠（点击操作按钮时不触发） */
function onRowClick(row: any, _column: any, event: Event) {
  // 如果点击目标是按钮或按钮内的元素，不切换
  const target = event.target as HTMLElement
  if (target.closest('.el-button, .el-button *')) return
  tableRef.value?.toggleRowExpansion(row)
}

// ============ 部门名称查询 ============

function getDeptName(id: number): string {
  const dept = flatDeptMap.get(id)
  return dept?.name || '（已删除）'
}

/** 获取原始树节点（用于删除判断子部门） */
function getRawNode(id: number): any {
  function find(nodes: any[]): any {
    for (const n of nodes) {
      if (n.id === id) return n
      if (n.children?.length) {
        const found = find(n.children)
        if (found) return found
      }
    }
    return null
  }
  return find(rawTree)
}

// ============ 新增/编辑部门 ============

function openAddDept(parent: any) {
  deptEditId.value = null
  deptForm.value = {
    name: '',
    parent_id: parent?.id ?? null,
  }
  deptDialogVisible.value = true
}

function openEditDept(data: any) {
  deptEditId.value = data.id
  deptForm.value = {
    name: data.name || '',
    parent_id: data.parent_id ?? null,
  }
  deptDialogVisible.value = true
}

async function handleSaveDept() {
  if (!deptForm.value.name.trim()) {
    ElMessage.warning('请输入部门名称')
    return
  }

  deptSaving.value = true
  try {
    if (deptEditId.value) {
      await updateDepartment(deptEditId.value, {
        name: deptForm.value.name.trim(),
        parent_id: deptForm.value.parent_id,
      })
      ElMessage.success('修改成功')
    } else {
      await createDepartment({
        name: deptForm.value.name.trim(),
        parent_id: deptForm.value.parent_id,
      })
      ElMessage.success('创建成功')
    }
    deptDialogVisible.value = false
    await loadData()
  } catch (err: any) {
    ElMessage.error(err.message || '操作失败')
  } finally {
    deptSaving.value = false
  }
}

// ============ 删除部门 ============

async function handleDeleteDept(data: any) {
  const raw = getRawNode(data.id)
  const hasChildren = raw?.children?.length > 0
  const hasEmployees = data._empCount > 0

  let msg = `确定删除部门「${data.name}」？`
  if (hasChildren) msg += ' 其子部门也将一并删除。'
  if (hasEmployees) msg += ' 该部门下的员工将被移除关联。'

  try {
    await ElMessageBox.confirm(msg, '确认删除', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteDepartment(data.id)
    ElMessage.success('删除成功')
    await loadData()
  } catch {
    // 取消则不处理
  }
}

// ============ 员工管理 ============

const empManageVisible = ref(false)
const empManageLoading = ref(false)
const empManageAdding = ref(false)
const empManageDept = ref<any>(null)
const empManageList = ref<any[]>([])
const empManageNewId = ref<number | null>(null)
const empManageNewPosition = ref('')

const availableEmployees = computed(() =>
  allEmployees.filter((e) => e.department_id !== empManageDept.value?.id),
)

function openEmpManage(dept: any) {
  empManageDept.value = dept
  empManageList.value = allEmployees.filter((e) => e.department_id === dept.id)
  empManageNewId.value = null
  empManageNewPosition.value = ''
  empManageVisible.value = true
}

async function handleEmpAdd() {
  if (!empManageNewId.value || !empManageDept.value) return
  empManageAdding.value = true
  try {
    await setEmployeeDepartment(empManageNewId.value, empManageDept.value.id, empManageNewPosition.value || undefined)
    ElMessage.success('添加成功')
    empManageNewId.value = null
    empManageNewPosition.value = ''
    await loadData()
    empManageList.value = allEmployees.filter((e) => e.department_id === empManageDept.value.id)
  } catch (err: any) {
    ElMessage.error(err.message || '添加失败')
  } finally {
    empManageAdding.value = false
  }
}

async function handleEmpRemove(emp: any) {
  try {
    await ElMessageBox.confirm(`确定将 ${emp.real_name || emp.nickname || emp.name} 移出该部门？`, '确认')
    await clearEmployeeDepartment(emp.id)
    ElMessage.success('已移出')
    await loadData()
    empManageList.value = allEmployees.filter((e) => e.department_id === empManageDept.value?.id)
  } catch {
    // 取消则不处理
  }
}

// ============ 初始化 ============

onMounted(loadData)
</script>
