package com.ytpm.middle.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytpm.constant.StrConstant;
import com.ytpm.handle.CustomerException;
import com.ytpm.middle.dao.MiddleUserMapper;
import com.ytpm.middle.dao.PermissionMapper;
import com.ytpm.middle.param.MiddlePermissionParam;
import com.ytpm.middle.util.RedisUtil;
import com.ytpm.middle.view.MiddleRoleVO;
import com.ytpm.middle.view.MiddleUserInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

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

    @Resource
    private RedisUtil redisService;
    @Resource
    private MiddleUserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @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;
            this.getAuthorities(map);
            Collection<? extends GrantedAuthority> authorities;
            MiddleUserInfo user = userMapper.getByLoginName(userName);
            if(Objects.isNull(user)){
                log.error("当前用户不存在，应该退出登录");
                throw new CustomerException("用户登录失效，请重新登录！");
            }
            String key = StrConstant.ADS_USER_INFO_PRE + userName ;
            if (Boolean.TRUE.equals(redisService.hasKey(key))) {
                String str = redisService.getStr(key);
                MiddleUserInfo jwtUser = JSONObject.parseObject(str, MiddleUserInfo.class);
                principal = jwtUser;
                authorities = jwtUser.getAuthorities();
            } else {
                List<MiddleRoleVO> roleList;
                if(1==user.getSuperAdmin()){
                    roleList = userMapper.getSuperAdmin();
                    user.setRoleList(roleList);
                    user.setPermissionList(permissionMapper.queryAll(new MiddlePermissionParam()));
                }else{
                    roleList = userMapper.getRoleList(user.getUserId());
                    if(CollUtil.isEmpty(roleList)){
                        throw new CustomerException("用户权限不足!");
                    }
                    user.setRoleList(roleList);
                    List<Integer> roleIdList = roleList.stream()
                            .map(MiddleRoleVO::getRoleId).collect(Collectors.toList());
                    user.setPermissionList(permissionMapper.queryAllByRoleIds(roleIdList));
                }
                MiddleUserInfo jwtUser = new MiddleUserInfo();
                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;
        }
    }

    /**
     * 用户资源授权的方法重写
     */
    private void getAuthorities(Map<String, ?> map) {
        if (map.containsKey("authorities")){
            Object authorities = map.get("authorities");
            if (authorities instanceof String) {
                AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
            } else if (authorities instanceof Collection) {
                AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }
        }
    }
}
