package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.bean.result.SmsResponseResult;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.BasicVerifyCode;
import com.qmth.sop.business.entity.SysConfig;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.BasicVerifyCodeMapper;
import com.qmth.sop.business.service.BasicVerifyCodeService;
import com.qmth.sop.business.util.SmsSendUtil;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;

/**
 * <p>
 * 短信验证码记录表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-08-01
 */
@Service
public class BasicVerifyCodeServiceImpl extends ServiceImpl<BasicVerifyCodeMapper, BasicVerifyCode> implements BasicVerifyCodeService {

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    SmsSendUtil smsSendUtil;

    /**
     * 发送验证码
     *
     * @param mobileNumber
     * @param sysUser
     * @return
     */
    @Override
    public Boolean sendVeirfyCode(String mobileNumber, SysUser sysUser) {
        SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SYS_CODE_ENABLE);
        Optional.ofNullable(sysConfig).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("短信验证码启用开关未设置"));

        if (!Boolean.valueOf(sysConfig.getConfigValue())) {
            throw ExceptionResultEnum.ERROR.exception("短信验证码已关闭");
        }
        BasicVerifyCode basicVerifyCode = this.getOne(new QueryWrapper<BasicVerifyCode>().lambda().eq(BasicVerifyCode::getMobileNumber, mobileNumber).eq(BasicVerifyCode::getUserId, sysUser.getId()));
        if (Objects.nonNull(basicVerifyCode)) {
            Date oldCreateTime = new Date(basicVerifyCode.getCreateTime());
            SysConfig sysConfigSmsSendInterval = commonCacheService.addSysConfigCache(SystemConstant.CODE_SEND_INTERVAL);
            Optional.ofNullable(sysConfigSmsSendInterval).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置短信验证码发送间隔"));
            Integer sendInterval = Integer.parseInt(sysConfigSmsSendInterval.getConfigValue());
            if ((System.currentTimeMillis() - oldCreateTime.getTime()) < sendInterval * 1000) {
                throw ExceptionResultEnum.ERROR.exception("发送验证码过于频繁，请" + sendInterval + "秒之后再试");
            }
        }
        try {
            StringBuilder sb = new StringBuilder();
            sb.append((int) ((Math.random() * 9 + 1) * 1000));
            String verifyCode = sb.toString();

            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("code", verifyCode);

            // 调用短信发送公共接口
            SmsResponseResult smsResponseResult = smsSendUtil.sendSms(mobileNumber, SystemConstant.SMS_TPL_CODE, templateParam);

            if (SmsSendUtil.OK.equals(smsResponseResult.getCode())) {
                // 请求成功
                SysConfig sysConfigSmsExpiredTime = commonCacheService.addSysConfigCache(SystemConstant.CODE_EXPIRED_TIME);
                Optional.ofNullable(sysConfigSmsExpiredTime).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置短信验证码有效时间"));
                Integer codeExpiredTime = Integer.parseInt(sysConfigSmsExpiredTime.getConfigValue());
                if (Objects.isNull(basicVerifyCode)) {
                    basicVerifyCode = new BasicVerifyCode(sysUser.getId(), sysUser.getOrgId(), mobileNumber, SystemConstant.processMiniutePlus(Duration.ofMinutes(2)), codeExpiredTime, verifyCode);
                } else {
                    basicVerifyCode.updateVerifyCodeInfo(sysUser.getId(), sysUser.getOrgId(), SystemConstant.processMiniutePlus(Duration.ofMinutes(2)), codeExpiredTime, verifyCode);
                }
                this.saveOrUpdate(basicVerifyCode);
            } else {
                throw ExceptionResultEnum.ERROR.exception(smsResponseResult.getMessage());
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.ERROR.exception("请重新获取验证码");
        }
        return true;
    }
}
