package cn.quantgroup.xyqb.service.sms.impl;

import cn.quantgroup.sms.MsgParams;
import cn.quantgroup.sms.SmsSender;
import cn.quantgroup.tech.util.TechEnvironment;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.sms.ISmsService;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;


/**
 * @author mengfan.feng
 * @time 2015-07-25 18:47
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    private static SmsSender smsSender = null;
    @Value("${sms.is.debug}")
    private Boolean isDebug;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate<String, String> stringRedisTemplate;

    @Override
    @Synchronized
    public SmsSender getSmsSender() {
        if (null == smsSender) {
            smsSender = new SmsSender();
        }
        return smsSender;
    }


    /**
     * 24-“【信用钱包】么么哒，等您好久了~感谢您注册信用钱包，我们来给您送钱啦，点击提交借款申请，万元现金立即到手 s.xyqb.com/a”
     * 1005-“【信用钱包】等您好久了~感谢您的注册，尊享息费5折优惠。登录 s.xyqb.com/a 享更多优惠（合理消费，理性借贷）”
     *
     * @param phoneNo
     */
    @Override
    public void sendAfterRegister(String phoneNo) {
        try {
            MsgParams msgParams =
                    new MsgParams(Collections.singletonList(2), phoneNo, "1", "1005", Collections.emptyList());
            getSmsSender().sendMsg(msgParams);
            //smsSender.sendAndForget(new SendAndForgetMsg(Collections.emptyList(), "24", "1", phoneNo));
            log.info("注册完成，发送短信, phoneNo:{}", phoneNo);
        } catch (Exception e) {
            log.error("注册完成短信发送异常", e);
        }
    }

    @Override
    public void sendAfterRegister(String phoneNo, String contentId) {
        try {
            if (StringUtils.isBlank(contentId)) {
                contentId = "24";
            }
            MsgParams msgParams = new MsgParams(Collections.singletonList(2), phoneNo, "1", contentId,
                    Collections.emptyList());
            getSmsSender().sendMsg(msgParams);
            log.info("注册完成，发送短信, phoneNo:{}", phoneNo);
        } catch (Exception e) {
            log.error("注册完成短信发送异常", e);
        }
    }

    /**
     * 检查验证码是否正确
     */
    @Override
    public boolean verifyPhoneAndCode(String phoneNo, String verificationCode) {
        // 非生产环境直接跳过验证码检验
        if (!TechEnvironment.isPro()) {
            return true;
        }
        String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
        String randomCode = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(randomCode)) {
            return false;
        }
        String[] arr = randomCode.split(":");
        if (arr.length != Constants.VERIFICATION_LEN) {
            return false;
        }
        String uniqueId = arr[0];
        String code = arr[1];
        return confirmSms(verificationCode, uniqueId, code);
    }

    private boolean confirmSms(String smsVerificationCode, String unqiueId, String code) {
        try {
            MsgParams message = new MsgParams(Collections.singletonList(2), unqiueId);
            //MsgParams messageVoice = new MsgParams(Collections.singletonList(4), unqiueId);
            getSmsSender().confirmMsg(message);
            //getSmsSender().confirmMsg(messageVoice);
            //smsSender.confirmSmsResult("1", unqiueId);
            log.info("confirmMsg send success, uniqueId={}", unqiueId);
        } catch (Exception e) {
            log.info("短信验证向短信中心确认失效", e);
        }
        return StringUtils.equals(code, smsVerificationCode);
    }

    @Override
    public boolean needResendCode(String phoneNo) {
        return needResendCode(phoneNo, Constants.VERIFICATION_CODE_FINITE_COUNT,true);
    }

    @Override
    public boolean needResendCode(String phoneNo, Long threshold,boolean isDelTryCount) {

        String verificationCountKey = Constants.REDIS_VERIFICATION_COUNT + phoneNo;
        Long getVerificationCount = stringRedisTemplate.opsForHash().increment(verificationCountKey, Constants.REDIS_VERIFICATION_COUNT, 1);
        boolean needResend = getVerificationCount >= threshold;
        if (needResend) {
            if (isDelTryCount) {
                deleteCodeFromCache(phoneNo);
            } else {
                deleteOnlyCodeFromCache(phoneNo);
            }
        }
        return needResend;
    }

    @Override
    public void deleteCodeFromCache(String phoneNo) {
        String verificationCountKey = Constants.REDIS_VERIFICATION_COUNT + phoneNo;
        stringRedisTemplate.opsForHash().delete(verificationCountKey, Constants.REDIS_VERIFICATION_COUNT);

        deleteOnlyCodeFromCache(phoneNo);
    }

    @Override
    public void deleteOnlyCodeFromCache(String phoneNo) {
        String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
        stringRedisTemplate.delete(key);
    }

}
