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

import com.aliyun.core.utils.StringUtils;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.dto.login.UserLoginDTO;
import com.cool.store.entity.login.UserLoginDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.login.LoginBaseService;
import com.cool.store.utils.Md5Utils;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.constant.Constants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.time.LocalDate;

/**
 * <p>
 * 密码登录服务实现类
 * </p>
 *
 * @author wangff
 * @since 2025/9/4
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PasswordLoginServiceImpl extends LoginBaseService {
    private final RedisUtilPool redisUtilPool;

    @Override
    public ResponseResult userLogin(UserLoginDTO param, UserLoginDO userLoginDO) {
        if (StringUtils.isBlank(param.getPassword())) {
            return ResponseResult.fail(ErrorCodeEnum.PASSWORD_MISSING);
        }
        if (StringUtils.isBlank(userLoginDO.getPassword())) {
            return ResponseResult.fail(ErrorCodeEnum.IMPROVE_USER_INFO);
        }
        String password = Md5Utils.md5(param.getPassword() + CommonConstants.USER_AUTH_KEY);
        if (!password.equals(userLoginDO.getPassword())) {
            String errorPasswordCountKey = MessageFormat.format(RedisConstant.ERROR_PASSWORD_COUNT_KEY, LocalDate.now(), param.getMobile());
            Long errorNum = redisUtilPool.incrby(errorPasswordCountKey, 1);
            redisUtilPool.expire(errorPasswordCountKey, 24 * 60 * 60);
            if(errorNum == 1){
                return ResponseResult.fail(ErrorCodeEnum.PASSWORD_ERROR);
            }
            return ResponseResult.fail(ErrorCodeEnum.PASSWORD_ERROR_MULTI, errorNum.toString());
        }
        return ResponseResult.success(getUserLoginInfo(userLoginDO));
    }
}
