package com.cm.common.plugin.converter;

import com.cm.common.config.properties.OauthProperties;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.token.ClientTokenManager;
import com.cm.common.plugin.utils.RestTemplateUtil;
import com.cm.common.pojo.bos.RoleBO;
import com.cm.common.pojo.bos.RoleGrantedAuthority;
import com.cm.common.pojo.bos.UserInfoBO;
import com.cm.common.pojo.dtos.UserAttrInfoDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;

import java.io.IOException;
import java.util.*;

/**
 * @ClassName: UserAuthConverter
 * @Description: 重写用户认证
 * @Author: WangGeng
 * @Date: 2019/2/27 4:57 PM
 * @Version: 1.0
 **/
public class ClientUserAuthConverter implements UserAuthenticationConverter {

    private static final Logger LOG = LoggerFactory.getLogger(ClientUserAuthConverter.class);
    private RestTemplateUtil restTemplateUtil;
    private OauthProperties oauthProperties;

    public ClientUserAuthConverter() {
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        return new LinkedHashMap();
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        Object principal = map.get("user_name");
        if (!Objects.isNull(principal)) {
            Collection<GrantedAuthority> authorities = new LinkedHashSet<>();;
            Map<String, Object> userInfo = (Map<String, Object>) map.get("user_info");
            UserInfoBO userInfoBO = new UserInfoBO();
            userInfoBO.setUserId(userInfo.get("userId").toString());
            userInfoBO.setUserUsername(userInfo.get("username").toString());
            userInfoBO.setUserName(userInfo.get("userName").toString());
            userInfoBO.setUserPhone(userInfo.get("userPhone") == null ? "" : userInfo.get("userPhone").toString());
            userInfoBO.setUserAvatar(userInfo.get("userAvatar") == null ? "" : userInfo.get("userAvatar").toString());
            userInfoBO.setUserEmail(userInfo.get("userEmail") == null ? "" : userInfo.get("userEmail").toString());
            if (ISystemConstant.ADMIN.equals(principal.toString())) {
            } else {
                Map<String, Object> params = new HashMap<>(1);
                params.put(IApiConsts.ACCESS_TOKEN, ClientTokenManager.getInstance().getClientToken().getAccessToken());
                String result = this.restTemplateUtil.doGetFormNormal(String.format("%s/resource/user/getuserinfobyuserid/%s", oauthProperties.getOauthServer(), userInfoBO.getUserId()), params);
                if (Objects.isNull(result)) {
                    throw new IllegalArgumentException("系统错误");
                }
                try {
                    // 获取角色信息
                    ObjectMapper objectMapper = new ObjectMapper();
                    UserAttrInfoDTO userAttrInfoDTO = objectMapper.readValue(result, UserAttrInfoDTO.class);
                    userInfoBO.setDepartments(userAttrInfoDTO.getDepartments());
                    userInfoBO.setRoles(userAttrInfoDTO.getRoles());
                    userInfoBO.setGroups(userAttrInfoDTO.getGroups());
                    userInfoBO.setPositions(userAttrInfoDTO.getPositions());
                    userInfoBO.setDataAuthority(userAttrInfoDTO.getDataAuthority());
                    userInfoBO.setDataAuthorityUserIds(userAttrInfoDTO.getDataAuthorityUserIds());
                    userInfoBO.setBaseDepartmentIds(userAttrInfoDTO.getBaseDepartmentIds());
                } catch (IOException e) {
                    LOG.error(e.getMessage(), e);
                    throw new IllegalArgumentException("系统错误");
                }
            }
            principal = userInfoBO;
            LOG.debug("设置Token");
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        }
        return null;
    }

    /**
     * 设置权限
     *
     * @param roleBOs
     * @return
     */
    @Deprecated
    private Collection<GrantedAuthority> getAuthorities(List<RoleBO> roleBOs) {
        Set<GrantedAuthority> roleGrantedAuthoritySet = new LinkedHashSet<>();
        for (RoleBO roleBO : roleBOs) {
            RoleGrantedAuthority roleGrantedAuthority = new RoleGrantedAuthority(roleBO.getRoleId(), roleBO);
            roleGrantedAuthoritySet.add(roleGrantedAuthority);
        }
        return roleGrantedAuthoritySet;
    }

    public RestTemplateUtil getRestTemplateUtil() {
        return restTemplateUtil;
    }

    public void setRestTemplateUtil(RestTemplateUtil restTemplateUtil) {
        this.restTemplateUtil = restTemplateUtil;
    }

    public OauthProperties getOauthProperties() {
        return oauthProperties;
    }

    public void setOauthProperties(OauthProperties oauthProperties) {
        this.oauthProperties = oauthProperties;
    }
}
