package com.vctgo.system.service.impl;

import com.vctgo.common.core.constant.HttpStatus;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.system.api.RemoteProfileService;
import com.vctgo.system.api.domain.SysPlatformRole;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.dto.ProfileUserInfoDto;
import com.vctgo.system.service.ISysPlatformMenuService;
import com.vctgo.system.service.ISysPlatformPermissionService;
import com.vctgo.system.service.ISysPlatformRoleService;
import com.vctgo.system.util.ConstantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysPlatformPermissionServiceImpl implements ISysPlatformPermissionService {
    private static final Logger log = LoggerFactory.getLogger(SysPlatformPermissionServiceImpl.class);
    @Autowired
    private ISysPlatformRoleService roleService;

    @Autowired
    private ISysPlatformMenuService menuService;

    @Autowired
    private RemoteProfileService remoteProfileService;
    /**
     * 获取角色数据权限
     *
     * @param user 用户Id
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(SysPlatformUser user) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户Id
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(SysPlatformUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            List<SysPlatformRole> roles = user.getRoles();
            if (!roles.isEmpty() && roles.size() > 1) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysPlatformRole role : roles) {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }

            try {
                //剔除角色关联的特定菜单
                List<String> profileMenuAuthList = Arrays.asList(
                        ConstantUtils.PROFILE_USER_AUTH_WHOLE,                                  //综合查询
                        ConstantUtils.PROFILE_USER_AUTH_CONTROL,                                //园所资料
                        ConstantUtils.PROFILE_USER_AUTH_ACHIEVEMENT,                            //方案成果
                        ConstantUtils.PROFILE_USER_AUTH_SCHEME_TEMPLATE,                        //方案模板
                        ConstantUtils.PROFILE_POLICY_AUTH,                                      //政策文件
                        ConstantUtils.PROFILE_PLACE_RESOURCE_AUTH,                              //地方资源
                        ConstantUtils.PROFILE_THEORY_AUTH,                                      //专业理论
                        ConstantUtils.PROFILE_USER_AUTH_CASE,                                   //活动案例
                        ConstantUtils.PROFILE_USER_AUTH_DIRECTION,                              //主题方向
                        ConstantUtils.PROFILE_USER_AUTH_STANDARD,                               //标准管理
                        ConstantUtils.PROFILE_USER_AUTH_LABEL,                                  //标签管理
                        ConstantUtils.PROFILE_USER_AUTH_AUTH,                                   //权限配置
                        ConstantUtils.PROFILE_USER_AUTH_KINDER,                                 //园所资料授权
                        ConstantUtils.PROFILE_USER_GAME_AUTH                                    //区域游戏授权
                );
                perms.removeIf(profileMenuAuthList::contains);
                //添加内部资源管理用户获取菜单权限，如果为“启用”状态且“时间”有效
                R<ProfileUserInfoDto> profileUserInfoDtoR = remoteProfileService.getValidUserInfoByUserId(user.getUserId());
                if (HttpStatus.SUCCESS == profileUserInfoDtoR.getCode()) {
                    if (Objects.nonNull(profileUserInfoDtoR.getData()) && profileUserInfoDtoR.getData().getAccountStatus().equals(ConstantUtils.PROFILE_USER_ACCOUNT_STATUS_10)) {
                        ProfileUserInfoDto profileUserInfoDto = profileUserInfoDtoR.getData();
                        if (StrUtils.isNotEmpty(profileUserInfoDto.getMenuAuthCode())) {
                            List<String> menuAuthCodeList = Arrays.asList(profileUserInfoDto.getMenuAuthCode().split(","));
                            perms.addAll(menuAuthCodeList);
                            List<String> profileAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileAuthCode().split(","));
                            perms.addAll(profileAuthCodeList);
                            List<String> profileAchievementAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileAchievementAuthCode().split(","));
                            perms.addAll(profileAchievementAuthCodeList);
                            List<String> profileTemplateAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileTemplateAuthCode().split(","));
                            perms.addAll(profileTemplateAuthCodeList);
                            List<String> profilePolicyAuthCodeList = Arrays.asList(profileUserInfoDto.getProfilePolicyAuthCode().split(","));
                            perms.addAll(profilePolicyAuthCodeList);
                            List<String> profilePlaceResourceAuthCodeList = Arrays.asList(profileUserInfoDto.getProfilePlaceResourceAuthCode().split(","));
                            perms.addAll(profilePlaceResourceAuthCodeList);
                            List<String> profileTheoryAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileTheoryAuthCode().split(","));
                            perms.addAll(profileTheoryAuthCodeList);
                            List<String> profileCaseAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileCaseAuthCode().split(","));
                            perms.addAll(profileCaseAuthCodeList);
                            List<String> profileGameAuthCodeList = Arrays.asList(profileUserInfoDto.getProfileGameAuthCode().split(","));
                            perms.addAll(profileGameAuthCodeList);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取内部资源管理用户权限失败:{}", e.getMessage());
            }
        }
        //System.out.println("获取菜单数据权限："  + JSONArray.toJSON(perms));
        return perms;
    }
}
