package com.zzsn.knowbase.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzsn.knowbase.entity.*;
import com.zzsn.knowbase.mapper.KbAuthorizedUserMapper;
import com.zzsn.knowbase.service.*;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.AddUserPermissKnowsVo;
import com.zzsn.knowbase.vo.Result;
import com.zzsn.knowbase.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author obcy
 * @since 2024-01-04
 */
@Service
public class KbAuthorizedUserServiceImpl extends ServiceImpl<KbAuthorizedUserMapper, KbAuthorizedUser> implements KbAuthorizedUserService {

    @Autowired
    KbUserRoleMapService kbUserRoleMapService;
    @Autowired
    KbAuthorizedUserMapper authorizedUserMapper;
    @Autowired
    KbRoleService roleService;
    @Autowired
    KbPermissionsService permissionsService;
    @Autowired
    KbRolePermissionMapService rolePermissionMapService;
    @Autowired
    KbAuthuserKnowledgeprojectMapService authuserKnowledgeprojectMapService;
    @Autowired
    KbKnowledgeProjectService knowledgeProjectService;
    @Autowired
    KbAuthuserKnowMapService kbAuthuserKnowMapService;

    /**
     * 校验第三方用户接口地址
     */
    @Value("${know.thirdpartyurl.checkuserurl:}")
    private String checkuserurl;

    /**
     * 获取第三方用户接口
     */
    @Value("${know.thirdpartyurl.getusersurl:}")
    private String getusersurl;

    @Override
    @Transactional
    public Result<?> addOne(KbAuthorizedUser authorizedUser) {
        /**保存授权用户*/
        authorizedUser.setStatus("0");
        authorizedUser.setCreateTime(new Date());
        super.save(authorizedUser);


        /**插入用户知识库权限关系表*/
        if (StringUtils.isNotBlank(authorizedUser.getKnowledgeProjectId())){
            KbAuthuserKnowledgeprojectMap kbAuthuserKnowledgeprojectMap = new KbAuthuserKnowledgeprojectMap();
            kbAuthuserKnowledgeprojectMap.setAuthUserId(authorizedUser.getId());
            kbAuthuserKnowledgeprojectMap.setKnowledgeProjectId(authorizedUser.getKnowledgeProjectId());
            authuserKnowledgeprojectMapService.save(kbAuthuserKnowledgeprojectMap);
            /**插入用户角色关系表*/
            if (StringUtils.isNotBlank(authorizedUser.getRoleId())){
                String roleId = authorizedUser.getRoleId();
                List<String> list = Arrays.asList(roleId.split(","));
                List<KbUserRoleMap> maps = new ArrayList<>();
                list.forEach(e->{
                    KbUserRoleMap kbUserRoleMap = new KbUserRoleMap();
                    kbUserRoleMap.setUserId(authorizedUser.getId());
                    kbUserRoleMap.setRoleId(e);
                    maps.add(kbUserRoleMap);
                });
                kbUserRoleMapService.saveBatch(maps);
            }
        }
        return  Result.OK();
    }

