<template>
  <div class="departments-page">
    <a-card class="mb-4">
      <template #title>部门管理</template>
      <template #extra>
        <a-space>
          <a-button @click="showTree = !showTree">{{
            showTree ? "列表视图" : "树形视图"
          }}</a-button>
          <a-button
            v-permission="'department:create'"
            type="primary"
            @click="handleAdd"
            >新增部门</a-button
          >
        </a-space>
      </template>
    </a-card>

    <!-- 树形视图 -->
    <a-card v-if="showTree">
      <a-spin :spinning="treeLoading">
        <a-tree
          :tree-data="treeData"
          :field-names="{ children: 'children', title: 'name', key: 'id' }"
          default-expand-all
        >
          <template #title="{ name, _count }">
            <span>{{ name }} ({{ _count?.teachers || 0 }}人)</span>
          </template>
          <template #switcherIcon="{ expanded }">
            <span>{{ expanded ? "📂" : "📁" }}</span>
          </template>
        </a-tree>
      </a-spin>
    </a-card>

    <!-- 列表视图 -->
    <a-table
      v-else
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'parent'">
          <span>{{ record.parent?.name || "-" }}</span>
        </template>
        <template v-if="column.key === 'teacherCount'">
          <span>{{ record._count?.teachers || 0 }}人</span>
        </template>
        <template v-if="column.key === 'validState'">
          <a-tag :color="record.validState === 1 ? 'green' : 'red'">
            {{ record.validState === 1 ? "有效" : "失效" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button
              v-permission="'department:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-permission="'department:delete'"
              type="link"
              size="small"
              danger
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑部门弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="submitLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="父部门" name="parentId">
          <a-tree-select
            v-model:value="form.parentId"
            :tree-data="departmentTreeOptions"
            placeholder="请选择父部门（不选则为顶级部门）"
            allow-clear
            tree-default-expand-all
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="部门名称" name="name">
          <a-input
            v-model:value="form.name"
            placeholder="请输入部门名称"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="部门编码" name="code">
          <a-input
            v-model:value="form.code"
            placeholder="请输入部门编码"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number
            v-model:value="form.sort"
            placeholder="请输入排序值"
            :min="0"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="部门描述" name="description">
          <a-textarea
            v-model:value="form.description"
            placeholder="请输入部门描述"
            :rows="3"
            :maxlength="500"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, computed } from "vue"
import { message, Modal } from "ant-design-vue"
import type { TableColumnsType, FormInstance } from "ant-design-vue"
import {
  departmentsApi,
  type Department,
  type CreateDepartmentForm,
  type UpdateDepartmentForm,
} from "@/api/departments"
import { useListRequest } from "@/composables/useListRequest"
import { useAuthStore } from "@/stores/auth"

const authStore = useAuthStore()

const submitLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref("新增部门")
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)
const showTree = ref(false)
const treeLoading = ref(false)
const treeData = ref<Department[]>([])

const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<Department>({
  requestFn: departmentsApi.getList,
  errorMessage: "获取部门列表失败",
})

const form = reactive<CreateDepartmentForm>({
  name: "",
  code: "",
  parentId: undefined,
  sort: 0,
  description: "",
})

const rules = {
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  code: [
    { required: true, message: "请输入部门编码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: "编码只能包含字母、数字和下划线，且必须以字母开头",
      trigger: "blur",
    },
  ],
}

const columns: TableColumnsType = [
  { title: "ID", dataIndex: "id", key: "id", width: 80 },
  { title: "部门名称", dataIndex: "name", key: "name" },
  { title: "部门编码", dataIndex: "code", key: "code" },
  { title: "父部门", key: "parent", width: 150 },
  { title: "教师数量", key: "teacherCount", width: 100 },
  { title: "排序", dataIndex: "sort", key: "sort", width: 80 },
  { title: "状态", dataIndex: "validState", key: "validState", width: 80 },
  { title: "操作", key: "action", width: 150, fixed: "right" },
]

// 构建部门树选项（用于下拉选择）
const departmentTreeOptions = computed(() => {
  const buildOptions = (depts: Department[], excludeId?: number): any[] => {
    return depts
      .filter((dept) => dept.id !== excludeId)
      .map((dept) => ({
        title: dept.name,
        value: dept.id,
        children: dept.children
          ? buildOptions(dept.children, excludeId)
          : undefined,
      }))
  }
  return buildOptions(treeData.value, editingId.value || undefined)
})

const fetchTree = async () => {
  treeLoading.value = true
  try {
    treeData.value = await departmentsApi.getTree()
  } catch (error) {
    message.error("获取部门树失败")
  } finally {
    treeLoading.value = false
  }
}

const handleAdd = () => {
  if (!authStore.hasPermission("department:create")) {
    message.error("您没有创建部门的权限")
    return
  }

  modalTitle.value = "新增部门"
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ""
    form.code = ""
    form.parentId = undefined
    form.sort = 0
    form.description = ""
  })
}

const handleEdit = async (record: Department) => {
  modalTitle.value = "编辑部门"
  editingId.value = record.id
  modalVisible.value = true

  try {
    const detail = await departmentsApi.getDetail(record.id)
    form.name = detail.name
    form.code = detail.code
    form.parentId = detail.parentId || undefined
    form.sort = detail.sort
    form.description = detail.description || ""
  } catch (error) {
    message.error("获取部门详情失败")
    modalVisible.value = false
  }
}

const handleDelete = (record: Department) => {
  if (!authStore.hasPermission("department:delete")) {
    message.error("您没有删除部门的权限")
    return
  }

  Modal.confirm({
    title: "确认删除",
    content: `确定要删除部门 "${record.name}" 吗？删除前需先转移或删除该部门下的所有教师和子部门。`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await departmentsApi.delete(record.id)
        message.success("删除成功")
        refreshList()
        if (showTree.value) {
          fetchTree()
        }
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || "删除失败"
        message.error(errorMessage)
      }
    },
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    const data: CreateDepartmentForm | UpdateDepartmentForm = {
      name: form.name,
      code: form.code,
      parentId: form.parentId || undefined,
      sort: form.sort,
      description: form.description || undefined,
    }

    if (editingId.value) {
      await departmentsApi.update(editingId.value, data as UpdateDepartmentForm)
      message.success("编辑成功")
    } else {
      await departmentsApi.create(data)
      message.success("新增成功")
    }

    modalVisible.value = false
    refreshList()
    if (showTree.value) {
      fetchTree()
    }
  } catch (error: any) {
    if (error?.errorFields) {
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (editingId.value ? "编辑失败" : "新增失败")
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

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

<style scoped></style>
