package com.qs.mp.web.controller.api.sms;

/**
 *
 * @describe 短信验证码API，支持登录、提现验证码发送，运营短信通知发送
 * @auther duota
 * @create 2021-09-3 16:17:48
 */

import cn.jsms.api.ValidSMSResult;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.jsms.JSMSUtils;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.sms.domain.SmsCode;
import com.qs.mp.sms.service.ISmsLogService;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Api("短信验证码服务")
@RestController
@RequestMapping("/api/v1/mp/*")
@Component
public class SmsController extends BaseApiController {

  @Autowired
  private ISmsLogService smsLogService;

  @RequestMapping(value = "/sms/sendSmsCode", method = RequestMethod.POST)
  @ResponseBody
  public AjaxResult sendSmsCode(@RequestBody SmsCode smsCode) {
    logger.info("sendSmsCode...mobile"+smsCode.getMobile() +" messageId"+smsCode.getMessageId()+" code:"+smsCode.getCode());
    String msgId = smsLogService.sendSmsVerifyCode(smsCode.getMobile());
    if (StringUtils.isNotBlank(msgId)) {
      return success("发送成功.",msgId);
    }
    return error("验证码发送失败.");
  }

  @RequestMapping(value = "/sms/authsend", method = RequestMethod.POST)
  @ResponseBody
  public AjaxResult authsend(@RequestBody SmsCode smsCode) {
    logger.info("sendSmsCode...mobile"+smsCode.getMobile() +" messageId"+smsCode.getMessageId()+" code:"+smsCode.getCode());
    String msgId = smsLogService.sendSmsVerifyCode(smsCode.getMobile());
    if (StringUtils.isNotBlank(msgId)) {
      return success("发送成功.",msgId);
    }
    return error("验证码发送失败.");
  }


  @RequestMapping(value = "/sms/validSmsCode", method = RequestMethod.POST)
  @ResponseBody
  public AjaxResult validSmsCode(@RequestBody SmsCode smsCode) {

    if(smsCode.getCode() == null || smsCode.getCode().length() != 6) {
      return error("请输入6位验证码");
    }

    ValidSMSResult res = JSMSUtils.sendValidSMSCode(smsCode.getMessageId(), smsCode.getCode());
    if (res != null) {
      if (res.getIsValid()) {
        return success(res.getIsValid());
      }
    }
    logger.error("code:"+smsCode.getCode()+" mesageId:"+smsCode.getMessageId());
    return error("验证码错误.");
  }

}
