package com.tuoheng.admin.service.user.query;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.Dept;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.code.user.QueryUserListByDeptIdCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  根据部门id查询用户列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-08
 */
@Slf4j
@Service
public class QueryUserListByDeptIdService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 获取部门树形列表
     *
     * @return
     */
    public JsonResult getListByDeptId(String deptId) {
        log.info("进入根据部门id查询用户列表业务");
        JsonResult result = this.check(deptId);
        if (0 != result.getCode()) {
            log.info("根据根据部门id查询用户列表业业务：校验失败：{}", result.getMsg());
            return result;
        }
        String tenantId = CurrentUserUtil.getTenantId();
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                                .eq(User::getTenantId, tenantId)
                                .eq(User::getDeptId, deptId)
                                .ne(User::getRoleId, DataPermissionEnum.ALL.getCode())
                                .eq(User::getMark, 1));

        if (CollectionUtil.isEmpty(userList)) {
            log.info("根据部门id查询用户列表业：获取用户列表为空");
        }
        return JsonResult.success(userList);
    }

    /**
     * 检查参数
     *
     * @param deptId
     * @return
     */
    private JsonResult check(String deptId) {
        // 判断id是否为空
        if (StringUtils.isEmpty(deptId)) {
            return JsonResult.error(QueryUserListByDeptIdCodeEnum.DEPT_ID_IS_NULL.getCode(), QueryUserListByDeptIdCodeEnum.DEPT_ID_IS_NULL.getMsg());
        }

        // 判断部门是否存在
        Integer count = deptMapper.selectCount(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getId, deptId)
                .eq(Dept::getMark, 1));
        if (count <= 0) {
            return JsonResult.error(QueryUserListByDeptIdCodeEnum.DEPT_IS_NOT_EXIST.getCode(), QueryUserListByDeptIdCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success();
    }
}
