<template>
  <div class="departments-view">
    <a-page-header
      title="部门管理"
      sub-title="创建、编辑部门并管理技能与知识库绑定"
      class="departments-view__header"
    >
      <template #extra>
        <a-button type="primary" @click="openCreate">
          <PlusOutlined /> 新建部门
        </a-button>
      </template>
    </a-page-header>

    <a-card class="departments-view__card">
      <a-table
        :columns="columns"
        :data-source="departments"
        :row-key="(record: IDepartment) => record.id"
        :loading="loading"
        :pagination="false"
        size="middle"
      >
        <template #bodyCell="{ column, record }: { column: TableColumnType<IDepartment>; record: IDepartment }">
          <template v-if="column.key === 'name'">
            <strong>{{ record.name }}</strong>
          </template>
          <template v-else-if="column.key === 'is_active'">
            <a-tag :color="record.is_active ? 'green' : 'default'">
              {{ record.is_active ? '启用' : '停用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'created_at'">
            {{ formatTime(record.created_at) }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <a-space :size="4">
              <a-button type="link" size="small" @click="openEdit(record)">编辑</a-button>
              <a-button type="link" size="small" @click="toggleActive(record)">
                {{ record.is_active ? '停用' : '启用' }}
              </a-button>
              <a-button type="link" size="small" @click="openBindings(record)">绑定</a-button>
              <a-popconfirm
                title="确认删除该部门？删除后不可恢复。"
                ok-text="删除"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger size="small">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- Create / Edit modal -->
    <a-modal
      v-model:open="formOpen"
      :title="editingId ? '编辑部门' : '新建部门'"
      :confirm-loading="submitting"
      ok-text="保存"
      cancel-text="取消"
      @ok="handleSubmit"
    >
      <a-form layout="vertical">
        <a-form-item label="部门名称" required>
          <a-input v-model:value="form.name" placeholder="输入部门名称" :max-length="64" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="form.description"
            placeholder="部门描述（可选）"
            :rows="3"
            :max-length="500"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- Bindings drawer -->
    <a-drawer
      v-model:open="bindingsOpen"
      :title="`绑定管理 — ${bindingsDept?.name ?? ''}`"
      width="520"
      placement="right"
    >
      <a-spin :spinning="bindingsLoading">
        <div class="departments-view__bindings">
          <a-card title="技能绑定" size="small" class="departments-view__binding-card">
            <template #extra>
              <a-input-search
                v-model:value="newSkillName"
                placeholder="输入 skill 名称"
                enter-button="添加"
                size="small"
                style="width: 220px"
                @search="handleBindSkill"
              />
            </template>
            <a-empty v-if="deptSkills.length === 0" description="暂无绑定技能" :image="simpleImage" />
            <a-list v-else size="small" :data-source="deptSkills" :bordered="false">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-space :size="8" style="width: 100%" justify="space-between">
                    <span><ThunderboltOutlined /> {{ item }}</span>
                    <a-button type="link" danger size="small" @click="handleUnbindSkill(item)">移除</a-button>
                  </a-space>
                </a-list-item>
              </template>
            </a-list>
          </a-card>

          <a-card title="知识库绑定" size="small" class="departments-view__binding-card">
            <template #extra>
              <a-input-search
                v-model:value="newKbSourceId"
                placeholder="输入 KB source ID"
                enter-button="添加"
                size="small"
                style="width: 220px"
                @search="handleBindKb"
              />
            </template>
            <a-empty v-if="deptKbs.length === 0" description="暂无绑定知识库" :image="simpleImage" />
            <a-list v-else size="small" :data-source="deptKbs" :bordered="false">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-space :size="8" style="width: 100%" justify="space-between">
                    <span><BookOutlined /> {{ item }}</span>
                    <a-button type="link" danger size="small" @click="handleUnbindKb(item)">移除</a-button>
                  </a-space>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </div>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
/**
 * Department management view.
 *
 * - Table listing departments with create/edit/disable/enable/delete.
 * - Drawer for managing skill and KB source bindings per department.
 */
import { ref, reactive, onMounted } from 'vue'
import { message, Empty } from 'ant-design-vue'
import type { TableColumnType } from 'ant-design-vue'
import {
  PlusOutlined,
  ThunderboltOutlined,
  BookOutlined,
} from '@ant-design/icons-vue'
import { adminApi, type IDepartment } from '@/api/admin'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const departments = ref<IDepartment[]>([])
const loading = ref(false)

const columns: TableColumnType<IDepartment>[] = [
  { title: '名称', key: 'name', dataIndex: 'name', width: 200 },
  { title: '描述', key: 'description', dataIndex: 'description', ellipsis: true },
  { title: '状态', key: 'is_active', width: 100 },
  { title: '创建时间', key: 'created_at', width: 180 },
  { title: '操作', key: 'actions', width: 280 },
]

// --- Create / Edit ---
const formOpen = ref(false)
const editingId = ref<string | null>(null)
const submitting = ref(false)
const form = reactive({ name: '', description: '' })

function openCreate(): void {
  editingId.value = null
  form.name = ''
  form.description = ''
  formOpen.value = true
}

function openEdit(record: IDepartment): void {
  editingId.value = record.id
  form.name = record.name
  form.description = record.description
  formOpen.value = true
}

async function handleSubmit(): Promise<void> {
  if (!form.name.trim()) {
    message.warning('请输入部门名称')
    return
  }
  submitting.value = true
  try {
    if (editingId.value) {
      await adminApi.updateDepartment(editingId.value, {
        name: form.name.trim(),
        description: form.description,
      })
      message.success('部门已更新')
    } else {
      await adminApi.createDepartment(form.name.trim(), form.description)
      message.success('部门已创建')
    }
    formOpen.value = false
    await loadDepartments()
  } catch (err) {
    message.error(extractMessage(err, '保存部门失败'))
  } finally {
    submitting.value = false
  }
}

async function toggleActive(record: IDepartment): Promise<void> {
  try {
    if (record.is_active) {
      await adminApi.disableDepartment(record.id)
      message.success('部门已停用')
    } else {
      await adminApi.enableDepartment(record.id)
      message.success('部门已启用')
    }
    await loadDepartments()
  } catch (err) {
    message.error(extractMessage(err, '操作失败'))
  }
}

async function handleDelete(record: IDepartment): Promise<void> {
  try {
    await adminApi.deleteDepartment(record.id)
    message.success('部门已删除')
    await loadDepartments()
  } catch (err) {
    message.error(extractMessage(err, '删除部门失败'))
  }
}

// --- Bindings ---
const bindingsOpen = ref(false)
const bindingsLoading = ref(false)
const bindingsDept = ref<IDepartment | null>(null)
const deptSkills = ref<string[]>([])
const deptKbs = ref<string[]>([])
const newSkillName = ref('')
const newKbSourceId = ref('')

async function openBindings(record: IDepartment): Promise<void> {
  bindingsDept.value = record
  bindingsOpen.value = true
  newSkillName.value = ''
  newKbSourceId.value = ''
  await loadBindings(record.id)
}

async function loadBindings(deptId: string): Promise<void> {
  bindingsLoading.value = true
  try {
    const [skills, kbs] = await Promise.all([
      adminApi.listDepartmentSkills(deptId),
      adminApi.listDepartmentKb(deptId),
    ])
    deptSkills.value = skills
    deptKbs.value = kbs
  } catch (err) {
    message.error(extractMessage(err, '加载绑定信息失败'))
  } finally {
    bindingsLoading.value = false
  }
}

async function handleBindSkill(): Promise<void> {
  if (!bindingsDept.value || !newSkillName.value.trim()) return
  try {
    await adminApi.bindSkill(bindingsDept.value.id, newSkillName.value.trim())
    message.success('技能已绑定')
    newSkillName.value = ''
    await loadBindings(bindingsDept.value.id)
  } catch (err) {
    message.error(extractMessage(err, '绑定技能失败'))
  }
}

async function handleUnbindSkill(skillName: string): Promise<void> {
  if (!bindingsDept.value) return
  try {
    await adminApi.unbindSkill(bindingsDept.value.id, skillName)
    message.success('技能已解绑')
    await loadBindings(bindingsDept.value.id)
  } catch (err) {
    message.error(extractMessage(err, '解绑技能失败'))
  }
}

async function handleBindKb(): Promise<void> {
  if (!bindingsDept.value || !newKbSourceId.value.trim()) return
  try {
    await adminApi.bindKb(bindingsDept.value.id, newKbSourceId.value.trim())
    message.success('知识库已绑定')
    newKbSourceId.value = ''
    await loadBindings(bindingsDept.value.id)
  } catch (err) {
    message.error(extractMessage(err, '绑定知识库失败'))
  }
}

async function handleUnbindKb(sourceId: string): Promise<void> {
  if (!bindingsDept.value) return
  try {
    await adminApi.unbindKb(bindingsDept.value.id, sourceId)
    message.success('知识库已解绑')
    await loadBindings(bindingsDept.value.id)
  } catch (err) {
    message.error(extractMessage(err, '解绑知识库失败'))
  }
}

// --- Helpers ---
function formatTime(iso: string): string {
  if (!iso) return '—'
  try {
    return new Date(iso).toLocaleString('zh-CN', { hour12: false })
  } catch {
    return iso
  }
}

function extractMessage(err: unknown, fallback: string): string {
  if (err && typeof err === 'object') {
    const obj = err as { detail?: unknown; message?: unknown }
    if (typeof obj.detail === 'string' && obj.detail) return obj.detail
    if (typeof obj.message === 'string' && obj.message) return obj.message
  }
  return fallback
}

async function loadDepartments(): Promise<void> {
  loading.value = true
  try {
    departments.value = await adminApi.listDepartments()
  } catch (err) {
    message.error(extractMessage(err, '加载部门列表失败'))
  } finally {
    loading.value = false
  }
}

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

<style scoped>
.departments-view {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.departments-view__header {
  margin-bottom: 16px;
}

.departments-view__card {
  margin-top: 8px;
}

.departments-view__bindings {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.departments-view__binding-card {
  width: 100%;
}
</style>