    @Override
    @Transactional
    public Result<?> add(List<KbAuthorizedUser>   authorizedUsers) {

        if (CollectionUtil.isEmpty(authorizedUsers)){
            return  Result.error("请选择要授权的用户");
        }

        Map<String, List<KbAuthorizedUser>> reqUsersMap = authorizedUsers.stream().collect(Collectors.groupingBy(KbAuthorizedUser::getUserId));
        //授权用户表中已存在的用户
        List<KbAuthorizedUser> kbAuthorizedUsers = authorizedUserMapper.selectList(Wrappers.<KbAuthorizedUser>lambdaQuery()
                .in(KbAuthorizedUser::getUserId, authorizedUsers.stream().map(KbAuthorizedUser::getUserId).collect(Collectors.toList())));

        List<String> collect = kbAuthorizedUsers.stream().map(KbAuthorizedUser::getUserId).collect(Collectors.toList());


        //已经授权过的用户在用户表里不用重复插入
        List<KbAuthorizedUser> notExist = authorizedUsers.stream().filter(f -> !collect.contains(f.getUserId())).collect(Collectors.toList());

        authorizedUsers = new ArrayList<>();
        authorizedUsers.addAll(notExist);

        if (CollectionUtil.isNotEmpty(authorizedUsers)) {
            authorizedUsers.forEach(e-> {
                /**保存授权用户*/
                e.setStatus("0");
                e.setCreateBy(SpringContextUtils.getUserInfo().getUsername());
                e.setCreateTime(new Date());
            });
            super.saveBatch(authorizedUsers);
        }
        if (CollectionUtil.isNotEmpty(kbAuthorizedUsers)){
            kbAuthorizedUsers.forEach(e->{
                e.setRoleId(reqUsersMap.get(e.getUserId()).get(0).getRoleId());
                e.setKnowledgeProjectId(reqUsersMap.get(e.getUserId()).get(0).getKnowledgeProjectId());
                e.setCreateBy(SpringContextUtils.getUserInfo().getUsername());
            });
            authorizedUsers.addAll(kbAuthorizedUsers);
        }

        //获取这一批下面的其中一个用户，获取这批用户关联的知识库分类
        KbAuthorizedUser kbAuthorizedUser = authorizedUsers.get(0);
        if (!"0".equals(kbAuthorizedUser.getKnowledgeProjectId())) {

            //查询授权节点和其子节点，一起授权
            List<KbKnowledgeProject> projectTypes = knowledgeProjectService.list(Wrappers.<KbKnowledgeProject>lambdaQuery().like(KbKnowledgeProject::getFullPath, kbAuthorizedUser.getKnowledgeProjectId()));

            //去除已经受过权的节点
            List<String> thisBanth = authorizedUsers.stream().map(KbAuthorizedUser::getId).collect(Collectors.toList());
            List<KbAuthuserKnowledgeprojectMap> list1 = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery().in(KbAuthuserKnowledgeprojectMap::getAuthUserId, thisBanth));
            Map<String, List<KbAuthuserKnowledgeprojectMap>> collect1Map = list1.stream().collect(Collectors.groupingBy(KbAuthuserKnowledgeprojectMap::getAuthUserId));


            List<KbUserRoleMap> maps = new ArrayList<>();
            List<KbAuthuserKnowledgeprojectMap> userknows = new ArrayList<>();

            authorizedUsers.forEach(authorizedUser->{

                List<KbKnowledgeProject> projectTypesFi = new ArrayList<>();
                //此用户已经受过权限的知识库分类
                List<KbAuthuserKnowledgeprojectMap> kbAuthuserKnowledgeprojectMaps = collect1Map.get(authorizedUser.getId());

                if (CollectionUtil.isNotEmpty(kbAuthuserKnowledgeprojectMaps)){
                    List<String> collect1 = kbAuthuserKnowledgeprojectMaps.stream().map(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId).collect(Collectors.toList());
                    projectTypesFi  = projectTypes.stream().filter(f -> !collect1.contains(f.getId())).collect(Collectors.toList());
                }else {
                    projectTypesFi = projectTypes;
                }

                /**插入用户知识库分类权限关系表*/
                if (CollectionUtil.isNotEmpty(projectTypesFi)){
                    projectTypesFi.forEach(e -> {
                        KbAuthuserKnowledgeprojectMap kbAuthuserKnowledgeprojectMap = new KbAuthuserKnowledgeprojectMap();
                        kbAuthuserKnowledgeprojectMap.setAuthUserId(authorizedUser.getId());
                        kbAuthuserKnowledgeprojectMap.setKnowledgeProjectId(e.getId());
                        kbAuthuserKnowledgeprojectMap.setSign(0);
                        kbAuthuserKnowledgeprojectMap.setCreateDate(new Date());
                        userknows.add(kbAuthuserKnowledgeprojectMap);
                        /**插入用户角色关系表*/
                        if (StringUtils.isNotBlank(authorizedUser.getRoleId())){
                            String roleId = authorizedUser.getRoleId();
                            List<String> list = Arrays.asList(roleId.split(","));
                            list.forEach(ee->{
                                KbUserRoleMap kbUserRoleMap = new KbUserRoleMap();
                                kbUserRoleMap.setUserId(authorizedUser.getId());
                                kbUserRoleMap.setRoleId(ee);
                                kbUserRoleMap.setKnowledgeProjectId(e.getId());
                                kbUserRoleMap.setCreateDate(new Date());
                                maps.add(kbUserRoleMap);
                            });
                        }
                    });

                }
            });

            kbUserRoleMapService.saveBatch(maps);
            authuserKnowledgeprojectMapService.saveBatch(userknows);
        }else {
            List<String> ids = authorizedUsers.stream().map(KbAuthorizedUser::getId).collect(Collectors.toList());
            //删除这个用户下已经授权的信息
            kbUserRoleMapService.remove(Wrappers.<KbUserRoleMap>lambdaQuery().in(KbUserRoleMap::getUserId,ids));
            authuserKnowledgeprojectMapService.remove(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery().in(KbAuthuserKnowledgeprojectMap::getAuthUserId,ids));
            kbAuthuserKnowMapService.remove(Wrappers.<KbAuthuserKnowMap>lambdaQuery().in(KbAuthuserKnowMap::getAuthUserId,ids));
            authorizedUsers.forEach(authorizedUser->{
                /**插入用户知识库权限关系表*/
                if (StringUtils.isNotBlank(authorizedUser.getKnowledgeProjectId())){
                    KbAuthuserKnowledgeprojectMap kbAuthuserKnowledgeprojectMap = new KbAuthuserKnowledgeprojectMap();
                    kbAuthuserKnowledgeprojectMap.setAuthUserId(authorizedUser.getId());
                    kbAuthuserKnowledgeprojectMap.setKnowledgeProjectId(authorizedUser.getKnowledgeProjectId());
                    kbAuthuserKnowledgeprojectMap.setSign(0);
                    authuserKnowledgeprojectMapService.save(kbAuthuserKnowledgeprojectMap);
                }
                /**插入用户角色关系表*/
                if (StringUtils.isNotBlank(authorizedUser.getRoleId())){
                    String roleId = authorizedUser.getRoleId();
                    List<String> list = Arrays.asList(roleId.split(","));
                    List<KbUserRoleMap> maps = new ArrayList<>();
                    list.forEach(e->{
                        KbUserRoleMap kbUserRoleMap = new KbUserRoleMap();
                        kbUserRoleMap.setUserId(authorizedUser.getId());
                        kbUserRoleMap.setRoleId(e);
                        kbUserRoleMap.setKnowledgeProjectId(authorizedUser.getKnowledgeProjectId());
                        maps.add(kbUserRoleMap);
                    });
                    kbUserRoleMapService.saveBatch(maps);
                }


            });
        }


