package cn.fateverse.admin.service.impl;

import cn.fateverse.admin.mapper.DeptMapper;
import cn.fateverse.admin.service.DeptService;
import cn.fateverse.admin.vo.UserVo;
import cn.fateverse.common.core.entity.Dept;
import cn.fateverse.common.core.utils.AssertUtil;
import cn.fateverse.common.core.utils.LongUtils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Clay
 * @date 2022/11/2
 */
@Slf4j
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept>
        implements DeptService {


    @Override
    public List<Dept> list(String deptName, Integer state) {
        return this.lambdaQuery()
                .like(StrUtil.isNotBlank(deptName), Dept::getDeptName, deptName)
                .like(ObjectUtil.isNotNull(state), Dept::getState, state)
                .list();
    }

    @Override
    public List<Dept> searchExcludeTree(Long deptId) {
        return this.lambdaQuery()
                .ne(Dept::getDeptId, deptId)
                .ne(Dept::getParentId, deptId)
                .list();
    }


    @Override
    public List<Dept> searchByIds(List<Long> deptIds) {
        return this.lambdaQuery()
                .in(Dept::getDeptId, deptIds)
                .list();
    }

    @Override
    public void checkNameUnique(Dept dept) {
        Long deptId = LongUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        Dept info = this.lambdaQuery()
                .eq(Dept::getDeptName, dept.getDeptName())
                .eq(Dept::getParentId, deptId)
                .last("limit 1")
                .one();
        AssertUtil.isTrue(ObjectUtil.isNotNull(info) && !dept.getDeptId().equals(info.getDeptId()), "新增部门: {}'失败,部门名称以存在!", dept.getDeptName());
    }

    @Override
    public boolean hasChildById(Long deptId) {
        return this.lambdaQuery()
                .eq(Dept::getParentId, deptId)
                .eq(Dept::getDelFlag, 0)
                .exists();
    }


    @Override
    public List<Dept> selectChildrenById(Long deptId) {
        return this.lambdaQuery()
                .eq(Dept::getParentId, deptId)
                .list();
    }

    @Override
    public List<Dept> selectListByDeptParentId(Long deptId) {
        return this.lambdaQuery()
                .eq(Dept::getParentId, deptId)
                .list();
    }

}
