package com.example.demo.service;

import com.example.demo.model.Department;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 部门管理服务。
 * <p>基于内存数据存储，提供部门的新增、编辑、删除、查询及树形结构维护。</p>
 */
@Service
public class DepartmentService {

    private final Map<Long, Department> deptStore = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    public DepartmentService() {
        initMockData();
    }

    private void initMockData() {
        save(new Department(1L, "总公司", 0L, 1, "总经理", 1));
        save(new Department(2L, "技术部", 1L, 1, "李四", 1));
        save(new Department(3L, "市场部", 1L, 2, "王五", 1));
        save(new Department(4L, "研发组", 2L, 1, "赵六", 1));
        idGenerator.set(5);
    }

    /**
     * 新增部门。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param dept 部门信息
     * @return 已保存的部门
     */
    public Department save(Department dept) {
        if (dept.getDeptId() == null) {
            dept.setDeptId(idGenerator.getAndIncrement());
        }
        if (dept.getStatus() == null) {
            dept.setStatus(1);
        }
        deptStore.put(dept.getDeptId(), dept);
        return dept;
    }

    /**
     * 编辑部门信息。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param dept 包含更新信息的部门对象
     * @return 更新后的部门，若ID不存在返回 null
     */
    public Department update(Department dept) {
        Department existing = deptStore.get(dept.getDeptId());
        if (existing == null) {
            return null;
        }
        if (dept.getDeptName() != null) existing.setDeptName(dept.getDeptName());
        if (dept.getParentDeptId() != null) existing.setParentDeptId(dept.getParentDeptId());
        if (dept.getSortOrder() != null) existing.setSortOrder(dept.getSortOrder());
        if (dept.getLeader() != null) existing.setLeader(dept.getLeader());
        if (dept.getStatus() != null) existing.setStatus(dept.getStatus());
        return existing;
    }

    /**
     * 删除部门。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param deptId 部门ID
     * @return 是否删除成功
     */
    public boolean deleteById(Long deptId) {
        if (hasChildren(deptId)) {
            return false;
        }
        return deptStore.remove(deptId) != null;
    }

    private boolean hasChildren(Long deptId) {
        return deptStore.values().stream().anyMatch(d -> d.getParentDeptId().equals(deptId));
    }

    /**
     * 查询部门树形结构。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @return 树形部门列表（顶层节点）
     */
    public List<Department> tree() {
        List<Department> all = new ArrayList<>(deptStore.values());
        Map<Long, List<Department>> parentMap = all.stream()
                .collect(Collectors.groupingBy(d -> d.getParentDeptId() != null ? d.getParentDeptId() : 0L));
        all.forEach(d -> d.setChildren(parentMap.getOrDefault(d.getDeptId(), Collections.emptyList())));
        return parentMap.getOrDefault(0L, Collections.emptyList()).stream()
                .sorted(Comparator.comparingInt(Department::getSortOrder))
                .collect(Collectors.toList());
    }

    /**
     * 根据ID查询部门。
     *
     * @param deptId 部门ID
     * @return 部门对象
     */
    public Department findById(Long deptId) {
        return deptStore.get(deptId);
    }
}
