<template>
  <div class="app-page org-workbench">
    <div class="page-hero">
      <div class="hero-info">
        <h2>组织架构</h2>
        <p>部门树 + 人员管理</p>
      </div>
      <div class="hero-actions">
        <el-button @click="showDeptForm = true; editingDept = null" round>添加部门</el-button>
        <el-button type="primary" @click="showUserCreate = true" round>添加成员</el-button>
        <el-button type="warning" @click="handleInitSeed" round :disabled="users.length > 1">
          初始化企业数据
        </el-button>
      </div>
    </div>

    <div class="two-col">
      <!-- Left: Department Tree -->
      <div class="col dept-col">
        <div class="col-head">部门结构</div>
        <el-tree :data="tree" node-key="id" default-expand-all :props="{ label: 'name', children: 'children' }">
          <template #default="{ data }">
            <span class="tree-node">
              <span class="tree-name">{{ data.name }}</span>
              <el-tag v-if="data.leaderName" size="small" effect="plain" type="info" round>负责人 {{ data.leaderName }}</el-tag>
              <span class="tree-actions">
                <el-button link size="small" @click.stop="editDept(data)">编辑</el-button>
                <el-button link size="small" type="danger" @click.stop="delDept(data.id)">删除</el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- Right: User List -->
      <div class="col user-col">
        <div class="col-head">人员列表 <span class="count">{{ users.length }} 人</span></div>
        <el-table :data="users" stripe style="width:100%" size="small">
          <el-table-column prop="username" label="用户名" min-width="100" show-overflow-tooltip />
          <el-table-column prop="realName" label="姓名" min-width="90" show-overflow-tooltip />
          <el-table-column prop="position" label="职位" min-width="110" show-overflow-tooltip />
          <el-table-column label="部门" min-width="130">
            <template #default="{ row }">
              <el-select v-model="row._deptId" size="small" @change="v => updateDept(row.id, v)" placeholder="选择" clearable>
                <el-option v-for="d in flatTree" :key="d.id" :label="d.name" :value="d.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="直属上级" min-width="130">
            <template #default="{ row }">
              <el-select v-model="row.superiorId" size="small" @change="v => updateSuperior(row.id, v)" placeholder="选择" clearable>
                <el-option v-for="u in users.filter(x => x.id !== row.id)" :key="u.id" :label="u.realName" :value="u.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="role" label="角色" width="110">
            <template #default="{ row }">
              <el-tag :color="roleColor(row.role)" size="small" effect="dark" round style="border:none">
                {{ roleLabel(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="statusType(row.status)" size="small" effect="plain" round>{{ statusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="210" fixed="right">
            <template #default="{ row }">
              <el-button link size="small" type="primary" @click="editUser(row)">编辑</el-button>
              <el-button link size="small" type="warning" @click="disableUser(row)" :disabled="row.status === 'DISABLED' || row.id === 1">禁用</el-button>
              <el-button link size="small" type="warning" @click="markUserLeft(row)" :disabled="row.status === 'LEFT' || row.id === 1">离职</el-button>
              <el-button link size="small" type="danger" @click="delUser(row.id)" :disabled="row.id === 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Dept Dialog -->
    <el-dialog v-model="showDeptForm" :title="editingDept ? '编辑部门' : '添加部门'" width="420px">
      <el-form label-width="80px">
        <el-form-item label="名称"><el-input v-model="deptForm.name" /></el-form-item>
        <el-form-item label="上级部门">
          <el-tree-select v-model="deptForm.parentId" :data="tree" :props="{ label: 'name', value: 'id' }"
            check-strictly clearable placeholder="无（顶级）" style="width:100%" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="deptForm.leaderId" clearable placeholder="选择负责人" style="width:100%">
            <el-option v-for="u in users" :key="u.id" :label="u.realName" :value="u.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDeptForm = false">取消</el-button>
        <el-button type="primary" @click="saveDept">保存</el-button>
      </template>
    </el-dialog>

    <!-- User Dialog -->
    <el-dialog v-model="showUserCreate" :title="editingUser ? '编辑成员' : '添加成员'" width="460px">
      <el-form label-width="80px">
        <el-form-item label="用户名" required><el-input v-model="userForm.username" :disabled="!!editingUser" /></el-form-item>
        <el-form-item label="密码" :required="!editingUser">
          <el-input v-model="userForm.password" :placeholder="editingUser ? '留空不修改' : '设置密码'" show-password />
        </el-form-item>
        <el-form-item label="姓名" required><el-input v-model="userForm.realName" /></el-form-item>
        <el-form-item label="岗位">
          <el-select v-model="userForm.position" filterable placeholder="选择岗位（对应KPI模板）" style="width:100%">
            <el-option v-for="n in templateNames" :key="n" :label="n" :value="n" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="userForm.departmentId" clearable style="width:100%">
            <el-option v-for="d in flatTree" :key="d.id" :label="d.name" :value="d.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="直属上级">
          <el-select v-model="userForm.superiorId" clearable style="width:100%">
            <el-option v-for="u in users.filter(x => x.id !== editingUser?.id)" :key="u.id" :label="u.realName" :value="u.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="普通员工" value="EMPLOYEE" />
            <el-option label="团队主管" value="TEAM_LEADER" />
            <el-option label="部门负责人" value="DEPT_LEADER" />
            <el-option label="HR管理员" value="HR_ADMIN" />
            <el-option label="超级管理员" value="SUPER_ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" v-if="editingUser">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="正常" value="ACTIVE" />
            <el-option label="禁用" value="DISABLED" />
            <el-option label="离职" value="LEFT" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUserCreate = false; editingUser = null">取消</el-button>
        <el-button type="primary" @click="saveUser">{{ editingUser ? '保存' : '创建' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { orgApi, kpiApi } from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const tree = ref([])
const users = ref([])
const templateNames = ref([])
const showDeptForm = ref(false)
const showUserCreate = ref(false)
const editingDept = ref(null)
const editingUser = ref(null)
const deptForm = ref({ name: '', parentId: null, leaderId: null })
const userForm = ref({ username: '', password: '', realName: '', position: '', departmentId: null, superiorId: null, role: 'EMPLOYEE' })

function roleLabel(role) {
  const map = { SUPER_ADMIN: '管理员', HR_ADMIN: 'HR管理员', DEPT_LEADER: '部门负责人', TEAM_LEADER: '团队主管', EMPLOYEE: '员工' }
  return map[role] || '员工'
}
function roleColor(role) {
  const map = { SUPER_ADMIN: 'var(--color-danger)', HR_ADMIN: 'var(--color-warning)', DEPT_LEADER: 'var(--color-brand-muted)', TEAM_LEADER: 'var(--color-accent)', EMPLOYEE: 'var(--color-info)' }
  return map[role] || 'var(--color-info)'
}
function statusLabel(status) { return { ACTIVE: '正常', DISABLED: '禁用', LEFT: '离职' }[status || 'ACTIVE'] || status }
function statusType(status) { return { ACTIVE: 'success', DISABLED: 'warning', LEFT: 'info' }[status || 'ACTIVE'] || 'info' }

const flatTree = computed(() => {
  const result = []
  function walk(nodes, prefix = '') {
    for (const n of nodes) {
      result.push({ id: n.id, name: prefix + n.name })
      if (n.children?.length) walk(n.children, prefix + '├ ')
    }
  }
  walk(tree.value)
  return result
})

onMounted(() => load())

async function load() {
  tree.value = await orgApi.getTree()
  users.value = await orgApi.getUsers()
  users.value.forEach(u => { u._deptId = u.departmentId })
  try { templateNames.value = await kpiApi.getTemplateNames() } catch { templateNames.value = [] }
}

// Department CRUD
function editDept(d) { editingDept.value = d; deptForm.value = { name: d.name, parentId: d.parentId, leaderId: d.leaderId }; showDeptForm.value = true }
async function saveDept() {
  if (editingDept.value) await orgApi.updateDept(editingDept.value.id, deptForm.value)
  else await orgApi.createDept(deptForm.value)
  ElMessage.success('保存成功'); showDeptForm.value = false; load()
}
async function delDept(id) {
  await ElMessageBox.confirm('确定删除该部门吗？', '提示', { type: 'warning' })
  await orgApi.deleteDept(id); ElMessage.success('已删除'); load()
}

// User CRUD
function editUser(u) {
  editingUser.value = u
  userForm.value = { username: u.username, password: '', realName: u.realName, position: u.position || '', departmentId: u.departmentId, superiorId: u.superiorId, role: u.role, status: u.status || 'ACTIVE' }
  showUserCreate.value = true
}
async function saveUser() {
  if (!userForm.value.username || !userForm.value.realName) { ElMessage.warning('用户名和姓名必填'); return }
  if (!editingUser.value && !userForm.value.password) { ElMessage.warning('请设置密码'); return }
  try {
    if (editingUser.value) await orgApi.updateUser(editingUser.value.id, userForm.value)
    else await orgApi.createUser(userForm.value)
    ElMessage.success(editingUser.value ? '已保存' : '已创建')
    showUserCreate.value = false; editingUser.value = null
    userForm.value = { username: '', password: '', realName: '', position: '', departmentId: null, superiorId: null, role: 'EMPLOYEE' }
    load()
  } catch {}
}
async function delUser(id) {
  await ElMessageBox.confirm('确定删除该用户吗？此操作不可恢复。', '删除用户', { type: 'error', confirmButtonText: '确认删除' })
  await orgApi.deleteUser(id); ElMessage.success('已删除'); load()
}
async function updateSuperior(userId, superiorId) { await orgApi.updateSuperior(userId, superiorId); ElMessage.success('已更新') }
async function updateDept(userId, deptId) { await orgApi.updateDepartment(userId, deptId); ElMessage.success('已更新') }

async function disableUser(row) {
  await ElMessageBox.confirm(`确定禁用 ${row.realName} 的账号吗？禁用后无法登录。`, '禁用账号', { type: 'warning' })
  await orgApi.disableUser(row.id)
  ElMessage.success('账号已禁用')
  load()
}

async function markUserLeft(row) {
  await ElMessageBox.confirm(`确定将 ${row.realName} 标记为离职吗？离职后无法登录且不会进入新周期。`, '标记离职', { type: 'warning' })
  await orgApi.markUserLeft(row.id)
  ElMessage.success('已标记离职')
  load()
}

async function handleInitSeed() {
  await ElMessageBox.confirm(
    '将初始化企业组织数据：深圳总部（含4个中心）+甘肃运营中心，以及韩拓等7名员工。确定继续？',
    '初始化企业数据', { type: 'info', confirmButtonText: '确定初始化' }
  )
  await orgApi.initSeed()
  ElMessage.success('企业数据已初始化')
  load()
}
</script>

<style scoped>
.page { width: 100%; }
.page-hero { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
.hero-info h2 { font-size: 28px; font-weight: 700; color: var(--color-text); margin: 0; }
.hero-info p { font-size: 14px; color: var(--color-text-secondary); margin: 4px 0 0; }
.hero-actions { display: flex; gap: 8px; }

.two-col { display: flex; gap: 20px; }
.col { background: var(--color-surface); border-radius: 8px; padding: 20px 24px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); border: 1px solid var(--color-border-soft); }
.dept-col { width: 320px; flex-shrink: 0; }
.user-col { flex: 1; min-width: 0; }
.col-head { font-size: 15px; font-weight: 700; color: var(--color-text); margin-bottom: 16px; }
.count { font-size: 12px; color: var(--color-text-muted); font-weight: 400; margin-left: 8px; }

.tree-node { display: flex; align-items: center; gap: 8px; font-size: 14px; flex: 1; }
.tree-name { font-weight: 500; }
.tree-actions { margin-left: auto; opacity: 0; gap: 4px; display: flex; }
.tree-node:hover .tree-actions { opacity: 1; }
</style>
