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 {

			//优先获取最近登录的数据，没有登录的话获取被邀请的用户数据，如果既没有登录信息，也没有用户信息则属于全新用户，

			loginLogs, _ := service.GetLastXTAdminRoleLoginRole(adminUser.Id, appType)
			var appRole *models.App_Role
			var org *models.Org
			var subscibe *models.ServeSubscibe
			var app *models.OrgApp

			if loginLogs == nil { //登录信息不存在,获取被邀请的用户
				tempAppRole, 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
				}
				appRole = tempAppRole

				if appRole == nil { //如果用户信息不存在，说明没有创建机构和用户信息
					org = nil
					subscibe = nil
					app = nil

				} else { //用户信息存在则可能属于被邀请的

					tempOrg, getOrgErr := service.GetOrgById(appRole.OrgId)
					if getOrgErr != nil {
						utils.ErrorLog("获取机构失败:%v", getOrgErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}

					tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
					if getSubscibeErr != nil {
						utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}

					tempApp, getAppErr := service.GetOrgApp(tempOrg.Id, appType)
					if getAppErr != nil {
						utils.ErrorLog("获取应用失败：%v", getAppErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}

					subscibe = tempSubscibe
					org = tempOrg
					app = tempApp
				}

			} else {
				//根据登录信息的机构和用户id，去获取对应用户信息和机构信息
				tempApp, _ := service.GetOrgApp(loginLogs.OrgId, appType)
				tempRole, _ := service.GetAppRole(adminUser.Id, loginLogs.OrgId, tempApp.Id)
				if tempRole.Status != 1 {
					admin_user_info, _ := service.GetLastUserRole(int64(loginLogs.OrgId), int64(adminUser.Id))
					tempRole = admin_user_info
					app, _ := service.GetOrgApp(tempRole.OrgId, 3)
					tempApp = app

					tempOrg, getOrgErr := service.GetOrgById(tempRole.OrgId)
					if getOrgErr != nil {
						utils.ErrorLog("获取机构失败:%v", getOrgErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}
					tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
					if getSubscibeErr != nil {
						utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}

					subscibe = tempSubscibe
					org = tempOrg
					appRole = tempRole
					app = tempApp

				} else {
					tempOrg, getOrgErr := service.GetOrgById(loginLogs.OrgId)
					if getOrgErr != nil {
						utils.ErrorLog("获取机构失败:%v", getOrgErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}
					tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
					if getSubscibeErr != nil {
						utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						this.ServeJSON()
						return
					}
					subscibe = tempSubscibe
					org = tempOrg
					appRole = tempRole
					app = tempApp
				}
			}

			if org != nil && appRole != nil {
				// 插入一条登录记录
				ip := this.GetString("ip")
				loginLog := &models.AdminUserLoginLog{
					AdminUserId: adminUser.Id,
					OrgId:       org.Id,
					AppId:       appRole.AppId,
					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()
	}
}

func (this *MobileLoginController) LoginByCode() {
	appType, _ := this.GetInt("app_type")
	if appType != 3 { // 暂时只支持血透系统
		appType = 3
	}
	mobile := this.GetString("mobile")
	if len(mobile) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
		this.ServeJSON()
		return
	}

	// 只取最近被创建的 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 {

		//优先获取最近登录的数据，没有登录的话获取被邀请的用户数据，如果既没有登录信息，也没有用户信息则属于全新用户，

		loginLogs, _ := service.GetLastXTAdminRoleLoginRole(adminUser.Id, appType)
		var appRole *models.App_Role
		var org *models.Org
		var subscibe *models.ServeSubscibe
		var app *models.OrgApp

		if loginLogs == nil { //登录信息不存在,获取被邀请的用户
			tempAppRole, 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
			}
			appRole = tempAppRole

			if appRole == nil { //如果用户信息不存在，说明没有创建机构和用户信息
				org = nil
				subscibe = nil
				app = nil

			} else { //用户信息存在则可能属于被邀请的

				tempOrg, getOrgErr := service.GetOrgById(appRole.OrgId)
				if getOrgErr != nil {
					utils.ErrorLog("获取机构失败:%v", getOrgErr)
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					this.ServeJSON()
					return
				}

				tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
				if getSubscibeErr != nil {
					utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					this.ServeJSON()
					return
				}

				tempApp, getAppErr := service.GetOrgApp(tempOrg.Id, appType)
				if getAppErr != nil {
					utils.ErrorLog("获取应用失败：%v", getAppErr)
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					this.ServeJSON()
					return
				}

				subscibe = tempSubscibe
				org = tempOrg
				app = tempApp
			}

		} else {
			//根据登录信息的机构和用户id，去获取对应用户信息和机构信息
			tempApp, _ := service.GetOrgApp(loginLogs.OrgId, appType)
			tempRole, _ := service.GetAppRole(adminUser.Id, loginLogs.OrgId, tempApp.Id)

			tempOrg, getOrgErr := service.GetOrgById(loginLogs.OrgId)
			if getOrgErr != nil {
				utils.ErrorLog("获取机构失败:%v", getOrgErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}
			tempSubscibe, getSubscibeErr := service.GetOrgServeSubscibe(tempOrg.Id)
			if getSubscibeErr != nil {
				utils.ErrorLog("获取机构订阅信息失败：%v", getSubscibeErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}

			subscibe = tempSubscibe
			org = tempOrg
			appRole = tempRole
			app = tempApp
		}

		if org != nil && appRole != nil {
			// 插入一条登录记录
			ip := this.GetString("ip")
			loginLog := &models.AdminUserLoginLog{
				AdminUserId: adminUser.Id,
				OrgId:       org.Id,
				AppId:       appRole.AppId,
				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()
	}
}
