package cn.axzo.msg.center.notices.service.impl;

import cn.axzo.basics.common.exception.ServiceException;
import cn.axzo.msg.center.notices.service.SmsService;
import cn.axzo.msg.center.notices.service.manager.SmsManager;
import cn.axzo.msg.center.notices.service.request.CodeStatusReq;
import cn.axzo.msg.center.notices.service.request.SendCodeV2Req;
import cn.axzo.msg.center.notices.service.response.CodeStatusRes;
import cn.axzo.msg.center.notices.service.response.SendCodeRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
@RefreshScope
public class SmsServiceImpl implements SmsService {

    @Value("${phone.whites}")
    private List<String> phoneWrites;
    @Value("${phone.returnCode}")
    private Boolean returnCode;
    @Resource
    private SmsManager smsManager;

    @Override
    public SendCodeRes sendPhoneCodeV2(SendCodeV2Req req) {
        SendCodeRes result = new SendCodeRes();
        // 发送验证码
        int code = smsManager.sendSmsCode(req);
        result.setCode(code);
        return result;
    }



    @Override
    public CodeStatusRes getPhoneCodeStatus(CodeStatusReq req) {
        CodeStatusRes res = new CodeStatusRes();
        // 手机号再白名单中存在 则不验证
        if (phoneWrites.contains(req.getPhoneNumber())) {
            return res;
        }
        Integer code = smsManager.getSmsCode(req.getPhoneNumber(), String.valueOf(req.getType()));
        Long second = smsManager.getSmsCodeSsl(req.getPhoneNumber(), String.valueOf(req.getType()));
        // 判断验证码
        if (!StringUtils.isEmpty(req.getCode())) {
            if (!(code + "").equals(req.getCode())) {
                throw new ServiceException("验证码不正确");
            }
        } else if (code != null && second != 0L) {
            throw new ServiceException("发送频繁, 请" + second + "秒后再试");
        }
        return res;
    }
}
