<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { departmentApi } from '@/api/system.js'

// ─── State ────────────────────────────────────────────────────────────────────

const treeData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增部门')
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// Flat list for parent selector (avoid selecting self/descendants)
const flatDepts = ref([])

// ─── Form ─────────────────────────────────────────────────────────────────────

const form = reactive({
  id: null,
  parent_id: null,
  name: '',
  code: '',
  leader: '',
  phone: '',
  sort: 0,
  status: 1,
  description: ''
})

const formRules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function flattenTree(nodes, result = []) {
  for (const node of nodes) {
    result.push({ id: node.id, name: node.name })
    if (node.children?.length) {
      flattenTree(node.children, result)
    }
  }
  return result
}

// Get all descendant IDs to prevent circular parent selection
function getDescendantIds(id, nodes) {
  const ids = [id]
  const node = nodes.find((n) => n.id === id)
  if (node?.children) {
    for (const child of node.children) {
      ids.push(...getDescendantIds(child.id, flatDepts.value.map((d) => ({ ...d }))))
    }
  }
  return ids
}

const parentOptions = ref([])

function buildParentOptions(excludeId) {
  if (!excludeId) {
    parentOptions.value = flatDepts.value
    return
  }
  parentOptions.value = flatDepts.value.filter((d) => d.id !== excludeId)
}

// ─── Methods ──────────────────────────────────────────────────────────────────

async function fetchTree() {
  loading.value = true
  try {
    const res = await departmentApi.getList({ per_page: 500 })
    // Backend already returns a tree array directly in res.data
    if (Array.isArray(res.data)) {
      treeData.value = res.data
      flatDepts.value = flattenTree(res.data)
    } else {
      const flat = res.data?.list || res.data?.data || []
      flatDepts.value = flat.map(d => ({ id: d.id, name: d.name }))
      treeData.value = buildTree(flat)
    }
  } catch {
    //
  } finally {
    loading.value = false
  }
}

function buildTree(nodes, parentId = 0) {
  return nodes
    .filter(n => (n.parent_id ?? 0) === parentId)
    .map(n => ({ ...n, children: buildTree(nodes, n.id) }))
}

function handleAdd(parentRow) {
  isEdit.value = false
  dialogTitle.value = parentRow ? `在「${parentRow.name}」下新增部门` : '新增顶级部门'
  Object.assign(form, {
    id: null,
    parent_id: parentRow?.id || null,
    name: '', code: '', leader: '', phone: '',
    sort: 0, status: 1, description: ''
  })
  buildParentOptions(null)
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = `编辑部门 - ${row.name}`
  Object.assign(form, {
    id: row.id,
    parent_id: row.parent_id,
    name: row.name,
    code: row.code || '',
    leader: row.leader || '',
    phone: row.phone || '',
    sort: row.sort || 0,
    status: row.status,
    description: row.description || ''
  })
  buildParentOptions(row.id)
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await departmentApi.update(form.id, form)
        ElMessage.success('部门信息更新成功')
      } else {
        await departmentApi.create(form)
        ElMessage.success('部门创建成功')
      }
      dialogVisible.value = false
      fetchTree()
    } catch {
      //
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleDelete(row) {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('请先删除子部门')
    return
  }
  await ElMessageBox.confirm(
    `确定删除部门「${row.name}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  )
  await departmentApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchTree()
}

onMounted(fetchTree)
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <el-button :icon="'Refresh'" @click="fetchTree">刷新</el-button>
        </div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd(null)">新增顶级部门</el-button>
      </div>
      <div class="px-2">
        <el-table
          v-loading="loading"
          :data="treeData"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'has_children' }"
          default-expand-all
          style="width: 100%"
        >
          <el-table-column prop="name" label="部门名称" min-width="200" />
          <el-table-column prop="code" label="部门编码" width="120" />
          <el-table-column prop="leader" label="负责人" width="110" />
          <el-table-column prop="phone" label="联系电话" width="140" />
          <el-table-column prop="sort" label="排序" width="70" align="center" />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="success" text @click="handleAdd(row)">新增子部门</el-button>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="上级部门" prop="parent_id">
              <el-select
                v-model="form.parent_id"
                placeholder="不选则为顶级部门"
                clearable
                style="width: 100%"
              >
                <el-option label="顶级部门（无上级）" :value="null" />
                <el-option
                  v-for="dept in parentOptions"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门编码" prop="code">
              <el-input v-model="form.code" placeholder="如: HR（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="部门负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="部门联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="2"
                placeholder="备注信息（选填）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
