package com.cirle.scientific.utils;

import com.cirle.scientific.constants.LoginConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author DeMin
 * @date 2022年06月13日 23:17
 */
@Slf4j
@Service
public class LoginUtil {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //判断用户是被顶掉导致的未登录还是正常的就是未登录替代
    public boolean isReplace(HttpServletRequest request,
                                    HttpServletResponse response,
                                    String memCard) {


        //如果当前的人登陆过cookie里有痕迹 memCard为空说明现在没有登录了 mvalue不为空说明再别的地方登录着呢
        //之所以用这个不用UserLoginUtil 是因为UserLoginUtil过滤器里取不到mValue(因为都退出了session和cookie都请了)
        String memCardOld = CookieUtil.getValueByCookie(request, LoginConsts.M_COOKIE_MEMCARD_KEY);

        String keyM = String.format(LoginConsts.M_LOGIN_USER_KEY, memCardOld);
        String mValue = stringRedisTemplate.opsForValue().get(keyM);
        log.info("isReplace mValue:{}", mValue);
        if(StringUtils.isBlank(mValue)){
            String keyPc = String.format(LoginConsts.PC_LOGIN_USER_KEY, memCardOld);
            mValue = stringRedisTemplate.opsForValue().get(keyPc);
        }

        log.info("isReplace memCard:{} memCardOld:{} mValue:{}", memCard, memCardOld, mValue);
        if (StringUtils.isBlank(memCard) && StringUtils.isNotBlank(memCardOld) && StringUtils.isNotBlank(mValue)) {
            log.info("isReplace memCardOld:{} ", memCardOld);
            CookieUtil.clearCookies(response, StringUtil.getdomain(request), "/", LoginConsts.M_COOKIE_MEMCARD_KEY);
            return true;
        }

        return false;

    }

}
