package com.storlead.sms.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.storlead.framework.common.constant.RedisKeySaltConstant;
import com.storlead.framework.common.util.RandomCodeUtil;
import com.storlead.framework.redis.RedisService;
import com.storlead.framework.web.assemble.Result;
import com.storlead.framework.web.enums.ErrorMsgCode;
import com.storlead.sms.constants.SmsTemplateConstants;
import com.storlead.sms.exception.SMSException;
import com.storlead.sms.mapper.SmsLogMapper;
import com.storlead.sms.pojo.entity.SmsLogEntity;
import com.storlead.sms.service.SmsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 短信日志 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2022-05-27
 */
@Service
public class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLogEntity> implements SmsLogService {

    @Autowired
    private RedisService redisService;



    @Override
    public Result sendLoginSmsCode(String mobile) throws ClientException, SMSException {
        //
        int count = this.count(new LambdaQueryWrapper<SmsLogEntity>().eq(SmsLogEntity::getMobile,mobile).eq(SmsLogEntity::getType,Integer.valueOf(10)).apply(" TO_DAYS(send_time) = TO_DAYS(NOW()) "));
        if (count >= SmsTemplateConstants.SEND_MAXIMIZE) {
            return Result.error(ErrorMsgCode.D_400001);
        }
        Object var1 = redisService.getCacheObject(RedisKeySaltConstant.REDIS_LOGIN_VALID_CODE_KEY+mobile);
        if (Objects.nonNull(var1)) {
            SmsLogEntity smsLog = (SmsLogEntity) var1;
            Long currentTime = System.currentTimeMillis();
            Long sendTime = smsLog.getSendTime().getTime();
            if ((currentTime - sendTime) / 1000 < smsLog.getValidTime()) {
                return Result.error(ErrorMsgCode.D_400002);
            }
        }
        int checkCode = RandomCodeUtil.RandomCheckCode();

        try {
            boolean res = sendMobileVerifyCode(mobile, checkCode);
            if (!res) {
                return Result.error(ErrorMsgCode.D_400003);
            }
            log.error("SmsLog ---- = "+checkCode);
            SmsLogEntity smsLog = new SmsLogEntity();
            smsLog.setVerifyCode(String.valueOf(checkCode));
            smsLog.setMobile(mobile);
            smsLog.setType(Integer.valueOf(10));
            //无需关注id  验证的是手机号码
            smsLog.setUserId(null);
            smsLog.setValidTime(60);
            smsLog.setSendTime(new Date());
            smsLog.setStatus(1);
            this.baseMapper.insert(smsLog);
            redisService.setCacheObject(RedisKeySaltConstant.REDIS_LOGIN_VALID_CODE_KEY+mobile,smsLog,120L, TimeUnit.MINUTES);
        } catch (ClientException e) {
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }


    /**
     * 发送手机验证码短信
     *
     * @param mobile    手机
     * @param checkCode 验证码
     */
    public boolean sendMobileVerifyCode(String mobile, Integer checkCode) throws ClientException {
        return true;
        // return SmsUtil.sendSms(smsProperties.getSmsCheckCodeTemplate(), JSON.toJSONString(ImmutableMap.of("number", checkCode)), mobile,smsProperties.getSmsAccessKeyId(),smsProperties.getSmsAccessKeyIdSecret());
    }
}