        return  Result.OK();
    }

    @Override
    @Transactional
    public Result<?> delById(String id, String knowledgeProjectId) {

        if (!"0".equals(knowledgeProjectId)) {
            //移除知识库分类节点下所有的子节点下的这个用户
            List<KbKnowledgeProject> knowPros = knowledgeProjectService.list(Wrappers.<KbKnowledgeProject>lambdaQuery()
                    .like(KbKnowledgeProject::getFullPath, knowledgeProjectId)
            );
            List<String> knowProIds = knowPros.stream().map(KbKnowledgeProject::getId).collect(Collectors.toList());
            kbUserRoleMapService.remove(Wrappers.<KbUserRoleMap>lambdaQuery()
                    .eq(KbUserRoleMap::getUserId,id)
                    .in(KbUserRoleMap::getKnowledgeProjectId,knowProIds)
            );
            authuserKnowledgeprojectMapService.remove(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                    .eq(KbAuthuserKnowledgeprojectMap::getAuthUserId,id)
                    .in(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId,knowProIds));
            kbAuthuserKnowMapService.remove(Wrappers.<KbAuthuserKnowMap>lambdaQuery()
                    .eq(KbAuthuserKnowMap::getAuthUserId,id)
                    .in(KbAuthuserKnowMap::getKnowledgeProjectId,knowProIds));
            //判断用户在有没有其他节点的权限，如果都没有了，就移除这个授权用户
            List<KbAuthuserKnowledgeprojectMap> list = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery().eq(KbAuthuserKnowledgeprojectMap::getAuthUserId, id));
            if (CollectionUtil.isEmpty(list)){
                super.remove(Wrappers.<KbAuthorizedUser>lambdaQuery().eq(KbAuthorizedUser::getId,id));
            }

        }else {
            super.remove(Wrappers.<KbAuthorizedUser>lambdaQuery().eq(KbAuthorizedUser::getId,id));
            kbUserRoleMapService.remove(Wrappers.<KbUserRoleMap>lambdaQuery()
                    .eq(KbUserRoleMap::getUserId,id)
                    .eq(KbUserRoleMap::getKnowledgeProjectId,"0")
            );
            authuserKnowledgeprojectMapService.remove(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                    .eq(KbAuthuserKnowledgeprojectMap::getAuthUserId,id)
                    .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId,"0"));
        }

        return Result.OK();
    }

    @Override
    @Transactional
    public Result<?> addUserPermitsKnows(AddUserPermissKnowsVo addUserPermissKnowsVo) {
        String knowledgeProjectId = addUserPermissKnowsVo.getKnowledgeProjectId();
        List<KbAuthorizedUser> authorizedUsers = addUserPermissKnowsVo.getAuthorizedUsers();
        List<String> knowledgeIds = addUserPermissKnowsVo.getKnowledgeIds();
        if (StrUtil.isBlank(knowledgeProjectId)||CollectionUtil.isEmpty(authorizedUsers)||CollectionUtil.isEmpty(knowledgeIds)){
            return Result.error("请检查参数，授权节点、授权用户，授权资讯不能为空");
        }
        List<String> userIds = authorizedUsers.stream().map(KbAuthorizedUser::getId).collect(Collectors.toList());
        List<KbAuthuserKnowledgeprojectMap> list = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                .in(KbAuthuserKnowledgeprojectMap::getAuthUserId, userIds)
                .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, knowledgeProjectId)
                .eq(KbAuthuserKnowledgeprojectMap::getSign, 0)
        );
        List<KbAuthuserKnowledgeprojectMap> listSign = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                .in(KbAuthuserKnowledgeprojectMap::getAuthUserId, userIds)
                .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, knowledgeProjectId)
                .eq(KbAuthuserKnowledgeprojectMap::getSign, 1)
        );

        if (CollectionUtil.isNotEmpty(list)){
            StringBuffer res = new StringBuffer();
            list.forEach(e->{
                res.append("用户"+e.getAuthUserId()+"在"+e.getKnowledgeProjectId()+"节点下已有完全权限。请先移除用户在此节点下的完全权限,再在此节点对用户进行单独资讯的授权\r\n");
            });
            return Result.error(res.toString());
        }


        List<KbAuthuserKnowMap> saves = new ArrayList<>();
        List<KbAuthuserKnowledgeprojectMap> saves1 = new ArrayList<>();
        authorizedUsers.forEach(user->{
            //第一次在这个节点添加资讯授权
            if (CollectionUtil.isEmpty(listSign)) {
                KbAuthuserKnowledgeprojectMap kbAuthuserKnowledgeprojectMap = new KbAuthuserKnowledgeprojectMap();
                kbAuthuserKnowledgeprojectMap.setAuthUserId(user.getId());
                kbAuthuserKnowledgeprojectMap.setKnowledgeProjectId(knowledgeProjectId);
                kbAuthuserKnowledgeprojectMap.setSign(1);
                kbAuthuserKnowledgeprojectMap.setCreateDate(new Date());
                saves1.add(kbAuthuserKnowledgeprojectMap);
            }
            knowledgeIds.forEach(know->{
                KbAuthuserKnowMap kbAuthuserKnowMap = new KbAuthuserKnowMap();
                kbAuthuserKnowMap.setAuthUserId(user.getId());
                kbAuthuserKnowMap.setCreateDate(new Date());
                kbAuthuserKnowMap.setKnowledgeId(know);
                kbAuthuserKnowMap.setKnowledgeProjectId(knowledgeProjectId);
                saves.add(kbAuthuserKnowMap);
            });
        });
        kbAuthuserKnowMapService.saveBatch(saves);
        authuserKnowledgeprojectMapService.saveBatch(saves1);
        return Result.OK();
    }

    @Override
    public Result<?> getAll(KbAuthorizedUser user) {
        Integer pageNum = 1;
        Integer pageSize = 10;
        if (ObjectUtil.isNotEmpty(user.getPageNum())) {
            pageNum = user.getPageNum();
        }
        if (ObjectUtil.isNotEmpty(user.getPageSize())) {
            pageSize = user.getPageSize();
        }
        //查询出已经有超级管理员权限的用户，做排除
        List<KbUserRoleMap> list = kbUserRoleMapService.list(Wrappers.<KbUserRoleMap>lambdaQuery().eq(KbUserRoleMap::getKnowledgeProjectId, "0"));
        List<String> collect = list.stream().map(KbUserRoleMap::getUserId).collect(Collectors.toList());
        Page page = new Page(pageNum,pageSize);
        return Result.OK(super.page(page,Wrappers.<KbAuthorizedUser>lambdaQuery()
                .like(StringUtils.isNotBlank(user.getName()),KbAuthorizedUser::getName,user.getName())
                .eq(StringUtils.isNotBlank(user.getUsername()),KbAuthorizedUser::getUsername,user.getUsername())
                .eq(StringUtils.isNotBlank(user.getOrgId()),KbAuthorizedUser::getOrgId,user.getOrgId())
                .eq(StringUtils.isNotBlank(user.getOrgName()),KbAuthorizedUser::getOrgName,user.getOrgName())
                .notIn(CollectionUtil.isNotEmpty(collect),KbAuthorizedUser::getId,collect)
        ));
    }

    @Override
    public Result<?> knowBelongWho(String knowledgeProjectId, String knowledgeId) {
        List<String> userIds = new ArrayList<>();
        List<KbAuthuserKnowledgeprojectMap> list = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, knowledgeProjectId)
                .eq(KbAuthuserKnowledgeprojectMap::getSign, 0)
        );
        if (CollectionUtil.isNotEmpty(list)){
            List<String> collect = list.stream().map(KbAuthuserKnowledgeprojectMap::getAuthUserId).collect(Collectors.toList());
            userIds.addAll(collect);
        }
        List<KbAuthuserKnowMap> list1 = kbAuthuserKnowMapService.list(Wrappers.<KbAuthuserKnowMap>lambdaQuery()
                .eq(KbAuthuserKnowMap::getKnowledgeProjectId, knowledgeProjectId)
                .eq(KbAuthuserKnowMap::getKnowledgeId, knowledgeId)
        );
        if (CollectionUtil.isNotEmpty(list1)){
            List<String> collect = list1.stream().map(KbAuthuserKnowMap::getAuthUserId).collect(Collectors.toList());
            userIds.addAll(collect);
        }

        if (CollectionUtil.isNotEmpty(userIds)) {
            return Result.OK(super.list(Wrappers.<KbAuthorizedUser>lambdaQuery().in(KbAuthorizedUser::getId,userIds)));
        }else {
            return  Result.OK();
        }
    }


    @Override
    @Transactional
    public Result<?> edit(KbAuthorizedUser authorizedUser) {
        String newRole = authorizedUser.getRoleId();
        String knowProId = authorizedUser.getKnowledgeProjectId();
        authorizedUser.setUpdateTime(new Date());
        super.updateById(authorizedUser);


        if (!"0".equals(knowProId)) {
            /**修改用户角色关系表*/
            if (StringUtils.isNotBlank(newRole)){
                //所编辑知识库分类节点下所有的子节点
                List<KbKnowledgeProject> knowPros = knowledgeProjectService.list(Wrappers.<KbKnowledgeProject>lambdaQuery()
                        .like(KbKnowledgeProject::getFullPath, knowProId)
                );


                List<String> knowProIds = knowPros.stream().map(KbKnowledgeProject::getId).collect(Collectors.toList());

                kbUserRoleMapService.remove(Wrappers.<KbUserRoleMap>lambdaQuery()
                        .eq(KbUserRoleMap::getUserId,authorizedUser.getId())
                        .in(KbUserRoleMap::getKnowledgeProjectId,knowProIds)
                );

                List<String> list = Arrays.asList(newRole.split(","));
                List<KbUserRoleMap> maps = new ArrayList<>();
                list.forEach(e->{
                    knowProIds.forEach(ee->{
                        KbUserRoleMap kbUserRoleMap = new KbUserRoleMap();
                        kbUserRoleMap.setUserId(authorizedUser.getId());
                        kbUserRoleMap.setRoleId(e);
                        kbUserRoleMap.setKnowledgeProjectId(ee);
                        kbUserRoleMap.setCreateDate(new Date());
                        maps.add(kbUserRoleMap);
                    });

                });
                kbUserRoleMapService.saveBatch(maps);

            }
        }else {
            kbUserRoleMapService.remove(Wrappers.<KbUserRoleMap>lambdaQuery().eq(KbUserRoleMap::getUserId,authorizedUser.getId()));
            authuserKnowledgeprojectMapService.remove(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery().eq(KbAuthuserKnowledgeprojectMap::getAuthUserId,authorizedUser.getId()));
            kbAuthuserKnowMapService.remove(Wrappers.<KbAuthuserKnowMap>lambdaQuery().eq(KbAuthuserKnowMap::getAuthUserId,authorizedUser.getId()));

            /**插入用户知识库权限关系表*/
            if (StringUtils.isNotBlank(authorizedUser.getKnowledgeProjectId())){
                KbAuthuserKnowledgeprojectMap kbAuthuserKnowledgeprojectMap = new KbAuthuserKnowledgeprojectMap();
                kbAuthuserKnowledgeprojectMap.setAuthUserId(authorizedUser.getId());
                kbAuthuserKnowledgeprojectMap.setKnowledgeProjectId(authorizedUser.getKnowledgeProjectId());
                kbAuthuserKnowledgeprojectMap.setSign(0);
                authuserKnowledgeprojectMapService.save(kbAuthuserKnowledgeprojectMap);
            }
            /**插入用户角色关系表*/
            if (StringUtils.isNotBlank(authorizedUser.getRoleId())){
                String roleId = authorizedUser.getRoleId();
                List<String> list = Arrays.asList(roleId.split(","));
                List<KbUserRoleMap> maps = new ArrayList<>();
                list.forEach(e->{
                    KbUserRoleMap kbUserRoleMap = new KbUserRoleMap();
                    kbUserRoleMap.setUserId(authorizedUser.getId());
                    kbUserRoleMap.setRoleId(e);
                    kbUserRoleMap.setKnowledgeProjectId(authorizedUser.getKnowledgeProjectId());
                    maps.add(kbUserRoleMap);
                });
                kbUserRoleMapService.saveBatch(maps);
            }
        }
        return Result.OK();
    }



    @Override
    public Result<?> lists(String roleId, String username, String name, String orgId, String orgName, String knowledgeProjectId, String category, Integer pageNum, Integer pageSize) {
        QueryWrapper<KbAuthorizedUser> query = new QueryWrapper<>();
        Page<KbAuthorizedUser> page = new Page<>(pageNum, pageSize);

        query.eq(StringUtils.isNotBlank(username),"a.username",username);
        query.eq(StringUtils.isNotBlank(orgId),"a.org_id",orgId);
        query.eq(StringUtils.isNotBlank(roleId),"b.role_id",roleId);
        query.eq(StringUtils.isNotBlank(knowledgeProjectId),"d.knowledge_project_id",knowledgeProjectId);
        query.eq(StringUtils.isNotBlank(knowledgeProjectId),"b.knowledge_project_id",knowledgeProjectId);
        query.like(StringUtils.isNotBlank(name),"a.name",name);
        query.like(StringUtils.isNotBlank(orgName),"a.org_name",orgName);


        //根据一些条件动态的关联表
        String sql = "";
        IPage<KbAuthorizedUser> res = authorizedUserMapper.pageList(page, query);
        return Result.OK(res);
    }

    @Override
    public Result<?> userPermission(String token) {
        /**调用第三方系统校验接口*/
        Result res =  doCheck(token);
        boolean success = res.isSuccess();
        if(200 == res.getCode() && success){
            /**校验成功，获取到第三方用户信息*/
            KbAuthorizedUser bean = JSONUtil.toBean(JSONUtil.toJsonStr(res.getResult()), KbAuthorizedUser.class);
            /**校验第三方用户是否进行了授权*/
            List<KbAuthorizedUser> list = super.list(Wrappers.<KbAuthorizedUser>lambdaQuery().eq(KbAuthorizedUser::getUserId, bean.getUserId()));
            if (CollectionUtil.isEmpty(list)){
                HttpServletResponse httpServletResponse = SpringContextUtils.getHttpServletResponse();
                httpServletResponse.setStatus(401);
                return Result.error("该用户还未进行授权访问，请联系管理员进行授权");
            }
            /**查询授权用户的角色和权限*/
            UserInfoVo userInfoVo = new UserInfoVo();
            /**查询授权用户,“所有”节点的角色优先*/
            QueryWrapper<KbAuthorizedUser> query = new QueryWrapper<>();
            query.eq("a.user_id",bean.getUserId());
            query.eq("b.knowledge_project_id","0");
            KbAuthorizedUser one = authorizedUserMapper.getOne(query);
            if (ObjectUtil.isEmpty(one) || StringUtils.isBlank(one.getRoleId())){
                QueryWrapper<KbAuthorizedUser> query1 = new QueryWrapper<>();
                query1.eq("a.user_id",bean.getUserId());
                one = authorizedUserMapper.getOne(query1);
            }

            /**是否是所有节点的管理员*/
            List<KbAuthuserKnowledgeprojectMap> list1 = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                    .eq(KbAuthuserKnowledgeprojectMap::getAuthUserId, one.getId())
                    .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, "0")
                    .eq(KbAuthuserKnowledgeprojectMap::getSign, 0)
            );

            if (CollectionUtil.isNotEmpty(list1)){
                one.setIsAll(0);
            }else {
                one.setIsAll(1);
            }

            List<KbRole> kbRoles = roleService.listByIds(Arrays.asList(one.getRoleId().split(",")));

            List<KbRolePermissionMap> permissionMaps = rolePermissionMapService.list(Wrappers.<KbRolePermissionMap>lambdaQuery().in(KbRolePermissionMap::getRoleId, Arrays.asList(one.getRoleId().split(","))));

