package com.qmth.paper.library.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.common.config.DictionaryConfig;
import com.qmth.paper.library.common.contant.SysSettingConstant;
import com.qmth.paper.library.common.entity.BasicVerifyCode;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.mapper.BasicVerifyCodeMapper;
import com.qmth.paper.library.common.service.BasicVerifyCodeService;
import com.qmth.paper.library.common.service.CommonCacheService;
import com.qmth.paper.library.common.util.CodeUtil;
import com.qmth.paper.library.common.util.SmsSendUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

    @Resource
    private DictionaryConfig dictionaryConfig;

    @Resource
    private CommonCacheService commonCacheService;

    @Resource
    private SmsSendUtil smsSendUtil;

    @Override
    public void sendVeirfyCode(String mobileNumber, SysUser sysUser) {
        String verificationCodeLoginEnable = commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_VERIFICATION_CODE_LOGIN_ENABLE);
        if (verificationCodeLoginEnable == null) {
            throw ExceptionResultEnum.ERROR.exception("短信验证码启用开关未设置");
        }
        if (verificationCodeLoginEnable.equals("false") || verificationCodeLoginEnable.equals("0")) {
            throw ExceptionResultEnum.ERROR.exception("短信验证码已关闭");
        }
        QueryWrapper<BasicVerifyCode> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BasicVerifyCode::getMobileNumber, mobileNumber).eq(BasicVerifyCode::getUserId, sysUser.getId());
        BasicVerifyCode basicVerifyCode = this.getOne(wrapper);
        if (basicVerifyCode != null) {
            Date oldCreateTime = new Date(basicVerifyCode.getCreateTime());
            Integer sendInterval = Integer.valueOf(commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_VERIFICATION_CODE_SEND_INTERVAL));
            if ((System.currentTimeMillis() - oldCreateTime.getTime()) < sendInterval * 1000) {
                throw ExceptionResultEnum.ERROR.exception("发送验证码过于频繁，请" + sendInterval + "秒之后再试");
            }
        }
        try {
            // 验证码
            String normalCode = dictionaryConfig.smsDomain().getSmsNormalCode();
            String verifyCode = CodeUtil.getVerificationCode(normalCode);

            String templateCode = dictionaryConfig.smsDomain().getVerificationCode();
            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("code", verifyCode);
            String bizId = smsSendUtil.sendSms(mobileNumber, templateCode, templateParam);

            if (StringUtils.isNotBlank(bizId)) {
                // 请求成功
                Integer codeExpiredTime = Integer.valueOf(commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_VERIFICATION_CODE_EXPIRED_TIME));
                if (basicVerifyCode == null) {
                    basicVerifyCode = new BasicVerifyCode();
                    basicVerifyCode.setUserId(sysUser.getId());
                    basicVerifyCode.setSchoolId(sysUser.getSchoolId());
                    basicVerifyCode.setMobileNumber(mobileNumber);
                    basicVerifyCode.setExpireTime(processMiniute(new Date(), codeExpiredTime));
                    basicVerifyCode.setValidPeriod(codeExpiredTime);
                    basicVerifyCode.setVerifyCode(verifyCode);
                    basicVerifyCode.setCreateId(sysUser.getId());
                    basicVerifyCode.setCreateTime(System.currentTimeMillis());
                    this.save(basicVerifyCode);
                } else {
                    basicVerifyCode.setExpireTime(processMiniute(new Date(), codeExpiredTime));
                    basicVerifyCode.setValidPeriod(codeExpiredTime);
                    basicVerifyCode.setVerifyCode(verifyCode);
                    basicVerifyCode.setUpdateId(sysUser.getId());
                    basicVerifyCode.setUpdateTime(System.currentTimeMillis());
                    this.updateById(basicVerifyCode);
                }
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("请重新获取验证码：" + e.getMessage());
        }
    }

    private static Long processMiniute(Date oldTime, int m) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(oldTime);
        calendar.add(Calendar.MINUTE, m);
        return calendar.getTime().getTime();
    }
}
