<template>
  <div class="department-management">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="部门管理" :bordered="false">
          <div class="toolbar">
            <a-button type="primary" @click="showAddModal(null)">添加部门</a-button>
          </div>
          <a-spin :spinning="loading">
            <a-tree
              v-if="treeData.length > 0"
              :tree-data="treeData"
              show-line
              :default-expand-all="true"
              :selected-keys.sync="selectedKeys"
            >
              <template #title="{ dataRef }">
                <div class="tree-node">
                  <span>{{ dataRef.departmentName }}</span>
                  <div class="node-actions">
                    <a-button
                      size="small"
                      type="link"
                      @click="showAddModal(dataRef)"
                    >
                      添加子部门
                    </a-button>
                    <a-button
                      size="small"
                      type="link"
                      @click="showEditModal(dataRef)"
                    >
                      编辑
                    </a-button>
                    <a-button
                      size="small"
                      type="link"
                      danger
                      @click="confirmDelete(dataRef)"
                    >
                      删除
                    </a-button>
                  </div>
                </div>
              </template>
            </a-tree>
            <a-empty v-else description="暂无数据" />
          </a-spin>
        </a-card>
      </a-col>
    </a-row>

    <!-- 添加/编辑部门弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      :confirm-loading="confirmLoading"
    >
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="部门名称" required>
          <a-input v-model:value="formState.departmentName" placeholder="请输入部门名称" />
        </a-form-item>
        <a-form-item label="区域">
          <a-input v-model:value="formState.area" placeholder="请输入区域" />
        </a-form-item>
        <a-form-item label="负责人">
          <a-input v-model:value="formState.managerName" placeholder="请输入负责人姓名" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import axios from 'axios';
import { apiRequestGet } from '@/utils/api';
import { localStg } from '@/utils/storage';

// 部门树数据
const treeData = ref([]);
// 加载状态
const loading = ref(false);
// 弹窗相关
const modalVisible = ref(false);
const modalTitle = ref('添加部门');
const confirmLoading = ref(false);
const formState = ref({
  departmentName: '',
  area: '',
  managerName: '',
  departmentId: null,
  parentId: null,
});
// 当前操作的部门
const currentDept = ref(null);
// 选中的节点
const selectedKeys = ref([]);

// 获取部门数据
const fetchDepartments = async () => {
  try {
    loading.value = true; // 开始加载
    const response = await apiRequestGet('/department/allDepartment');

    if (response.data.success) {
      // 过滤重复数据并构建树结构
      const deptMap = new Map();
      response.data.data.forEach((dept) => {
        if (!deptMap.has(dept.departmentId)) {
          deptMap.set(dept.departmentId, {
            key: dept.departmentId,
            departmentName: dept.departmentName,
            area: dept.area,
            manager: dept.manager,
            children: dept.children.map(child => ({
              key: child.departmentId,
              departmentName: child.departmentName,
              area: child.area,
              manager: child.manager,
              children: child.children || [],
            })),
          });
        }
      });
      treeData.value = Array.from(deptMap.values()).filter(dept => dept.key === 1); // 示例中以departmentId=1作为根节点
    } else {
      message.error(response.data.errorMsg || '获取部门数据失败');
    }
  } catch (error) {
    message.error('请求失败: ' + error.message);
  } finally {
    loading.value = false; // 结束加载
  }
};

// 显示添加部门弹窗
const showAddModal = (dept) => {
  modalTitle.value = dept ? `添加${dept.departmentName}的子部门` : '添加部门';
  modalVisible.value = true;
  formState.value = {
    departmentName: '',
    area: '',
    managerName: '',
    departmentId: null,
    parentId: dept ? dept.key : null,
  };
  currentDept.value = null;
};

// 显示编辑部门弹窗
const showEditModal = (dept) => {
  modalTitle.value = '编辑部门';
  modalVisible.value = true;
  formState.value = {
    departmentName: dept.departmentName,
    area: dept.area || '',
    managerName: dept.manager ? dept.manager.name : '',
    departmentId: dept.key,
    parentId: null,
  };
  currentDept.value = dept;
};

// 提交表单
const handleSubmit = async () => {
  if (!formState.value.departmentName) {
    message.error('部门名称不能为空');
    return;
  }
  confirmLoading.value = true;
  try {
    const payload = {
      departmentName: formState.value.departmentName,
      area: formState.value.area,
      manager: {
        name: formState.value.managerName,
      },
      parentId: formState.value.parentId,
    };
    if (formState.value.departmentId) {
      await axios.put(`http://localhost:8080/api/departments/${formState.value.departmentId}`, payload);
      message.success('编辑成功');
    } else {
      await axios.post('http://localhost:8080/api/departments', payload);
      message.success('添加成功');
    }
    modalVisible.value = false;
    fetchDepartments(); // 刷新数据
  } catch (error) {
    message.error('操作失败: ' + error.message);
  } finally {
    confirmLoading.value = false;
  }
};

// 删除部门
const confirmDelete = (dept) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除部门 ${dept.departmentName} 吗？`,
    async onOk() {
      try {
        loading.value = true; // 开始加载
        await axios.delete(`http://localhost:8080/api/departments/${dept.key}`);
        message.success('删除成功');
        fetchDepartments(); // 刷新数据
      } catch (error) {
        message.error('删除失败: ' + error.message);
      } finally {
        loading.value = false; // 结束加载
      }
    },
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchDepartments();
});
</script>

<style scoped>
.department-management {
  padding: 16px;
}

.toolbar {
  margin-bottom: 16px;
  text-align: right;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.node-actions {
  display: none;
}

.tree-node:hover .node-actions {
  display: block;
}
</style>