package com.sptg.gateway.receiver;

import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.AccountAuthenticationFeign;
import com.sptg.permissions.api.stream.SyncAccountReceiverInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * title: SyncAccountReceiver
 * description: 同步账号信息消费者
 *
 *                  
 *            
 */

@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { SyncAccountReceiverInterface.class})
public class SyncAccountReceiver {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final AccountAuthenticationFeign accountAuthenticationFeign;

    @StreamListener(value = SyncAccountReceiverInterface.INPUT)
    public void input(Long accountId){
        if (null == accountId){
            return;
        }
        //  获取需要更新的账号缓存
        List<Account> onLineUserList = this.securityServiceInterface.getOnLineUserList();
        for (Account onLineUser : onLineUserList){
            if (onLineUser.getId().equals(accountId)){
                //  获取最新的账号的信息
                Account account = this.accountAuthenticationFeign.reload(accountId);
                if (null == account){
                    //  用户已经被删除或不可用，强制退出
                    this.securityServiceInterface.removeUserToken(onLineUser.getLoginToken());
                }else {
                    //  更新账号缓存
                    account.setLoginToken(onLineUser.getLoginToken());
                    this.securityServiceInterface.updateAccount(account);
                }
                break;
            }
        }
    }

}
