package v1

import (
	"bytes"
	"encoding/json"
	"github.com/astaxie/beego/validation"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
	sms "openapi/pkg/application/sms/service"
	"openapi/pkg/constant"
	protocol "openapi/pkg/domain"
	"openapi/pkg/infrastructure/utils"
	"openapi/pkg/port/beego/controllers"
)

type SmsController struct {
	controllers.BaseController
}

//短信验证码 SmsCode
// @router /smsCode [post]
func (this *SmsController) SmsCode() {
	var msg *protocol.ResponseMessage
	defer func() {
		this.Resp(msg)
	}()
	var request *protocol.SmsCodeRequest
	decoder := json.NewDecoder(bytes.NewBuffer(this.ByteBody))
	decoder.UseNumber()
	if err := decoder.Decode(&request); err != nil {
		log.Error(err)
		msg = protocol.BadRequestParam(1)
		return
	}
	if utils.IsProductEnv(constant.RunMode) {
		valid := validation.Validation{}
		if !valid.Mobile(request.Phone, "mobile").Ok {
			msg = protocol.BadRequestParam(1001)
			return
		}
	}
	header := controllers.GetRequestHeader(this.Ctx)
	msg = protocol.NewReturnResponse(sms.SmsCode(header, request))
}

//检查短信验证码 CheckSmsCode
// @router /checkSmsCode [post]
func (this *SmsController) CheckSmsCode() {
	var msg *protocol.ResponseMessage
	defer func() {
		this.Resp(msg)
	}()
	var request *protocol.CheckSmsCodeRequest
	decoder := json.NewDecoder(bytes.NewBuffer(this.ByteBody))
	decoder.UseNumber()
	if err := decoder.Decode(&request); err != nil {
		log.Error(err)
		msg = protocol.BadRequestParam(1)
		return
	}
	if utils.IsProductEnv(constant.RunMode) {
		valid := validation.Validation{}
		if !valid.Mobile(request.Phone, "mobile").Ok {
			msg = protocol.BadRequestParam(1002)
			return
		}
	}
	header := controllers.GetRequestHeader(this.Ctx)
	msg = protocol.NewReturnResponse(sms.CheckSmsCode(header, request))
}

//发送短信通知 sendSmsNotice
// @router /sendSmsNotice [post]
func (this *SmsController) SendSmsNotice() {
	var msg *protocol.ResponseMessage
	defer func() {
		this.Resp(msg)
	}()
	var request *protocol.SendSmsNoticeRequest
	decoder := json.NewDecoder(bytes.NewBuffer(this.ByteBody))
	decoder.UseNumber()
	if err := decoder.Decode(&request); err != nil {
		log.Error(err)
		msg = protocol.BadRequestParam(1)
		return
	}
	if utils.IsProductEnv(constant.RunMode) {
		valid := validation.Validation{}
		if !valid.Mobile(request.Phone, "mobile").Ok {
			msg = protocol.BadRequestParam(1002)
			return
		}
	}
	header := controllers.GetRequestHeader(this.Ctx)
	msg = protocol.NewReturnResponse(sms.SendSmsNotice(header, request))
}