//            Map<Long, List<KbRolePermissionMap>> collect = permissionMaps.stream().collect(Collectors.groupingBy(KbRolePermissionMap::getRoleId));
//            List<KbPermissions> permissions = new ArrayList<>();
//            kbRoles.forEach(e->{
//                List<Long> longs = CollectionUtil.isEmpty(collect.get(e.getId())) ? new ArrayList<Long>() : collect.get(e.getId()).stream().map(KbRolePermissionMap::getPermissionId).collect(Collectors.toList());
//                if (CollectionUtil.isNotEmpty(longs)) {
//                    e.setPermissions(permissionsService.list(Wrappers.<KbPermissions>lambdaQuery().in(KbPermissions::getId,longs)));
//                }
//            });
            if (CollectionUtil.isNotEmpty(permissionMaps)) {
                List<KbPermissions> permissions = permissionsService.list(Wrappers.<KbPermissions>lambdaQuery().in(KbPermissions::getId, permissionMaps.stream().map(KbRolePermissionMap::getPermissionId).collect(Collectors.toList())));
                userInfoVo.setPermissions(permissions);
            }
            userInfoVo.setRoles(kbRoles);
            userInfoVo.setAuthorizedUser(one);
            return Result.OK(userInfoVo);
        }else {
            HttpServletResponse httpServletResponse = SpringContextUtils.getHttpServletResponse();
            httpServletResponse.setStatus(550);
            return Result.error("第三方用户验证未通过,请检查令牌是否正确");
        }
    }

    @Override
    public Result<?> thirdpartyUsers(String token, String name, String username, String knowledgeProjectId, Integer pageNum, Integer pageSize) {
        //查询出这个节点已经受过权的用户
        List<KbAuthuserKnowledgeprojectMap> list1 = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery().eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, knowledgeProjectId));
        StringBuffer exists = new StringBuffer();
        if (CollectionUtil.isNotEmpty(list1)){
            List<String> collect = list1.stream().map(KbAuthuserKnowledgeprojectMap::getAuthUserId).collect(Collectors.toList());
            List<KbAuthorizedUser> list = super.list(Wrappers.<KbAuthorizedUser>lambdaQuery().select(KbAuthorizedUser::getUserId).in(KbAuthorizedUser::getId, collect));
            List<String> collect1 = list.stream().map(KbAuthorizedUser::getUserId).collect(Collectors.toList());
            collect1.forEach(e ->{
                exists.append(","+e);
            });
        }
        String finalExists = "";
        if (exists.length()>0){
            finalExists = exists.substring(1);
        }
        String body = HttpRequest.get(getusersurl).header("X-Access-Token", token)
                .form("pageNum",pageNum)
                .form("pageSize",pageSize)
                .form("name",name)
                .form("username",username)
                .form("excludeIds",finalExists)
                .execute().body();
        Result bean = JSONUtil.toBean(body, Result.class);

        Page page = JSONUtil.toBean(JSONUtil.toJsonStr(bean.getResult()), Page.class);

        List<KbAuthorizedUser> list = JSONUtil.toList(JSONUtil.parseArray(JSONUtil.toJsonStr(page.getRecords())), KbAuthorizedUser.class);
        Page<KbAuthorizedUser> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setCurrent(page.getCurrent());
        result.setSize(page.getSize());
        result.setRecords(list);
        return Result.OK(result);
    }


    @Override
    public Result<?> doCheck(String token) {
        String body = HttpRequest.post(checkuserurl).header("X-Access-Token", token).execute().body();
        Result bean = null;
        try {
            bean = JSONUtil.toBean(body, Result.class);
        } catch (Exception e) {
            return Result.error("第三方用户校验异常");
        }
        return  bean;
    }
    @Override
    public Result<?> doCheckAndGetUser(String token) {
/**调用第三方系统校验接口*/
        Result res =  doCheck(token);
        boolean success = res.isSuccess();
        if(200 == res.getCode() && success) {
            /**校验成功，获取到第三方用户信息*/
            KbAuthorizedUser bean = JSONUtil.toBean(JSONUtil.toJsonStr(res.getResult()), KbAuthorizedUser.class);
            /**校验第三方用户是否进行了授权*/
            List<KbAuthorizedUser> list = super.list(Wrappers.<KbAuthorizedUser>lambdaQuery().eq(KbAuthorizedUser::getUserId, bean.getUserId()));
            if (CollectionUtil.isEmpty(list)) {
                HttpServletResponse httpServletResponse = SpringContextUtils.getHttpServletResponse();
                httpServletResponse.setStatus(401);
                return Result.error("该用户还未进行授权访问，请联系管理员进行授权");
            }
            /**查询授权用户,“所有”节点的角色优先*/
            QueryWrapper<KbAuthorizedUser> query = new QueryWrapper<>();
            query.eq("a.user_id",bean.getUserId());
            query.eq("b.knowledge_project_id","0");
            KbAuthorizedUser one = authorizedUserMapper.getOne(query);
            if (ObjectUtil.isEmpty(one) || StringUtils.isBlank(one.getRoleId())){
                QueryWrapper<KbAuthorizedUser> query1 = new QueryWrapper<>();
                query1.eq("a.user_id",bean.getUserId());
                one = authorizedUserMapper.getOne(query1);
            }
            /**是否是所有节点的管理员*/
            List<KbAuthuserKnowledgeprojectMap> list1 = authuserKnowledgeprojectMapService.list(Wrappers.<KbAuthuserKnowledgeprojectMap>lambdaQuery()
                    .eq(KbAuthuserKnowledgeprojectMap::getAuthUserId, one.getId())
                    .eq(KbAuthuserKnowledgeprojectMap::getKnowledgeProjectId, "0")
                    .eq(KbAuthuserKnowledgeprojectMap::getSign, 0)
            );

            if (CollectionUtil.isNotEmpty(list1)){
                one.setIsAll(0);
            }else {
                one.setIsAll(1);
            }
            return Result.OK(one);
        }else {
            return Result.error("第三方系统未通过用户校验");
        }
    }


}
