package com.fdkankan.web.user;

import com.fdkankan.common.constant.LoginType;
import com.fdkankan.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SSOLoginHelper {

    @Autowired
    private SSOLoginStore ssoLoginStore;

    public SSOUser loginCheck(String token) {
        if (token != null && token.trim().length() > 0) {
            SSOUser ssoUser = ssoLoginStore.get(token);
            if (ssoUser != null) {
                return ssoUser;
            }
        }
        return null;
    }

    public SSOUser getSsoUser(String token) {
        if (token != null && token.trim().length() > 0) {
            SSOUser ssoUser = ssoLoginStore.getSsoUser(token);
            if (ssoUser != null) {
                return ssoUser;
            }
        }
        return null;
    }

    public SSOUser loginCheckV3(String token) {
        if (token != null && token.trim().length() > 0) {
            SSOUser ssoUser = ssoLoginStore.getSsoUser(token);
            if (ssoUser != null) {
                return ssoUser;
            }
        }
        return null;
    }

    public String login(String loginType,String userName) {
        return this.login(loginType,userName,null, null);
    }
    public String login(String loginType,String userName,Integer time) {
        return this.login(loginType,userName,time, null);
    }
    public String login(SSOUser ssoUser) {
        String loginType = LoginType.USER.code();
        String userName = ssoUser.getUserName();
        return this.login(loginType,userName,null, ssoUser);
    }
    public String login(SSOUser ssoUser,Integer time) {
        String loginType = LoginType.USER.code();
        String userName = ssoUser.getUserName();
        return this.login(loginType,userName,time, ssoUser);
    }

    /**
     * @param loginType     登录类型
     * @param userName      登录用户名
     * @param time          过期时间，时间单位为秒，默认为 6小时 21600
     * @param ssoUser       sooUser
     */
    public String login(String loginType,String userName,Integer time,
        SSOUser ssoUser) {
        String token = JwtUtil.createJWT(-1, userName,loginType);
        ssoLoginStore.put(loginType,userName,token,time, ssoUser);
        return token;
    }

    public  void logout(String token) {
        String username = JwtUtil.getUsername(token);
        String loginType = JwtUtil.getLoginType(token);
        this.logout(loginType,username);
    }
    public  void logout(String loginType,String userName) {
        ssoLoginStore.remove(loginType,userName);
    }

    public void loginV3(String token, com.fdkankan.web.model.SSOUser ssoUser) {
        ssoLoginStore.putV3(token, ssoUser);
    }

}
