package com.ytpm.config;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytpm.agent.view.AgentUserInfo;
import com.ytpm.constant.StrConstant;
import com.ytpm.dao.AgentUserMapper;
import com.ytpm.util.RedisService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 自定义Security上下文信息
 */
@Data
@Component
@Slf4j
public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {
    private Collection<? extends GrantedAuthority> defaultAuthorities =
            new ArrayList<>(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
    private UserDetailsService userDetailsService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private AgentUserMapper userMapper;

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap();
        response.put("username", authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey("user_name")) {
            String userName = (String) map.get("user_name");
            Object principal;
            Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);
            AgentUserInfo user = userMapper.getCurrentUserInfo(userName);
            if(Objects.isNull(user)){
                log.error("当前用户不存在，应该退出登录");
                return null;
            }
            String key = StrConstant.AGENT_USER_INFO_PRE + userName ;
            if (redisService.hasKey(key)) {
                String str = redisService.getStr(key);
                AgentUserInfo jwtUser = JSONObject.parseObject(str, AgentUserInfo.class);
                principal = jwtUser;
                authorities = jwtUser.getAuthorities();
            } else {
                AgentUserInfo jwtUser = new AgentUserInfo();
                BeanUtil.copyProperties(user,jwtUser);
                authorities = jwtUser.getAuthorities();
                principal = jwtUser;
                redisService.setStr(key, JSON.toJSONString(user));
            }
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        } else {
            return null;
        }
    }

    /**
     * 用户资源授权的方法重写  暂时未使用
     *
     * @param map
     * @return
     */
    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey("authorities")) {
            return this.defaultAuthorities;
        } else {
            Object authorities = map.get("authorities");
            if (authorities instanceof String) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
            } else if (authorities instanceof Collection) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection) authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }
        }
    }
}
