package controllers

import (
	"fmt"
	"time"

	"github.com/astaxie/beego"

	"SSO/enums"
	"SSO/service"
	"SSO/utils"
)

type RegisterController struct {
	BaseController
}

// /register [get]
func (this *RegisterController) Register() {
	mobile := this.GetString("mobile")
	redisClient := service.RedisClient()
	defer redisClient.Close()
	req := this.Ctx.Request
	addr := utils.GetIP(req)
	cur_time := time.Now().Format("2006-01-02")
	_, err := redisClient.Get("ip:host_" + cur_time + "_" + addr).Result()
	if err != nil {
		redisClient.Set("ip:host_"+cur_time+"_"+addr, 0, time.Second*24*60*60)
	}

	//将客户端的ip加密传给前端，作为短信验证的密钥，来验证短信发送的IP地址
	aespass := utils.AESEncrypt(addr)
	returnURL := this.GetString("return_url")
	this.Data["return_url"] = returnURL
	this.Data["aespass"] = aespass
	this.Data["mobile"] = mobile
	this.SetTpl("new_main/register.html")
}

// /register/submit [post]
func (this *RegisterController) RegisterSubmit() {
	mobile := this.GetString("phone")
	pwd := this.GetString("password")
	code := this.GetString("code")

	// 判断手机号是否存在
	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 len(pwd) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePasswordEmpty)
		this.ServeJSON()
		return
	}
	if len(code) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
		this.ServeJSON()
		return
	}
	redisClient := service.RedisClient()
	defer redisClient.Close()
	cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
	if cache_code != code {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
		this.ServeJSON()
		return
	}

	admin, err := service.RegisterSuperAdmin(mobile, pwd)
	if err != nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
		this.ServeJSON()
		return

	} else {
		// 保存登录令牌
		token := utils.GenerateLoginToken(mobile)
		expiration, _ := beego.AppConfig.Int64("login_token_expiration_second")
		this.Ctx.SetCookie("sso_token_cookie", token, expiration)
		if isDebuggingSSO, _ := beego.AppConfig.Bool("is_sso_use_session_id_key"); isDebuggingSSO {
			share_session_id := this.Ctx.Input.CruSession.SessionID()
			this.Ctx.SetCookie("s", share_session_id, expiration, "/", beego.AppConfig.String("cookie_rootdomain"))
			redisClient.Set(fmt.Sprintf("sso_token_%v", share_session_id), token, time.Duration(expiration)*time.Second)

		} else {
			redisClient.Set(fmt.Sprintf("sso_token_%v", mobile), token, time.Duration(expiration)*time.Second)
		}

		this.SetSession("admin_user", admin)

		// 注册成功后验证码就要使其失效
		redisClient.Del("code_msg_" + mobile)

		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"result": true,
			"id":     admin.Id,
		})
		this.ServeJSON()
		return
	}
}
