package com.zsc.edu.gateway.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.framework.DeptTreeUtil;
import com.zsc.edu.gateway.modules.system.dto.DeptDto;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.mapper.DeptMapper;
import com.zsc.edu.gateway.modules.system.repo.DeptRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import com.zsc.edu.gateway.modules.system.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.modules.system.vo.DeptTree;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 部门 服务实现类
 * </p>
 *
 * @author Yao
 * @since 2023-04-06
 */
@AllArgsConstructor
@Service
public class DeptServiceImpl extends ServiceImpl<DeptRepository, Dept> implements DeptService {

    private final DeptMapper mapper;
    private final DeptRepository repo;
    private final UserRepository userRepository;

    @Override
    public Dept create(DeptDto dto) {
        boolean existsByName = count(new LambdaQueryWrapper<Dept>().eq(Dept::getName, dto.getName())) > 0;
        if (existsByName) {
            throw new ConstraintException("name", dto.name, "部门已存在");
        }
        Dept dept = mapper.toEntity(dto);
        save(dept);
        return dept;
    }

    @Override
    public Boolean edit(DeptDto dto, Long id) {
        boolean isExists = count(new LambdaQueryWrapper<Dept>().ne(Dept::getId, id).eq(Dept::getName, dto.getName())) > 0;
        if (isExists) {
            throw new ConstraintException("name", dto.name, "同名部门已存在");
        }
        return update(dto.updateWrapper(id));
    }

    @Override
    public Boolean toggle(Long id) {
        Dept dept = getById(id);
        dept.setEnabled(!dept.getEnabled());
        return updateById(dept);
    }

    @Override
    public List<DeptTree> getDeptTree() {
        List<Dept> depots = repo.selectList(null);
        List<User> users = userRepository.selectList(null);
        Map<Long, List<User>> userMap = new HashMap<>();
        for (User user : users) {
            userMap.computeIfAbsent(user.getDeptId(), k -> new ArrayList<>()).add(user);
        }
        return DeptTreeUtil.buildDeptTree(depots, userMap);
    }

}
