package controllers

import (
	"SSO/enums"
	"SSO/models"
	"SSO/service"
	"SSO/utils"
	"encoding/json"
	"time"
)

type MobileRegistController struct {
	BaseController
}

// /mobile/regist [get]
func (this *MobileRegistController) 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)
	this.Data["aespass"] = aespass
	this.Data["mobile"] = mobile
	this.SetTpl("mobile_site/regist.html")
}

// /mobile/regist/submit [post]
// @param mobile:string
// @param password:string
// @param code:string
func (this *MobileRegistController) RegistSubmit() {
	mobile := this.GetString("mobile")
	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 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
	}
	if service.IsMobileRegister(mobile) == true {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMobileRegistered)
		this.ServeJSON()
		return
	}

	redisClient := service.RedisClient()
	defer redisClient.Close()
	// if strings.HasPrefix(mobile, "12") {
	// 	if code != "123456" {
	// 		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
	// 		this.ServeJSON()
	// 		return
	// 	}

	// } else {
	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()

	} else {
		this.Ctx.SetCookie("mobile", mobile)
		this.SetSession("mobile_admin_user", admin)

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

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

// /mobile/org/create [get]
func (this *MobileRegistController) CreateOrg() {
	adminUserObj := this.GetSession("mobile_admin_user")
	if adminUserObj == nil {
		this.Redirect302("/mobile/regist")
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
		utils.ErrorLog("检查id = %v的用户是否创建了机构时出错：%v", adminUser.Id, checkCreateOrgErr)
		this.Abort("404")
		return
	} else {
		if didCreateOrg {
			this.Redirect302("/mobile/finish")
			return
		}
	}

	cats, getCatErr := service.GetOrgCategoriesByPid(0)
	if getCatErr != nil {
		utils.ErrorLog("获取机构类型失败：%v", getCatErr)
		this.Abort("404")
		return
	}

	catsJSON, _ := json.Marshal(cats)
	this.Data["categories"] = string(catsJSON)

	this.SetTpl("mobile_site/create_org.html")
}

// /mobile/org/create/submit [post]
// @param name:string
// @param province:string 省名
// @param city:string 市名
// @param district:string 区县
// @param address:string
// @param category:int
// @param contact_name:string
// @param org_phone?:string
// @param open_xt?:bool 是否开启血透系统
// @param open_cdm?:bool 是否开启慢病系统
// @param open_scrm?:bool 是否开启SCRM
// @param open_mall?:bool 是否开启Mall
func (this *MobileRegistController) CreateOrgSubmit() {
	adminUserObj := this.GetSession("mobile_admin_user")
	if adminUserObj == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
		this.ServeJSON()
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)

	if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else if didCreateOrg {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg)
		this.ServeJSON()
		return
	}
	user_name := this.GetString("user_name")

	name := this.GetString("name")
	shortName := name
	provinceName := this.GetString("province")
	cityName := this.GetString("city")
	districtName := this.GetString("district")
	address := this.GetString("address")
	category, _ := this.GetInt64("category")
	contactName := this.GetString("contact_name")
	openXT, _ := this.GetBool("open_xt")
	openCDM, _ := this.GetBool("open_cdm")
	openSCRM, _ := this.GetBool("open_scrm")
	openMall, _ := this.GetBool("open_mall")
	if len(name) == 0 || len(shortName) == 0 || len(contactName) == 0 || len(address) == 0 || len(provinceName) <= 0 || len(cityName) <= 0 || len(districtName) <= 0 || category <= 0 || (!openXT && !openCDM && !openSCRM && !openMall) {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		this.ServeJSON()
		return
	}
	orgPhone := this.GetString("org_phone")

	if len(orgPhone) > 0 {
		if utils.CellPhoneRegexp().MatchString(orgPhone) == false {
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			this.ServeJSON()
			return
		}
	}

	provinceID := 0
	cityID := 0
	districtID := 0

	province, getProvinceErr := service.GetProvinceWithName(provinceName)
	if getProvinceErr != nil {
		utils.ErrorLog("查询省名失败：%v", getProvinceErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else if province != nil {
		provinceID = int(province.Id)
		city, getCityErr := service.GetCityWithName(province.Id, cityName)
		if getCityErr != nil {
			utils.ErrorLog("查询城市名失败：%v", getCityErr)
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			this.ServeJSON()
			return
		} else if city != nil {
			cityID = int(city.Id)
			district, getDistrictErr := service.GetDistrictWithName(city.Id, districtName)
			if getDistrictErr != nil {
				utils.ErrorLog("查询区县名失败：%v", getDistrictErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if district != nil {
				districtID = int(district.Id)
			}
		}
	}

	org := models.Org{
		Creator:      adminUser.Id,
		OrgName:      name,
		OrgShortName: shortName,
		Province:     provinceID,
		City:         cityID,
		District:     districtID,
		Address:      address,
		OrgType:      category,
		Telephone:    orgPhone,
		ContactName:  contactName,
		Claim:        1,
		Evaluate:     5,
		Status:       1,
		CreateTime:   time.Now().Unix(),
		ModifyTime:   time.Now().Unix(),
	}

	createErr := service.CreateOrg(&org, user_name, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app，如果有新类型的平台，则需要在这个方法里面把创建这一新类型的 app 的代码加上
	if createErr != nil {
		utils.ErrorLog("mobile=%v的超级管理员创建机构失败：%v", adminUser.Mobile, createErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		this.ServeJSON()
	} else {
		this.Ctx.SetCookie("org_name", name)
		this.SetSession("mobile_org", &org)
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
		this.ServeJSON()
	}
}

// /mobile/finish [get]
func (this *MobileRegistController) Finish() {
	adminUserObj := this.GetSession("mobile_admin_user")
	orgObj := this.GetSession("mobile_org")
	if adminUserObj == nil || orgObj == nil {
		this.Redirect302("/")
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	org := orgObj.(*models.Org)

	this.Data["mobile"] = adminUser.Mobile
	this.Data["org_name"] = org.OrgName
	this.SetTpl("mobile_site/close.html")
}
