package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.result.SmsResponseResult;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicVerifyCode;
import com.qmth.teachcloud.common.entity.SysConfig;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.mapper.BasicVerifyCodeMapper;
import com.qmth.teachcloud.common.service.BasicVerifyCodeService;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.SysConfigService;
import com.qmth.teachcloud.common.util.SmsSendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

    @Autowired
    private SysConfigService sysConfigService;

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    SmsSendUtil smsSendUtil;

    @Override
    public void sendVeirfyCode(String mobileNumber, SysUser sysUser) {
        SysConfig sysConfig = sysConfigService.getByKey(SystemConstant.SYS_CODE_ENABLE);
        if (sysConfig.getConfigValue() == null) {
            throw ExceptionResultEnum.ERROR.exception("短信验证码启用开关未设置");
        }
        if (sysConfig.getConfigValue().equals("false")) {
            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());
            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 (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);
                }
            } else {
                throw ExceptionResultEnum.ERROR.exception(smsResponseResult.getMessage());
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("请重新获取验证码");
        }
    }

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