package com.fs.framework.service;

import com.fs.common.core.domain.entity.SysRole;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyRole;
import com.fs.framework.security.LoginAdminUser;
import com.fs.framework.security.LoginCompanyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 自定义权限实现，ss取自SpringSecurity首字母
 */
@Service("ss")
public class PermissionService
{
    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    /** 管理员角色权限标识 */
    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMETER = ",";

    private static final String PERMISSION_DELIMETER = ",";

    @Autowired
    private TokenService tokenService;

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {
        if (StringUtils.isEmpty(permission))
        {
            return false;
        }
        //医生端不需要权限
        String type = ServletUtils.getRequest().getHeader("X-Frontend-Type");
        if("doctor".equals(type)) {
            return true;
        }
//        LoginCompanyUser loginCompanyUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Object user = tokenService.getLoginUser(ServletUtils.getRequest());
//        if (StringUtils.isNull(user) || CollectionUtils.isEmpty(user.getPermissions()))
        if (StringUtils.isNull(user))
        {
            return false;
        }
        if ("admin".equals(type)){
            LoginUser loginUser =(LoginUser) user;
            if (CollectionUtils.isEmpty(loginUser.getPermissions())){
                return false;
            }
            return hasPermissions(loginUser.getPermissions(), permission);
        } else if("company".equals(type)){
            com.fs.framework.security.LoginUser loginUser =(com.fs.framework.security.LoginUser) user;
            if (CollectionUtils.isEmpty(loginUser.getPermissions())){
                return false;
            }
            return hasPermissions(loginUser.getPermissions(), permission);
        }
        return false;
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermi(String permission)
    {
        return hasPermi(permission) != true;
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermi(String permissions)
    {
        if (StringUtils.isEmpty(permissions))
        {
            return false;
        }
//        LoginCompanyUser loginCompanyUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Object user = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(user))
        {
            return false;
        }
        String type = ServletUtils.getRequest().getHeader("X-Frontend-Type");
        if ("admin".equals(type)){
            LoginAdminUser loginUser =(LoginAdminUser) user;
            if (CollectionUtils.isEmpty(loginUser.getPermissions())){
                return false;
            }
            Set<String> authorities = loginUser.getPermissions();
            for (String permission : permissions.split(PERMISSION_DELIMETER))
            {
                if (permission != null && hasPermissions(authorities, permission))
                {
                    return true;
                }
            }
        } else if("company".equals(type)){
            LoginCompanyUser loginUser =(LoginCompanyUser) user;
            if (CollectionUtils.isEmpty(loginUser.getPermissions())){
                return false;
            }
            Set<String> authorities = loginUser.getPermissions();
            for (String permission : permissions.split(PERMISSION_DELIMETER))
            {
                if (permission != null && hasPermissions(authorities, permission))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断用户是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasRole(String role)
    {
        if (StringUtils.isEmpty(role))
        {
            return false;
        }
        Object user = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(user))
        {
            return false;
        }
        //获取不同对象
        String type = ServletUtils.getRequest().getHeader("X-Frontend-Type");
        if ("admin".equals(type)){
            LoginAdminUser loginUser =(LoginAdminUser) user;
            if (CollectionUtils.isEmpty(loginUser.getUser().getRoles())){
                return false;
            }
            for (SysRole sysRole : loginUser.getUser().getRoles())
            {
                String roleKey = sysRole.getRoleKey();
                if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role)))
                {
                    return true;
                }
            }
        } else if("company".equals(type)){
            LoginCompanyUser loginUser =(LoginCompanyUser) user;
            if (CollectionUtils.isEmpty(loginUser.getUser().getRoles())){
                return false;
            }
            for (CompanyRole sysRole : loginUser.getUser().getRoles())
            {
                String roleKey = sysRole.getRoleKey();
                if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role)))
                {
                    return true;
                }
            }
        }


        return false;
    }

    /**
     * 验证用户是否不具备某角色，与 isRole逻辑相反。
     *
     * @param role 角色名称
     * @return 用户是否不具备某角色
     */
    public boolean lacksRole(String role)
    {
        return hasRole(role) != true;
    }

    /**
     * 验证用户是否具有以下任意一个角色
     *
     * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
     * @return 用户是否具有以下任意一个角色
     */
    public boolean hasAnyRoles(String roles)
    {
        if (StringUtils.isEmpty(roles))
        {
            return false;
        }
//        LoginCompanyUser loginCompanyUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Object user = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(user))
        {
            return false;
        }
        String type = ServletUtils.getRequest().getHeader("X-Frontend-Type");
        if ("admin".equals(type)){
            LoginAdminUser loginUser =(LoginAdminUser) user;
            if (CollectionUtils.isEmpty(loginUser.getUser().getRoles())){
                return false;
            }
            for (String role : roles.split(ROLE_DELIMETER))
            {
                if (hasRole(role))
                {
                    return true;
                }
            }
        } else if("company".equals(type)){
            LoginCompanyUser loginUser =(LoginCompanyUser) user;
            if (CollectionUtils.isEmpty(loginUser.getUser().getRoles())){
                return false;
            }
            for (String role : roles.split(ROLE_DELIMETER))
            {
                if (hasRole(role))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission)
    {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }


}
