package com.qqchen.deploy.backend.system.service.impl;

import com.qqchen.deploy.backend.system.converter.DepartmentConverter;
import com.qqchen.deploy.backend.system.entity.Department;
import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.UniqueConstraintException;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.system.model.DepartmentDTO;
import com.qqchen.deploy.backend.system.model.query.DepartmentQuery;
import com.qqchen.deploy.backend.system.model.response.DepartmentResponse;
import com.qqchen.deploy.backend.system.repository.IDepartmentRepository;
import com.qqchen.deploy.backend.system.repository.IUserRepository;
import com.qqchen.deploy.backend.system.service.IDepartmentService;
import com.qqchen.deploy.backend.framework.annotation.ServiceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.*;

import static com.qqchen.deploy.backend.framework.annotation.ServiceType.Type.DATABASE;

@Slf4j
@Service
@ServiceType(DATABASE)
public class DepartmentServiceImpl extends BaseServiceImpl<Department, DepartmentDTO, DepartmentQuery, Long> implements IDepartmentService {

    @Resource
    private IDepartmentRepository departmentRepository;

    @Resource
    private IUserRepository userRepository;

    @Resource
    private DepartmentConverter departmentConverter;

    @Override
    protected void validateUniqueConstraints(DepartmentDTO dto) {
        // 检查部门编码唯一性
        if (departmentRepository.existsByCodeAndDeletedFalse(dto.getCode())) {
            throw new UniqueConstraintException(ResponseCode.DEPARTMENT_CODE_EXISTS, "code", dto.getCode());
        }

        // 检查部门名称唯一性
        if (departmentRepository.existsByNameAndDeletedFalse(dto.getName())) {
            throw new UniqueConstraintException(ResponseCode.DEPARTMENT_NAME_EXISTS, "name", dto.getName());
        }
    }

    @Override
    public List<DepartmentResponse> getTree() {
        List<Department> departments = departmentRepository.findByDeletedFalseOrderBySort();
        List<DepartmentDTO> dtoTree = buildTree(departments);
        return departmentConverter.toResponseList(dtoTree);
    }

    private List<DepartmentDTO> buildTree(List<Department> departments) {
        Map<Long, DepartmentDTO> dtoMap = new HashMap<>();
        List<DepartmentDTO> roots = new ArrayList<>();

        // 转换为DTO并建立映射
        departments.forEach(dept -> {
            DepartmentDTO dto = departmentConverter.toDto(dept);
            dto.setChildren(new ArrayList<>());
            dtoMap.put(dto.getId(), dto);
        });

        // 构建树形结构
        departments.forEach(dept -> {
            DepartmentDTO dto = dtoMap.get(dept.getId());
            if (dept.getParentId() == null || dept.getParentId() == 0) {
                roots.add(dto);
            } else {
                DepartmentDTO parent = dtoMap.get(dept.getParentId());
                if (parent != null) {
                    parent.getChildren().add(dto);
                }
            }
        });

        return roots;
    }

}