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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.conver.UserConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.code.user.QueryUserPageListCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.mapper.RoleMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.request.user.QueryUserPageListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.user.UserPageListVo;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 查询用户分页列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-08
 */
@Slf4j
@Service
public class QueryUserPageListService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 获取部门树形列表
     *
     * @return
     */
    public JsonResult getPageList(QueryUserPageListRequest request) {
        log.info("进入查询用户分页列表业务");
        User user = CurrentUserUtil.getUserInfo();
        JsonResult result = this.check(user);
        if (0 != result.getCode()) {
            log.info("查询用户分页列表业务：校验失败：{}", result.getMsg());
            return result;
        }

        String tenantId = user.getTenantId();
        request.setTenantId(tenantId);

        List<String> deptIdList = this.getDeptIdList(user);
        request.setDeptIdList(deptIdList);

        // 查询分页数据
        IPage<User> page = new Page<>(request.getPage(), request.getLimit());
        IPage<User> pageData = userMapper.selectPageList(page, request);

        if (null == pageData || pageData.getTotal() == 0) {
            log.info("获取任务分页列表为空");
            return JsonResult.success(pageData);
        }
        //不查当前用户
        List<User> collect = pageData.getRecords().stream().filter(t -> !t.getUsername().equals(CurrentUserUtil.getUserInfo().getUsername())).collect(Collectors.toList());

        // 构造返回结果对象
        List<UserPageListVo> userPageListVoList = this.buildUserPageListVoList(collect);

        // 重写返回结果对象
        IPage<UserPageListVo> userPageListVoPageData = new Page<>();
        userPageListVoPageData.setPages(pageData.getPages());
        userPageListVoPageData.setCurrent(pageData.getCurrent());
        userPageListVoPageData.setSize(pageData.getSize());
        userPageListVoPageData.setRecords(userPageListVoList);
        if (pageData.getTotal() == collect.size()) {
            userPageListVoPageData.setTotal(pageData.getTotal());
        } else {
            userPageListVoPageData.setTotal(pageData.getTotal() - 1);
        }
        return JsonResult.success(userPageListVoPageData);
    }

    /**
     * 检查参数
     *
     * @param user
     * @return
     */
    private JsonResult check(User user) {
        if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            return JsonResult.error(QueryUserPageListCodeEnum.ORDINARY_USERS_NO_PERMISSION.getCode(), QueryUserPageListCodeEnum.ORDINARY_USERS_NO_PERMISSION.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 获取部门Id的查询范围
     * 1）、超级管理员查全部
     * 2）、部门管理员：查本部门及子部门用户
     * 3）、普通用户：没有权限
     *
     * @param user
     * @return
     */
    private List<String> getDeptIdList(User user) {
        List<String> deptIdList;
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            return null;
        } else {
            deptIdList = deptMapper.selectAllChildListById(user.getDeptId());
            return deptIdList;
        }
    }

    /**
     * 1）、查找问题类型字段
     * 2）、拼接缩略图路径
     *
     * @param userList
     * @return
     */
    private List<UserPageListVo> buildUserPageListVoList(List<User> userList) {
        Map<String, Dept> deptMap = this.getDeptMap(userList);
        Map<Integer, Role> roleMap = this.getRoletMap(userList);
        List<UserPageListVo> userPageListVoList = UserConverMapper.INSTANCE.fromUserListToUserPageVoList(userList);
        Dept dept;
        Role role;
        for (UserPageListVo userPageListVo : userPageListVoList) {
            if (ObjectUtil.isNotNull(deptMap)) {
                dept = deptMap.get(userPageListVo.getDeptId());
                if (null != dept) {
                    userPageListVo.setDeptName(dept.getName());
                }
            }
            if (ObjectUtil.isNotNull(roleMap)) {
                role = roleMap.get(userPageListVo.getRoleId());
                if (null != role) {
                    userPageListVo.setRoleName(role.getRoleName());
                }
            }
        }
        return userPageListVoList;
    }

    /**
     * 获取部门列表，放到map，减少循环次数
     *
     * @param userList
     * @return
     */
    private Map<String, Dept> getDeptMap(List<User> userList) {
        if (CollectionUtil.isEmpty(userList)) {
            return null;
        }
        List<String> deptIdList = userList.stream().map(o -> o.getDeptId()).collect(Collectors.toList());
        List<Dept> deptList = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                .in(Dept::getId, deptIdList)
                .eq(Dept::getMark, 1));
        if (CollectionUtil.isEmpty(deptList)) {
            return null;
        }
        Map<String, Dept> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Function.identity()));
        return deptMap;
    }

    /**
     * 获取角色列表，放到map，减少循环次数
     *
     * @param userList
     * @return
     */
    private Map<Integer, Role> getRoletMap(List<User> userList) {
        if (CollectionUtil.isEmpty(userList)) {
            return null;
        }
        List<Integer> roleIdList = userList.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        List<Role> roleList = roleMapper.selectList(new LambdaQueryWrapper<Role>()
                .in(Role::getId, roleIdList)
                .eq(Role::getMark, 1));
        if (CollectionUtil.isEmpty(roleList)) {
            return null;
        }
        Map<Integer, Role> roleMap = roleList.stream().collect(Collectors.toMap(Role::getId, Function.identity()));
        return roleMap;
    }
}
