package com.jeequan.jeepay.member.service;

import cn.hutool.core.util.IdUtil;
import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.db.entity.MemberInfo;
import com.jeequan.jeepay.member.config.SystemYmlConfig;
import com.jeequan.jeepay.member.secruity.JWTPayload;
import com.jeequan.jeepay.member.secruity.JWTUtils;
import com.jeequan.jeepay.member.secruity.JeeMemberDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 认证Service
 *
 * @modify zhuxiao
 * @date 2021-04-27 15:50
 */
@Slf4j
@Service
public class AuthService {

    @Autowired private SystemYmlConfig systemYmlConfig;
    @Autowired private UserDetailsService userDetailsService;

    // 通过 mbrId 登录
    public String authByMbrId(String mbrId, String existsCacheKey){
        return userDetailsProcess(userDetailsService.loadUserByUsername(mbrId), existsCacheKey);
    }

    /** 根据用户ID 删除用户缓存信息  **/
    public void delAuthentication(List<Long> sysUserIdList){
        if(sysUserIdList == null || sysUserIdList.isEmpty()){
            return ;
        }
        for (Long sysUserId : sysUserIdList) {
            Collection<String> cacheKeyList = RedisUtil.keys(CS.getCacheKeyToken(sysUserId, "*"));
            if(cacheKeyList == null || cacheKeyList.isEmpty()){
                continue;
            }
            for (String cacheKey : cacheKeyList) {
                RedisUtil.del(cacheKey);
            }
        }
    }

    /** 获取到userDetail之后的操作 **/
    public String userDetailsProcess(UserDetails userDetails, String existsCacheKey) {

        JeeMemberDetails jeeMemberDetails = (JeeMemberDetails) userDetails;

        //验证通过后 再查询用户角色和权限信息集合
        MemberInfo memberInfo = jeeMemberDetails.getMemberInfo();

        //生成token
        String cacheKey = StringUtils.isNotEmpty(existsCacheKey) ? existsCacheKey : CS.getCacheKeyToken(memberInfo.getMbrId(), IdUtil.fastUUID());

        //生成iToken 并放置到缓存
        jeeMemberDetails.setCacheKey(cacheKey);
        RedisUtil.set(cacheKey, jeeMemberDetails, JWTUtils.EXPIRED_TIME);  // 放置在redis，缓存时间10分钟,

        //将信息放置到Spring-security context中
        UsernamePasswordAuthenticationToken authenticationRest = new UsernamePasswordAuthenticationToken(jeeMemberDetails, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationRest);

        //返回JWTToken
        return JWTUtils.generateToken(new JWTPayload(jeeMemberDetails), systemYmlConfig.getJwtSecret());
    }

}
