package com.zhongshu.card.server.core.service.user;

import com.github.microservice.auth.client.constant.AuthConstant;
import com.github.microservice.auth.client.content.ResultState;
import com.github.microservice.auth.client.model.AuthResourcesNameModel;
import com.github.microservice.auth.client.model.RoleGroupModel;
import com.github.microservice.auth.client.service.AuthResourcesNameService;
import com.github.microservice.auth.security.type.AuthType;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.google.common.collect.Lists;
import com.zhongshu.card.client.model.org.AuthModel;
import com.zhongshu.card.client.model.org.EditAuthParam;
import com.zhongshu.card.client.model.org.ModularModel;
import com.zhongshu.card.client.model.org.role.*;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.client.type.EditType;
import com.zhongshu.card.client.type.PermissionPointType;
import com.zhongshu.card.client.type.RoleType;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.org.OrganizationUserDao;
import com.zhongshu.card.server.core.dao.org.RoleDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.dataConfig.CardSystemDefault;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.OrganizationUser;
import com.zhongshu.card.server.core.domain.org.Role;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.org.OrganizationServiceImpl;
import com.zhongshu.card.server.core.service.scene.RoleSceneInfoService;
import com.zhongshu.card.server.core.util.AesUtils;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/6/5
 */
@Slf4j
@Service
public class RoleServiceImpl extends SuperService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private com.github.microservice.auth.client.service.RoleService roleService;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private AuthResourcesNameService authResourcesNameService;

    @Autowired
    private UserCountDao userCountDao;

    @Autowired
    private OrganizationUserDao organizationUserDao;

    @Autowired
    private OrganizationServiceImpl organizationService;

    @Autowired
    private RoleSceneInfoService roleSceneInfoService;

    /**
     * 添加/编辑角色
     *
     * @param param
     * @return
     */
    public ResultContent addRole(RoleAddParam param) {
        Assert.hasText(param.getName(), "name不能为空");
        Assert.hasText(param.getCode(), "code不能为空");
        String oid = param.getOid();
        Assert.hasText(oid, "oid不能为空");
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail(String.format("oid不存在：%s", oid));
        }
        param.setAuthType(organization.getAuthType());
        if (param.getSort() == null) {
            param.setSort(1L);
        }
        if (param.getState() == null) {
            param.setState(DataState.Enable);
        }
        Role nameRole = roleDao.findTopByNameAndOid(param.getName(), oid);
        Role codeRole = roleDao.findTopByCodeAndOid(param.getCode(), oid);
        if (StringUtils.isEmpty(param.getId())) {
            param.setId(null);
            // 添加
            if (ObjectUtils.isNotEmpty(nameRole)) {
                return ResultContent.buildFail(String.format("角色名称已存在：%s", param.getName()));
            }
            if (ObjectUtils.isNotEmpty(codeRole)) {
                return ResultContent.buildFail(String.format("角色名称已存在：%s", param.getCode()));
            }
            RoleGroupModel admin = new RoleGroupModel();
            admin.setName(param.getName());
            admin.setRemark("");
            admin.setOrganizationId(oid);
            com.github.microservice.auth.client.content.ResultContent<String> updateRoleGroupAdmin = roleService.updateRoleGroup(admin);
            String groupId = updateRoleGroupAdmin.getContent();

            com.github.microservice.auth.client.model.RoleModel roleModel = new com.github.microservice.auth.client.model.RoleModel();
            roleModel.setOrganizationId(oid);
            roleModel.setName(param.getName());
            roleModel.setRemark("");
            // 添加角色
            com.github.microservice.auth.client.content.ResultContent<String> updateRole = roleService.updateRole(roleModel);
            String roleId = updateRole.getContent();
            // 把角色绑定到角色组
            roleService.addRoleToRoleGroup(groupId, new String[]{updateRole.getContent()});

            Role role = new Role();
            BeanUtils.copyProperties(param, role);
            role.setRoleGroupId(groupId);
            role.setRoleType(RoleType.Custom);
            role.setRoleId(roleId);
            role.setCreateUserId(getCurrentUserId());
            role.setIsAdmin(Boolean.FALSE);
            // 初始信息
            initEntityNoOid(role);
            roleDao.save(role);
        } else {
            // 编辑
            Role role = roleDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(role)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            if (ObjectUtils.isNotEmpty(nameRole) && !nameRole.getId().equals(role.getId())) {
                return ResultContent.buildFail(String.format("角色名称已存在：%s", param.getName()));
            }
            if (ObjectUtils.isNotEmpty(codeRole) && !codeRole.getId().equals(role.getId())) {
                return ResultContent.buildFail(String.format("角色编码已存在：%s", param.getCode()));
            }
            // 更新权限中心的角色组信息
            com.github.microservice.auth.client.content.ResultContent<RoleGroupModel> resultContent = roleService.getRoleGroup(role.getRoleGroupId());
            if (resultContent.getState() == ResultState.Success) {
                RoleGroupModel roleGroupModel = resultContent.getContent();
                roleGroupModel.setName(param.getName());
                roleService.updateRoleGroup(roleGroupModel);
            }
            // 更新权限中心角色信息
            if (StringUtils.isNotEmpty(role.getRoleId())) {
                com.github.microservice.auth.client.content.ResultContent<com.github.microservice.auth.client.model.RoleModel> roleModelResultContent = roleService.getRole(role.getRoleId());
                if (roleModelResultContent.getState() == ResultState.Success) {
                    com.github.microservice.auth.client.model.RoleModel roleModel = roleModelResultContent.getContent();
                    roleModel.setName(param.getName());
                    roleService.updateRole(roleModel);
                }
            }
            // 编辑本地角色
            BeanUtils.copyProperties(param, role, "roleType");
            initUpdateEntity(role);
            roleDao.save(role);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    public ResultContent deleteRole(String id) {
        Role role = roleDao.findTopById(id);
        if (ObjectUtils.isEmpty(role)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        if (role.getIsAdmin() != null && role.getIsAdmin()) {
            return ResultContent.buildFail(String.format("管理员角色不能删除"));
        }
        if (role.getRoleType() == RoleType.BuildIn) {
            return ResultContent.buildFail(String.format("内置角色不能删除"));
        }
        // 删除本地角色
        roleDao.delete(role);
        // 删除权限中心角色
        roleService.removeRole(role.getRoleId());
        roleService.removeRoleGroup(role.getRoleGroupId());
        // 角色包含的场景
        roleSceneInfoService.deleteByRoleId(role.getId());
        return ResultContent.buildSuccess();
    }

    /**
     * 角色详情
     *
     * @param id
     * @return
     */
    public ResultContent<RoleModel> getRole(String id) {
        Role role = roleDao.findTopById(id);
        if (ObjectUtils.isEmpty(role)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        RoleModel roleModel = toModel(role);
        return ResultContent.buildSuccess(roleModel);
    }

    /**
     * 角色列表
     *
     * @param param
     * @param pageable
     * @return
     */
    public ResultContent<Page<RoleModel>> page(RoleSearchParam param, Pageable pageable) {
        initOidSearchParam(param);
        param.setIsSortDesc(Boolean.FALSE);

        Page<Role> page = roleDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    /**
     * 得到机构所有的角色
     *
     * @param oid
     * @return
     */
    public ResultContent<List<RoleModel>> getAllRoles(String oid) {
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        Assert.hasText(oid, "oid不能为空");
        List<Role> list = roleDao.findByOidOrderBySortAsc(oid);
        List<RoleModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toModel).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    public ResultContent<List<RoleModel>> queryRoles(RoleQueryParam param) {
        List<RoleModel> models = new ArrayList<>();
        AuthType authType = param.getAuthType();
        DataState state = param.getState();
        List<Role> roles = new ArrayList<>();
        if (authType != null && state != null) {
            roles = roleDao.findByAuthTypeAndStateOrderBySortAsc(authType, state);
        } else if (authType != null && state == null) {
            roles = roleDao.findByAuthTypeOrderBySortAsc(authType);
        } else if (authType == null && state != null) {
            roles = roleDao.findByStateOrderBySortAsc(state);
        } else {
            roles = roleDao.findByStateOrderBySortAsc(DataState.Enable);
        }
        if (ObjectUtils.isNotEmpty(roles)) {
            models = roles.stream().map(this::toModel).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 得到角色的权限数据
     *
     * @param roleId
     * @return
     */
    public ResultContent getList(String roleId) {
        Role roleObj = roleDao.findTopById(roleId);
        if (roleObj == null) {
            return ResultContent.buildFail("角色不存在");
        }
        Organization organization = organizationDao.findTopByOid(roleObj.getOid());
        if (organization == null) {
            return ResultContent.buildFail("企业不存在");
        }
        //获取该岗位的现在所有的权限
        var roleGroup = roleService.getRoleGroup(roleObj.getRoleGroupId()).getContent();
        Set<String> postAuth = new HashSet<>();
        if (!CollectionUtils.isEmpty(roleGroup.getRoleId())) {
            roleGroup.getRoleId().parallelStream().forEach(it -> {
                var role = roleService.getRole(it).getContent();
                if (role != null && !CollectionUtils.isEmpty(role.getAuth())) {
                    postAuth.addAll(role.getAuth());
                }
            });
        }
        // 角色确定
        AuthType authType = organization.getAuthType();
        return ResultContent.buildContent(buildAuthList(authType, postAuth));
    }

    /**
     * 构建权限树
     *
     * @param organizationType
     * @param postAuth
     * @return
     */
    List<ModularModel> buildAuthList(AuthType organizationType, Set<String> postAuth) {
        //获取系统所有权限
        List<AuthResourcesNameModel> authResourcesNameModels = new ArrayList<>();
        List<AuthModel> authModels = new ArrayList<>();

        if (organizationType != null) {
            com.github.microservice.auth.client.content.ResultContent<List<AuthResourcesNameModel>> content = authResourcesNameService.getAll(organizationType);
            authResourcesNameModels = content.getContent();

            authResourcesNameModels.forEach(it -> {
                String remark = it.getRemark();
                if (StringUtils.isNotEmpty(remark)) {
                    String[] split = remark.split("_");
                    if (split.length >= 2) {
                        AuthModel authModel = new AuthModel();
                        authModel.setId(CommonUtil.UUID());
                        authModel.setValue(it.getName());
                        authModel.setName(split[1]);
                        authModel.setModularName(split[0]);
                        int index = 1;
                        if (split.length >= 3) {
                            index = CommonUtil.turnStr2Inter(split[2]);
                        }
                        authModel.setIndex(index);
                        if (postAuth.contains(it.getName())) {
                            authModel.setSelect(true);
                        }

                        PermissionPointType pointType = null;
                        if (split.length >= 4) {
                            pointType = CommonUtil.getEnumByName(PermissionPointType.class, split[3]);
                        }
                        authModel.setPointType(pointType);
                        authModels.add(authModel);
                    }
                }
            });
        }

        Comparator comparator = new Comparator<AuthModel>() {
            @Override
            public int compare(AuthModel o1, AuthModel o2) {
                return Integer.compare(o1.getIndex(), o2.getIndex());
            }
        };

        Comparator comparator1 = new Comparator<ModularModel>() {
            @Override
            public int compare(ModularModel o1, ModularModel o2) {
                return Integer.compare(o1.getIndex(), o2.getIndex());
            }
        };

        Map<String, List<AuthModel>> maps = authModels.stream().collect(Collectors.groupingBy(AuthModel::getModularName));
        List<ModularModel> modularModels = new ArrayList<>();
        maps.forEach((key, val) -> {
            ModularModel modularModel = new ModularModel();
            modularModel.setId(CommonUtil.UUID());
            modularModel.setName(key);
            // 排序
            if (ObjectUtils.isNotEmpty(val)) {
                val.sort(comparator);
            }
            modularModel.setAuthModels(val);
            if (ObjectUtils.isNotEmpty(val)) {
                modularModel.setIndex(val.get(0).getIndex());
            }
            modularModels.add(modularModel);
        });
        modularModels.sort(comparator1);
        return modularModels;
    }

    /**
     * 改变角色权限
     *
     * @param param
     * @return
     */
    public ResultContent editRoleAuth(EditAuthParam param) {
        Role role = roleDao.findTopById(param.getRoleId());
        if (role == null) {
            return ResultContent.buildFail("角色不存在");
        }
        var roleGroup = roleService.getRoleGroup(role.getRoleGroupId()).getContent();
        com.github.microservice.auth.client.model.RoleModel roleModel;
        if (roleGroup.getRoleId() == null || CollectionUtils.isEmpty(roleGroup.getRoleId())) {
            // 如果角色不存在，则创建角色
            var roleByName = roleService.getRoleByName(role.getName(), role.getOid());
            if (roleByName.getState() != com.github.microservice.auth.client.content.ResultState.Success) {
                roleModel = new com.github.microservice.auth.client.model.RoleModel();
                roleModel.setOrganizationId(role.getOid());
                roleModel.setName(role.getName());
                roleModel.setRemark(role.getRemark());
                com.github.microservice.auth.client.content.ResultContent<String> updateRole = roleService.updateRole(roleModel);
                roleModel.setId(updateRole.getContent());
            } else {
                roleModel = roleByName.getContent();
            }
            // 权限中心角色绑定角色组
            roleService.addRoleToRoleGroup(roleGroup.getId(), new String[]{roleModel.getId()});
        } else {
            // 角色存在，查询角色信息
            List<String> roleIds = new ArrayList<>(roleGroup.getRoleId());
            roleModel = roleService.getRole(roleIds.get(0)).getContent();
            if (StringUtils.isEmpty(role.getRoleId())) {
                role.setRoleId(roleIds.get(0));
                roleDao.save(role);
            }
        }
        Set<String> auth = roleModel.getAuth();
        if (CollectionUtils.isEmpty(auth)) {
            auth = new HashSet<>();
        }
        if (param.getType() == null) {
            param.setType(EditType.Add);
        }

        if (param.getType() == EditType.Add) {
            // 最后提交的为准
            auth = new HashSet<>();
            auth.addAll(param.getAuths());
        } else {
            auth.removeAll(param.getAuths());
        }

        // 管理员角色默认有 管理员的权限
        if (role.getIsAdmin() != null && role.getIsAdmin()) {
            Organization organization = organizationDao.findTopByOid(role.getOid());
            if (organization != null && organization.getAuthType() == AuthType.Platform) {
                auth.add(AuthConstant.SuperAdmin);
            } else {
                auth.add(AuthConstant.Admin);
            }
        }
        roleModel.setAuth(auth);
        com.github.microservice.auth.client.content.ResultContent<String> content = roleService.updateRole(roleModel);
        if (content.getState() != ResultState.Success) {
            log.error("错误： {}", content.getMsg());
        }
        return ResultContent.buildSuccess(roleModel);
    }

    /**
     * 判断用户是否是超级管理员
     *
     * @param userId
     * @return
     */
    public boolean isSuperAdmin(String userId) {
        Set<String> auth = getUserAllAuths(userId);
        return auth.contains(AuthConstant.SuperAdmin);
    }

    /**
     * 得到用户在平台（平台机构）的所有的权限
     *
     * @param userId
     * @return
     */
    public Set<String> getUserAllAuths(String userId) {
        Set<String> auth = new HashSet<>();
        if (StringUtils.isEmpty(userId)) {
            return auth;
        }
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(userAccount)) {
            return auth;
        }
        List<OrganizationUser> organizationUsers = organizationUserDao.findByUserAndAuthType(userAccount, AuthType.Platform);
//        List<OrganizationUser> organizationUsers = organizationUserDao.findByUserId(userAccount.getUserId());
        if (ObjectUtils.isEmpty(organizationUsers)) {
            return auth;
        }
        for (OrganizationUser organizationUser : organizationUsers) {
            auth.addAll(getOrganizationUserAuths(organizationUser));
        }
        return auth;
    }

    /**
     * 得到当前用户在 指定的项目权限（加密后）
     *
     * @param projectOid
     * @return
     */
    public ResultContent getCurrentUserProjectAuth(String projectOid) {
        String userId = getCurrentUserId();
        Set<String> auths = getUserProjectAllAuths(projectOid, userId);
        // 得到平台的权限
        Organization organization = organizationService.getPlatForm();
        Set<String> platFormAuths = getUserOrgAllAuths(organization, userId);
        if (platFormAuths != null && !platFormAuths.isEmpty()) {
            auths.addAll(platFormAuths);
        }
        log.info("auths {}", auths);
        return ResultContent.buildSuccess(AesUtils.encryptAuth(auths));
    }

    public Set<String> getUserProjectAllAuths(String projectOid, String userId) {
        Set<String> auth = new HashSet<>();
        if (StringUtils.isEmpty(userId)) {
            return auth;
        }
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(userAccount)) {
            return auth;
        }
        List<OrganizationUser> organizationUsers = organizationUserDao.findByUserIdAndProjectOid(userAccount.getUserId(), projectOid);
        if (ObjectUtils.isEmpty(organizationUsers)) {
            return auth;
        }
        for (OrganizationUser organizationUser : organizationUsers) {
            auth.addAll(getOrganizationUserAuths(organizationUser));
        }
        return auth;
    }

    public Set<String> getUserOrgAllAuths(Organization organization, String userId) {
        Set<String> auth = new HashSet<>();
        if (StringUtils.isEmpty(userId)) {
            return auth;
        }
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(userAccount)) {
            return auth;
        }
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, userAccount);
        if (ObjectUtils.isEmpty(organizationUser)) {
            return auth;
        }
        auth.addAll(getOrganizationUserAuths(organizationUser));
        return auth;
    }

    /**
     * 得到机构用户数据权限
     *
     * @param organizationUser
     * @return
     */
    public Set<String> getOrganizationUserAuths(OrganizationUser organizationUser) {
        Set<String> auth = new HashSet<>();
        if (ObjectUtils.isNotEmpty(organizationUser)) {

//            var roleGroupModels = roleService.listRoleGroupFromOrganizationUser(oid, userId).getContent();
//            if (!CollectionUtils.isEmpty(roleGroupModels)) {
//                roleGroupModels.stream().forEach(roleGroup -> {
//                    if (!CollectionUtils.isEmpty(roleGroup.getRoleId())) {
//                        roleGroup.getRoleId().stream().forEach(it -> {
//                            var role = roleService.getRole(it).getContent();
//                            if (role != null && !CollectionUtils.isEmpty(role.getAuth())) {
//                                auth.addAll(role.getAuth());
//                            }
//                        });
//                    }
//                });
//            }

            List<Role> roles = organizationUser.getRoles();
            if (ObjectUtils.isNotEmpty(roles)) {
                roles.stream().forEach(tempRole -> {
                    var role = roleService.getRole(tempRole.getRoleId()).getContent();
                    if (role != null && !CollectionUtils.isEmpty(role.getAuth())) {
                        auth.addAll(role.getAuth());
                    }
                });
                List<Role> _list = roles.stream().filter(it -> {
                    return it.getIsAdmin();
                }).collect(Collectors.toList());

                // 如果角色是管理员角色，就把 Admin权限标识返回
                if (ObjectUtils.isNotEmpty(_list)) {
                    Organization org = organizationUser.getOrganization();
                    if (ObjectUtils.isNotEmpty(org)) {
                        if (org.getAuthType() == AuthType.Platform) {
                            auth.add(AuthConstant.SuperAdmin);
                        } else {
                            auth.add(AuthConstant.Admin);
                        }
                    }
                }
            }
        }
        return auth;
    }

    /**
     * 得到当前用户单企业的权限
     *
     * @param oid
     * @return
     */
    public ResultContent<Set<String>> getOrganizationAuth(String oid, String userId) {
        if (StringUtils.isEmpty(oid)) {
            oid = getCurrentOid();
        }
        if (StringUtils.isEmpty(userId)) {
            userId = getCurrentUserId();
        }
        Set<String> auth = new HashSet<>();
        if (StringUtils.isEmpty(oid)) {
            return ResultContent.buildSuccess(auth);
        }

        var roleGroupModels = roleService.listRoleGroupFromOrganizationUser(oid, userId).getContent();
        if (!CollectionUtils.isEmpty(roleGroupModels)) {
            roleGroupModels.stream().forEach(roleGroup -> {
                if (!CollectionUtils.isEmpty(roleGroup.getRoleId())) {
                    roleGroup.getRoleId().stream().forEach(it -> {
                        var role = roleService.getRole(it).getContent();
                        if (role != null && !CollectionUtils.isEmpty(role.getAuth())) {
                            auth.addAll(role.getAuth());
                        }
                    });
                }
            });
        }
        // 判断用户是否是管理员
        if (StringUtils.isNotEmpty(oid)) {
            UserAccount userAccount = userCountDao.findTopByUserId(userId);
            Organization organization = organizationDao.findTopByOid(oid);
            if (ObjectUtils.isNotEmpty(userAccount) && ObjectUtils.isNotEmpty(organization)) {
                OrganizationUser enterpriseUser = organizationUserDao.findTopByOrganizationAndUser(organization, userAccount);
                if (ObjectUtils.isNotEmpty(enterpriseUser)) {
                    List<Role> roles = enterpriseUser.getRoles();
                    if (ObjectUtils.isNotEmpty(roles)) {
                        List<Role> _list = roles.stream().filter(it -> {
                            return it.getIsAdmin();
                        }).collect(Collectors.toList());
                        // 如果角色是管理员角色，就把 Admin权限标识返回
                        if (ObjectUtils.isNotEmpty(_list)) {
                            auth.add(AuthConstant.Admin);
                        }
                    }
                }
            }
        }
        return ResultContent.buildSuccess(auth);
    }

    public List<Role> getProjectRoleByName(String projectOid, String name) {
        List<Role> roles = new ArrayList<>();
        if (StringUtils.isNotEmpty(projectOid) && StringUtils.isNotEmpty(name)) {
            List<String> names = List.of(name.split("、"));
            roles = roleDao.findByOidAndNameIn(projectOid, names);
        }
        return roles;
    }

    /**
     * 判断用户是否是项目管理员
     *
     * @param projectOid 项目oid
     * @param userId     用户userId
     * @return
     */
    public boolean userIsProjectManager(String projectOid, String userId) {
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isEmpty(organization)) {
            return false;
        }
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(userAccount)) {
            return false;
        }
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, userAccount);
        if (ObjectUtils.isEmpty(organizationUser)) {
            return false;
        }
        if (organizationUser.getIsAdmin() != null && organizationUser.getIsAdmin()) {
            return true;
        }
        return false;
    }

    public boolean userIsSuperAdmin(String userId) {
        UserAccount userAccount = userCountDao.findTopByUserId(userId);
        if (ObjectUtils.isEmpty(userAccount)) {
            return false;
        }
        Organization organization = organizationDao.findTopByAuthType(AuthType.Platform);
        if (ObjectUtils.isEmpty(organization)) {
            return false;
        }
        OrganizationUser organizationUser = organizationUserDao.findTopByOrganizationAndUser(organization, userAccount);
        if (ObjectUtils.isNotEmpty(organizationUser)) {
            return true;
        }
        return false;
    }

    /**
     * 初始机构的管理员角色
     *
     * @param organization
     * @return
     */
    public ResultContent initOrgManagerRole(Organization organization) {
        if (ObjectUtils.isNotEmpty(organization)) {
            Role adminRole = roleDao.findTopByNameAndOid(CardSystemDefault.DEFAULT_ROLE_NAME, organization.getOid());
            if (ObjectUtils.isEmpty(adminRole)) {
                Set<String> auth = Set.of(AuthConstant.Admin);
                if (organization.getAuthType().equals(AuthType.Platform)) {
                    auth = Set.of(AuthConstant.SuperAdmin);
                }

                String defaultName = CardSystemDefault.DEFAULT_ROLE_NAME;
                String defaultReMark = CardSystemDefault.DEFAULT_ROLE_NAME;
                String oid = organization.getOid();
                // 权限中心: 角色组
                RoleGroupModel admin = new RoleGroupModel();
                admin.setName(defaultName);
                admin.setRemark(defaultReMark);
                admin.setOrganizationId(oid);
                admin.setIdentity(auth);
                com.github.microservice.auth.client.content.ResultContent<String> updateRoleGroupAdmin = roleService.updateRoleGroup(admin);
                String groupId = updateRoleGroupAdmin.getContent();
                log.info("初始权限中心角色组成功：{}", groupId);

                if (!StringUtils.isEmpty(groupId)) {
                    // 权限中心: 角色信息
                    com.github.microservice.auth.client.model.RoleModel roleModel = new com.github.microservice.auth.client.model.RoleModel();
                    roleModel.setOrganizationId(oid);
                    roleModel.setName(defaultName);
                    roleModel.setRemark(defaultReMark);
                    roleModel.setAuth(auth);
                    com.github.microservice.auth.client.content.ResultContent<String> updateRole = roleService.updateRole(roleModel);

                    log.info("权限中心：初始角色和角色组关系成功");
                    String roleId = updateRole.getContent();
                    roleService.addRoleToRoleGroup(groupId, new String[]{roleId});

                    // 添加本地机构角色信息
                    adminRole = new Role();
                    if (organization.getAuthType().equals(AuthType.Platform)) {
                        adminRole.setCode(AuthConstant.SuperAdmin);
                    } else {
                        adminRole.setCode(AuthConstant.Admin);
                    }
                    adminRole.setAuth(auth);
                    adminRole.setOid(oid);
                    adminRole.setRoleGroupId(groupId);
                    adminRole.setName(defaultName);
                    adminRole.setRemark(defaultReMark);
                    adminRole.setRoleType(RoleType.BuildIn);
                    adminRole.setIsAdmin(Boolean.TRUE);
                    adminRole.setRoleId(roleId);
                    adminRole.setAuthType(organization.getAuthType());
                    roleDao.save(adminRole);
                }
            }
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 得到机构的 admin角色
     *
     * @param oid
     * @return
     */
    public List<Role> getOrgAdminRoles(String oid) {
        return roleDao.findByOidAndIsAdmin(oid, Boolean.TRUE);
    }

    /**
     * 用户移除角色
     *
     * @param userId
     * @param roles
     * @return
     */
    public ResultContent userRemoveRole(String userId, List<Role> roles) {
        if (StringUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(roles)) {
            String[] userIds = new String[]{userId};
            for (Role oldRole : roles) {
                roleService.removeUserFromRoleGroup(oldRole.getRoleGroupId(), userIds);
            }
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 用户绑定到角色中
     *
     * @param userId
     * @param roles
     * @return
     */
    public ResultContent userBindRoles(String userId, List<Role> roles) {
        if (StringUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(roles)) {
            String[] roleGroupIds = roles.stream().map(it -> it.getRoleGroupId()).collect(Collectors.toList()).toArray(String[]::new);
            roleService.addUsersToRoleGroup(userId, roleGroupIds);
        }
        return ResultContent.buildSuccess();
    }

    public ResultContent<List<RoleSimpleModel>> xcxGetCurrentRoles() {
        String projectOid = getCurrentProjectOid();
        String userId = getCurrentUserId();
        return ResultContent.buildSuccess(getUserInProjectRoles(projectOid, userId));
    }

    /**
     * 得到用户在项目下所有的角色信息
     *
     * @param projectOid
     * @param userId
     */
    public List<RoleSimpleModel> getUserInProjectRoles(String projectOid, String userId) {
        List<RoleSimpleModel> models = new ArrayList<>();
        if (StringUtils.isNotEmpty(projectOid) && ObjectUtils.isNotEmpty(userId)) {
            List<OrganizationUser> list = organizationUserDao.findByUserIdAndProjectOidAndIsOrg(userId, projectOid, Boolean.TRUE);
            List<Role> roles = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(list)) {
                list.stream().forEach(it -> {
                    if (ObjectUtils.isNotEmpty(it.getRoles())) {
                        roles.addAll(it.getRoles());
                    }
                });
            }
            models = roles.stream().map(this::toSimpleModel).collect(Collectors.toList());
        }
        return models;
    }

    //--------------------------模型转换 start---------------------

    public List<RoleModel> toModels(List<Role> roles) {
        if (ObjectUtils.isNotEmpty(roles)) {
            return roles.stream().map(this::toModel).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    public RoleModel toModel(Role role) {
        RoleModel roleModel = new RoleModel();
        if (ObjectUtils.isNotEmpty(role)) {
            BeanUtils.copyProperties(role, roleModel);
        }
        return roleModel;
    }

    public RoleSimpleModel toSimpleModel(Role role) {
        RoleSimpleModel roleModel = new RoleSimpleModel();
        if (ObjectUtils.isNotEmpty(role)) {
            BeanUtils.copyProperties(role, roleModel);
        }
        return roleModel;
    }

}
