package com.cool.store.service.login.impl;

import com.cool.store.dto.login.UserLoginDTO;
import com.cool.store.entity.login.UserLoginDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.SmsCodeTypeEnum;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.login.LoginBaseService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhangchenbiao
 * @FileName: SmsLoginService
 * @Description: 验证码登录实现类
 * @date 2021-07-16 11:45
 */
@Service("smsLoginServiceImpl")
@Slf4j
public class SmsLoginServiceImpl extends LoginBaseService {

    @Resource
    private RedisUtilPool redisUtilPool;

    @Override
    public ResponseResult userLogin(UserLoginDTO param, UserLoginDO userLoginDO) {
        String mobile = param.getMobile();
        String smsCode = param.getSmsCode();
        if (StringUtils.isBlank(smsCode)) {
            return ResponseResult.fail(ErrorCodeEnum.SMS_CODE_MISSING);
        }
        String smsCodeKey = SmsCodeTypeEnum.LOGIN + ":" + mobile;
        String code = redisUtilPool.getString(smsCodeKey);
        if (StringUtils.isBlank(code)) {
            return ResponseResult.fail(ErrorCodeEnum.SMS_CODE_EXPIRE);
        }
        if (!smsCode.equals(code)) {
            return ResponseResult.fail(ErrorCodeEnum.SMS_CODE_ERROR);
        }
        redisUtilPool.delKey(smsCodeKey);
        return ResponseResult.success(getUserLoginInfo(userLoginDO));
    }

}
