package mobile_api_controllers

import (
	"XT_New/controllers"
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"fmt"
	"strconv"
	"strings"
)

type MobileBaseAPIController struct {
	controllers.BaseAPIController
}

func (this *MobileBaseAPIController) Prepare() {
	this.BaseAPIController.Prepare()
	// beego.Trace("============================================================")
	// beego.Trace("session ID: %v", this.Ctx.Input.Cookie("beegosessionID"))
	// beego.Trace("session : %v", this.GetSession("info"))
	// this.SetSession("info", time.Now().Format("2006/01/02 15:04:05"))
	// beego.Trace("============================================================")
}

//

func (this *MobileBaseAPIController) GetMobileAdminUserInfo() *MobileAdminUserInfo {
	userInfo := this.GetSession("mobile_admin_user_info")
	if userInfo == nil {
		return nil
	} else {
		return userInfo.(*MobileAdminUserInfo)
	}
}

type MobileAdminUserInfo struct {
	AdminUser    *models.AdminUser
	Org          *models.Org
	App          *models.OrgApp
	AppRole      *models.App_Role
	Subscibe     *models.ServeSubscibe
	TemplateInfo *models.GobalTemplate
}

type MobileBaseAPIAuthController struct {
	MobileBaseAPIController
}

func (this *MobileBaseAPIAuthController) Prepare() {
	token := this.Ctx.GetCookie("token_cookie")
	logout_cookie := this.Ctx.GetCookie("logout_cookie")

	//if len(token) == 0{
	//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
	//	this.StopRun()
	//}
	this.MobileBaseAPIController.Prepare()
	adminUserInfo := this.GetMobileAdminUserInfo()

	fmt.Println(token)
	if len(token) == 0 {
		this.DelSession("mobile_admin_user_info")
		fmt.Println(logout_cookie)
		if len(logout_cookie) == 1 {
			this.Ctx.SetCookie("logout_cookie", "2")
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLogOut)
			this.StopRun()
		} else {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
			this.StopRun()
		}

	} else {
		if adminUserInfo == nil {
			this.DelSession("mobile_admin_user_info")
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
			this.StopRun()
		}
	}

	//if this.Ctx.Request.Method != "GET" {
	//	err := service.GetOrgSubscibeState(adminUserInfo.Subscibe)
	//	if err != nil || adminUserInfo.Subscibe.State == 3 {
	//		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
	//		this.StopRun()
	//	}
	//}

	if adminUserInfo.AppRole != nil {
		if adminUserInfo.AppRole.Id > 0 {
			app_role, _ := service.FindAppRoleById(adminUserInfo.AppRole.Id)
			if app_role != nil {
				if app_role.Status != 1 {
					this.DelSession("mobile_admin_user_info")
					this.Ctx.SetCookie("token_cookie", "")
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeForbidden)
					this.StopRun()
				}
			}
		}

	}

	if this.Ctx.Request.Header.Get("Permission") == "1" {
		if adminUserInfo.AdminUser.Id != adminUserInfo.Org.Creator { //超级管理员不受此限制

			isPermission := false
			adminUserInfo := this.GetMobileAdminUserInfo()
			//该机构下该用户有多少个
			role, _ := service.GetUserAllRole(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id)
			var roles []string
			if len(role.RoleIds) <= 0 { //该用户没有设置角色

			} else {
				roles = strings.Split(role.RoleIds, ",")
			}
			fmt.Println(roles)

			//获取该用户下所有角色的权限总集
			var userRolePurviews string
			var userRolePurviewsArr []string
			for _, item := range roles {
				role_id, _ := strconv.ParseInt(item, 10, 64)
				purviews, _ := service.GetRoleFuncPurviewIds(role_id)
				if len(userRolePurviews) == 0 {
					userRolePurviews = purviews
				} else {
					userRolePurviews = userRolePurviews + "," + purviews
				}
			}
			//该用户所拥有角色的权限的总集
			userRolePurviewsArr = RemoveRepeatedPurviewElement(strings.Split(userRolePurviews, ","))
			fmt.Println(userRolePurviewsArr)
			//系统所记录的权限列表
			allPermission, _ := service.GetAllFunctionPurview()

			for _, item := range allPermission {
				fmt.Println(strings.Split(item.Urlfor, ",")[0])
				fmt.Println(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))

				//判断当前路由是否在权限路由列表里面
				if strings.Split(item.Urlfor, ",")[0] == strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode") {

					//获取该角色的所有权限
					for _, items := range userRolePurviewsArr {
						id, _ := strconv.ParseInt(items, 10, 64)
						fmt.Println(id)
						fmt.Println(item.ID)

						if id == item.ID {
							isPermission = true
						}
					}
					if !isPermission {
						msg, _ := service.FindErrorMsgByStr(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
						json := make(map[string]interface{})
						json["msg"] = msg
						json["code"] = 0
						json["state"] = 0
						this.Data["json"] = json
						this.ServeJSON()
						this.StopRun()
					}
				}
			}
		}
	}

}

func RemoveRepeatedPurviewElement(arr []string) (newArr []string) {
	newArr = make([]string, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}

type AdminUserInfo struct {
	AdminUser    *models.AdminUser                    `json:"user"`
	CurrentOrgId int64                                `json:"current_org_id"`
	CurrentAppId int64                                `json:"current_app_id"`
	OrgIds       []int64                              `json:"org_ids"`
	Orgs         map[int64]*models.Org                `json:"orgs"`
	OrgAppIds    map[int64][]int64                    `json:"org_app_ids"`
	OrgApps      map[int64](map[int64]*models.OrgApp) `json:"org_apps"`
	App2OrgIds   map[int64]int64                      `json:"app_to_org_ids"`
	AppRoles     map[int64]*models.App_Role           `json:"app_roles"`
	AppPurviews  map[int64][]*models.Purview          `json:"app_purviews"`
	AppUrlfors   map[int64][]string                   `json:"app_urlfors"`
	Subscibes    map[int64]*models.ServeSubscibe      `json:"org_subscibes"`
}
