package controllers

import (
	"exhibitionCentre/base"
	"exhibitionCentre/logging"
	"exhibitionCentre/models"
	"exhibitionCentre/utils"
	"fmt"
	"text/template"
)

type DashboardMenuInfo struct {
	Index int
	Name  string
	Icon  string
	Link  string
}

type DashboardInfo struct {
	Src    string
	Menus  []DashboardMenuInfo
	Logout DashboardMenuInfo
}

type SettingsInfo struct {
	DisplayName string `json:"display_name"`
}

type GetPublisherExhibitionsRequest struct {
	UserId int `json:"user_id"`
}

/****************************** 根据角色跳转对应Dashboard页面 ******************************/
// "/manage/dashboard"
func Dashboard(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("加载Dashboard页面鉴权失败")
		return 0, nil
	}

	// 根据角色重定向
	if jwt.Role == int(models.Admin) {
		logging.Log.Infof("管理员(%v)打开Dashboard页面", jwt.Email)
		Redirect(router, "/manage/dashboard/users")
	} else if jwt.Role == int(models.Publisher) {
		logging.Log.Infof("用户(%v)打开Dashboard页面", jwt.Email)
		Redirect(router, "/manage/dashboard/exhibitions")
	}

	return 200, nil
}

// 获取Dashboard界面展览页面
// "/manage/dashboard/exhibitions"
func DashboardExhibitions(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("加载Dashboard页面鉴权失败")
		return 0, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/dashboard.html")
	if err != nil {
		logging.Log.Error("加载Dashboard页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}

	// 判断角色
	if jwt.Role == int(models.Admin) {
		// 重定向到用户管理页面
		Redirect(router, "/manage/dashboard/users")
	} else if jwt.Role == int(models.Publisher) {
		page.Execute(router.Writer, generatePublisherDashboardExhibitions())
	}
	return 200, nil
}

// 获取Dashboard界面设置页面
// "/manage/dashboard/settings"
func DashboardSettings(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("加载Dashboard页面鉴权失败")
		return 0, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/dashboard.html")
	if err != nil {
		logging.Log.Error("加载Dashboard页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}

	// 判断角色
	if jwt.Role == int(models.Admin) {
		page.Execute(router.Writer, generateAdminDashboardSettings())
	} else if jwt.Role == int(models.Publisher) {
		page.Execute(router.Writer, generatePublisherDashboardSettings())
	}

	return 200, nil
}

// 获取Dashboard界面用户管理页面
// "/manage/dashboard/users"
func DashboardUsers(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("加载Dashboard页面鉴权失败")
		return 0, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/dashboard.html")
	if err != nil {
		logging.Log.Error("加载Dashboard页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}

	// 判断角色
	if jwt.Role == int(models.Admin) {
		page.Execute(router.Writer, generateAdminDashboardUsers())
	} else if jwt.Role == int(models.Publisher) {
		Redirect(router, "/manage/dashboard/exhibitions")
	}

	return 200, nil
}

/****************************** 获取相关Dashboard界面具体内容显示页面 ******************************/
// 获取Publishers具体展览页面
// "/manage/manage_exhibitions"
func ManageExhibitions(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized || jwt.Role == int(models.Tourist) {
		logging.Log.Error("加载manage_users页面鉴权失败")
		return 404, utils.SerializeErrorData("页面不存在!")
	}

	// 判断是否是合法访问方式
	valid := router.Req.URL.Query().Get("valid")
	if len(valid) == 0 || valid != "1" {
		Redirect(router, "/manage/dashboard/exhibitions")
		return 200, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/manage_exhibitions.html")
	if err != nil {
		logging.Log.Error("加载manage_users页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}
	page.Execute(router.Writer, nil)
	return 200, nil
}

// /manage/get_exhibitions/
func GetExhibitions(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized || jwt.Role == int(models.Tourist) {
		logging.Log.Error("获取展览信息鉴权失败")
		return 404, utils.SerializeErrorData("加载信息失败!")
	}

	// 获取所有展览
	exhibitions, err := models.GetAllExhibitionsByUserId(jwt.UserId)
	if err != nil {
		logging.Log.Infof("根据邮箱获取所有展览失败: %s", err.Error())
		return 400, utils.SerializeErrorData("加载信息失败!")
	}

	return 200, utils.Serialize(exhibitions)
}

func GetPublisherExhibitions(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized || jwt.Role == int(models.Tourist) {
		logging.Log.Error("获取展览信息鉴权失败")
		return 404, utils.SerializeErrorData("加载信息失败!")
	}

	// 解析request数据
	var info GetPublisherExhibitionsRequest
	if err := utils.JsonParse(router.Data, &info); err != nil {
		logging.Log.Error("解析数据失败: ", err.Error())
		return 403, utils.SerializeErrorData("获取展览列表失败!")
	}

	// 获取所有展览
	exhibitions, err := models.GetAllExhibitionsByUserId(uint(info.UserId))
	if err != nil {
		logging.Log.Infof("根据邮箱获取所有展览失败: %s", err.Error())
		return 400, utils.SerializeErrorData("获取展览列表失败!")
	}

	return 200, utils.Serialize(exhibitions)
}

// 获取Admin具体用户页面
// "/manage/manage_users"
func ManageUsers(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized || jwt.Role != int(models.Admin) {
		logging.Log.Error("加载manage_users页面鉴权失败")
		return 404, utils.SerializeErrorData("页面不存在!")
	}

	// 判断是否是合法访问方式
	valid := router.Req.URL.Query().Get("valid")
	if len(valid) == 0 || valid != "1" {
		Redirect(router, "/manage/dashboard/users")
		return 200, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/manage_users.html")
	if err != nil {
		logging.Log.Error("加载manage_users页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}

	// 获取所有用户
	// users := models.GetAllUsers()

	page.Execute(router.Writer, nil)
	return 200, nil
}

// /manage/get_users/
func GetUsers(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized || jwt.Role == int(models.Tourist) {
		logging.Log.Error("获取用户列表鉴权失败")
		return 404, utils.SerializeErrorData("加载信息失败!")
	}

	// 获取所有用户
	users, err := models.GetAllUsers()
	if err != nil {
		logging.Log.Errorf("获取用户列表鉴权失败, err: %v\n", err.Error())
		return 400, utils.SerializeErrorData("加载信息失败!")
	}

	return 200, utils.Serialize(users)
}

// 获取具体设置页面
// "/manage/settings"
func Settings(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("加载Settings页面鉴权失败")
		return 0, nil
	}

	// 判断是否是合法访问方式
	valid := router.Req.URL.Query().Get("valid")
	if len(valid) == 0 || valid != "1" {
		Redirect(router, "/manage/dashboard/settings")
		return 200, nil
	}

	// 加载dashboard页面
	page, err := template.ParseFiles("./view/html/settings.html")
	if err != nil {
		logging.Log.Error("加载Settings页面失败: ", err.Error())
		return 404, utils.SerializeErrorData("")
	}

	// 获取email的用户是否存在
	user, err := models.GetUser(jwt.Email)
	if err != nil {
		logging.Log.Errorf("Settings页用户(%s), err: %v", jwt.Email, err.Error())
		return 404, utils.SerializeErrorData(fmt.Sprintf("该用户(%s)不存在!", jwt.Email))
	}

	settingsInfo := SettingsInfo{
		DisplayName: user.DisplayName,
	}
	page.Execute(router.Writer, settingsInfo)
	return 200, nil
}

/****************************** 管理员相关页面 ******************************/
func generateAdminDashboardUsers() *DashboardInfo {
	dashboardInfo := &DashboardInfo{Src: "/manage/manage_users?valid=1&index=1"}
	dashboardInfo.Menus = []DashboardMenuInfo{
		{Index: 1, Name: "用户", Icon: "fas fa-users", Link: "javascript:manageUsers();"},
		{Index: 2, Name: "设置", Icon: "fas fa-cog", Link: "javascript:settings();"},
	}
	dashboardInfo.Logout = DashboardMenuInfo{
		Index: -1, Name: "退出", Icon: "fas fa-sign-out-alt", Link: "javascript:logout();",
	}
	return dashboardInfo
}

func generateAdminDashboardSettings() *DashboardInfo {
	dashboardInfo := &DashboardInfo{Src: "/manage/settings?valid=1&index=2"}
	dashboardInfo.Menus = []DashboardMenuInfo{
		{Index: 1, Name: "用户", Icon: "fas fa-users", Link: "javascript:manageUsers();"},
		{Index: 2, Name: "设置", Icon: "fas fa-cog", Link: "javascript:settings();"},
	}
	dashboardInfo.Logout = DashboardMenuInfo{
		Index: -1, Name: "退出", Icon: "fas fa-sign-out-alt", Link: "javascript:logout();",
	}
	return dashboardInfo
}

/****************************** 用户相关页面 ******************************/
func generatePublisherDashboardExhibitions() *DashboardInfo {
	dashboardInfo := &DashboardInfo{Src: "/manage/manage_exhibitions?valid=1&index=1"}
	dashboardInfo.Menus = []DashboardMenuInfo{
		{Index: 1, Name: "展览", Icon: "fas fa-photo-film", Link: "javascript:manageExhibitions();"},
		{Index: 2, Name: "设置", Icon: "fas fa-cog", Link: "javascript:settings();"},
	}
	dashboardInfo.Logout = DashboardMenuInfo{
		Index: -1, Name: "退出", Icon: "fas fa-sign-out-alt", Link: "javascript:logout();",
	}
	return dashboardInfo
}

func generatePublisherDashboardSettings() *DashboardInfo {
	dashboardInfo := &DashboardInfo{Src: "/manage/settings?valid=1&index=2"}
	dashboardInfo.Menus = []DashboardMenuInfo{
		{Index: 1, Name: "展览", Icon: "fas fa-photo-film", Link: "javascript:manageExhibitions();"},
		{Index: 2, Name: "设置", Icon: "fas fa-cog", Link: "javascript:settings();"},
	}
	dashboardInfo.Logout = DashboardMenuInfo{
		Index: -1, Name: "退出", Icon: "fas fa-sign-out-alt", Link: "javascript:logout();",
	}
	return dashboardInfo
}
