package controllers

import (
	"time"

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

type ForgetPwdController struct {
	BaseController
}

// /password/forget [get]
func (this *ForgetPwdController) ForgetPassword() {
	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.SetTpl("new_main/forget_password.html")
}

// /password/modify [post]
// @param mobile:string
// @param code:string
// @param password:string
func (this *ForgetPwdController) ModifyPassword() {
	mobile := this.GetString("mobile")
	code := this.GetString("code")
	password := this.GetString("password")
	checkErr := this.checkParams(mobile, code, password)
	if checkErr != nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(checkErr)
		this.ServeJSON()
		return
	}

	modifyErr := service.ModifyPassword(mobile, password)
	if modifyErr != nil {
		utils.ErrorLog("修改mobile=%v的用户的密码时失败: %v", mobile, modifyErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		this.ServeJSON()
		return
	} else {
		// 修改成功后验证码就要使其失效
		redisClient := service.RedisClient()
		defer redisClient.Close()
		redisClient.Del("code_msg_" + mobile)

		this.Data["json"] = enums.MakeSuccessResponseJSON(nil)
		this.ServeJSON()
		return
	}
}

func (this *ForgetPwdController) checkParams(mobile string, code string, password string) *enums.SGJError {
	if utils.CellPhoneRegexp().MatchString(mobile) == false {
		return &enums.SGJError{Code: enums.ErrorCodeMobileFormat}
	}
	if len(code) == 0 {
		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
	}
	if len(password) == 0 {
		return &enums.SGJError{Code: enums.ErrorCodePasswordEmpty}
	}
	if service.IsMobileRegister(mobile) == false {
		return &enums.SGJError{Code: enums.ErrorCodeMobileNotExit}
	}
	redisClient := service.RedisClient()
	defer redisClient.Close()
	cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
	if cache_code != code {
		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
	}
	return nil
}
