package controllers

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

type MobileLoginController struct {
	BaseController
}

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

// /m/login/pwd [post]
// @param mobile:string
// @param password:string
// @param app_type:int
// @param ip:string
func (this *MobileLoginController) LoginByPwd() {
	appType, _ := this.GetInt("app_type")
	if appType != 3 { // 暂时只支持血透系统
		appType = 3
	}
	mobile := this.GetString("mobile")
	password := this.GetString("password")
	if len(mobile) == 0 || len(password) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
		this.ServeJSON()
		return
	}

	if service.IsPasswordRight(mobile, password) {
		// 只取最近被创建的 admin_role
		adminUser, getAdminErr := service.GetValidAdminUserByMobileReturnErr(mobile)
		if getAdminErr != nil {
			utils.ErrorLog("获取管理员失败：%v", getAdminErr)
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			this.ServeJSON()
			return
		} else if adminUser == nil {
			utils.ErrorLog("查找不到 mobile = %v 的用户", mobile)
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
			this.ServeJSON()
			return
		} else {
			appRole, getAppRoleErr := service.GetLastXTAdminRole(adminUser.Id, appType)
			if getAppRoleErr != nil {
				utils.ErrorLog("获取 app_role 失败：%v", getAppRoleErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if appRole == nil {
				utils.ErrorLog("该管理员没有开通或被授权 app_type = %v 的应用", appType)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}
			org, getOrgErr := service.GetOrgById(appRole.OrgId)
			if getOrgErr != nil {
				utils.ErrorLog("获取机构失败:%v", getOrgErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if org == nil {
				utils.ErrorLog("该机构不存在或被删除")
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}
			app, getAppErr := service.GetAppById(appRole.AppId)
			if getAppErr != nil {
				utils.ErrorLog("获取应用失败:%v", getAppErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if app == nil {
				utils.ErrorLog("该应用不存在或被删除")
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}
			subscibe, getSubscibeErr := service.GetOrgServeSubscibe(org.Id)
			if getSubscibeErr != nil {
				utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if subscibe == nil {
				now := time.Now()
				nextMonthDate := now.AddDate(0, 0, 30)
				subscibe = &models.ServeSubscibe{
					OrgId:       int64(org.Id),
					PeriodStart: now.Unix(),
					PeriodEnd:   nextMonthDate.Unix(),
					Status:      1,
					CreatedTime: now.Unix(),
					UpdatedTime: now.Unix(),
					State:       2,
				}
				createErr := service.CreateOrgServeSubscibe(subscibe)
				if createErr != nil {
					utils.ErrorLog("创建机构订阅信息失败：%v", createErr)
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					this.ServeJSON()
					return
				}
			}

			// 插入一条登录记录
			ip := this.GetString("ip")
			loginLog := &models.AdminUserLoginLog{
				AdminUserId: adminUser.Id,
				OrgId:       org.Id,
				AppId:       app.Id,
				IP:          ip,
				OperateType: 1,
				AppType:     int8(appType),
				CreateTime:  time.Now().Unix(),
			}
			if insertErr := service.InsertLoginLog(loginLog); insertErr != nil {
				utils.ErrorLog("为手机号为%v的用户插入一条登录记录失败：%v", mobile, insertErr)
			}

			this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
				"admin":    adminUser,
				"org":      org,
				"app":      app,
				"app_role": appRole,
				"subscibe": subscibe,
			})
			this.ServeJSON()
		}

	} else {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
		this.ServeJSON()
	}
}

// /m/login/code [post]
