package controllers

import (
	"SSO/enums"
	"SSO/service"
	"SSO/utils"
)

type CodeController struct {
	BaseController
}

func (this *CodeController) Prepare() {
	this.EnableXSRF = false
}

func (this *CodeController) Post() {
	mobile := this.GetString("phone")
	aespass := this.GetString("aespass")
	utils.TraceLog("mobile:%v aespass:%v", mobile, aespass)
	if utils.CellPhoneRegexp().MatchString(mobile) == false {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
		this.ServeJSON()
		return
	}

	if err := service.SendVerificationCodeSMS(mobile, aespass); err != nil {
		this.Data["json"] = enums.MakeFailResponseJSON(err.Error(), 600)
		this.ServeJSON()
	} else {
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"msg": "短信发送成功,有效期为10分钟",
		})
		this.ServeJSON()
	}
}

func (this *CodeController) RegistCode() {
	mobile := this.GetString("phone")
	aespass := this.GetString("aespass")
	utils.TraceLog("mobile:%v aespass:%v", mobile, aespass)
	if utils.CellPhoneRegexp().MatchString(mobile) == false {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
		this.ServeJSON()
		return
	}

	if service.IsMobileRegister(mobile) == true {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMobileRegistered)
		this.ServeJSON()
		return
	}

	if err := service.SendVerificationCodeSMS(mobile, aespass); err != nil {
		this.Data["json"] = enums.MakeFailResponseJSON(err.Error(), 600)
		this.ServeJSON()
	} else {
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"msg": "短信发送成功,有效期为10分钟",
		})
		this.ServeJSON()
	}
}
