package com.jeequan.jeepay.bizcommons.manage.auth;

import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/***
 * 扫码登录
 *
 * @author zx
 * @date 2022/5/17 10:34
 */
@Slf4j
@Component
public class AuthByQrcodeManage {

    public final static String QRCODE_STATUS_WAITING = "waiting"; // 等待扫码
    public final static String QRCODE_STATUS_SCANED = "scaned"; // 已扫码
    public final static String QRCODE_STATUS_EXPRIED = "expried"; // 过期
    public final static String QRCODE_STATUS_CONFIRMED = "confirmed"; // 确认登录
    public final static String QRCODE_STATUS_CANCELED = "canceled"; // 取消登录

    // 设置web端二维码被扫状态，等待扫码
    public static void setQrcodeStatusWaiting(String qrcodeNo) {
        RedisUtil.setString(qrcodeNo, AuthByQrcodeManage.QRCODE_STATUS_WAITING, 60, TimeUnit.SECONDS);
    }

    // 清空web端二维码被扫状态
    public static void delQrcodeStatus(String qrcodeNo) {
        RedisUtil.del(qrcodeNo);
    }

    // 更新web端二维码被扫状态为：等待扫码 --> 已扫
    public static void updateQrcodeStatusWaiting2Scaned(String qrcodeNo) {

        String qrCodeStatus = RedisUtil.getString(qrcodeNo);
        if (StringUtils.isBlank(qrCodeStatus) || !qrCodeStatus.equals(AuthByQrcodeManage.QRCODE_STATUS_WAITING)) {
            throw new BizException("二维码无效，请刷新二维码后重新扫描");
        }

        RedisUtil.setString(qrcodeNo, AuthByQrcodeManage.QRCODE_STATUS_SCANED, 60, TimeUnit.SECONDS);
    }

    // 更新web端二维码被扫状态，已扫 --> 确认登录
    public static void updateQrcodeStatusScaned2Confirmed(String qrcodeNo, String tokenStr) {

        String dbQrCodeStatus = RedisUtil.getString(qrcodeNo);
        if (StringUtils.isBlank(dbQrCodeStatus) || !dbQrCodeStatus.equals(AuthByQrcodeManage.QRCODE_STATUS_SCANED)) {
            throw new BizException("二维码无效，请刷新二维码后重新扫描");
        }

        RedisUtil.setString(qrcodeNo, AuthByQrcodeManage.QRCODE_STATUS_CONFIRMED + "_" + tokenStr);
    }

    // 更新web端二维码被扫状态，已扫 --> 取消扫码登录
    public static void updateQrcodeStatusScaned2Canceled(String sysType, String qrcodeNo) {

        String dbQrCodeStatus = RedisUtil.getString(qrcodeNo);
        if (StringUtils.isBlank(dbQrCodeStatus) || !dbQrCodeStatus.equals(AuthByQrcodeManage.QRCODE_STATUS_SCANED)) {
            throw new BizException("二维码无效，请刷新二维码后重新扫描");
        }

        RedisUtil.setString(qrcodeNo, AuthByQrcodeManage.QRCODE_STATUS_CANCELED);
    }

}
