// Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	"LAPP_ACURA_MOM_BACKEND/utils"
)

/******************************************************************************
 *
 * @Description              : Menu的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 11:11:05
 *
 ******************************************************************************/
var DefaultConditionOfMenu = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Menu_MenuId.UrlParameterName:     grmi.NewConditionItem(meta.Menu_MenuId, grmi.Equal, true),
		meta.Menu_MenuName.UrlParameterName:   grmi.NewConditionItem(meta.Menu_MenuName, grmi.Equal, false),
		meta.Menu_Title.UrlParameterName:      grmi.NewConditionItem(meta.Menu_Title, grmi.Equal, false),
		meta.Menu_Icon.UrlParameterName:       grmi.NewConditionItem(meta.Menu_Icon, grmi.Equal, false),
		meta.Menu_Path.UrlParameterName:       grmi.NewConditionItem(meta.Menu_Path, grmi.Equal, false),
		meta.Menu_Paths.UrlParameterName:      grmi.NewConditionItem(meta.Menu_Paths, grmi.Equal, false),
		meta.Menu_MenuType.UrlParameterName:   grmi.NewConditionItem(meta.Menu_MenuType, grmi.Equal, false),
		meta.Menu_Action.UrlParameterName:     grmi.NewConditionItem(meta.Menu_Action, grmi.Equal, false),
		meta.Menu_Permission.UrlParameterName: grmi.NewConditionItem(meta.Menu_Permission, grmi.Equal, false),
		meta.Menu_ParentId.UrlParameterName:   grmi.NewConditionItem(meta.Menu_ParentId, grmi.Equal, false),
		meta.Menu_NoCache.UrlParameterName:    grmi.NewConditionItem(meta.Menu_NoCache, grmi.Equal, false),
		meta.Menu_BreadCrumb.UrlParameterName: grmi.NewConditionItem(meta.Menu_BreadCrumb, grmi.Equal, false),
		meta.Menu_Component.UrlParameterName:  grmi.NewConditionItem(meta.Menu_Component, grmi.Equal, false),
		meta.Menu_Sort.UrlParameterName:       grmi.NewConditionItem(meta.Menu_Sort, grmi.Equal, false),
		meta.Menu_Visible.UrlParameterName:    grmi.NewConditionItem(meta.Menu_Visible, grmi.Equal, false),
		meta.Menu_IsFrame.UrlParameterName:    grmi.NewConditionItem(meta.Menu_IsFrame, grmi.Equal, false),
		meta.Menu_LastModify.UrlParameterName: grmi.NewConditionItem(meta.Menu_LastModify, grmi.Approximate, false),
		meta.Menu_LastUser.UrlParameterName:   grmi.NewConditionItem(meta.Menu_LastUser, grmi.Equal, false),
		meta.Menu_CreateTime.UrlParameterName: grmi.NewConditionItem(meta.Menu_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Menu的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 11:11:05
 *
 ******************************************************************************/
var DefaultConditionOfMenuAndPaging = grmi.NewCondition(
	DefaultConditionOfMenu.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : MenuServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Menu的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 11:11:05
 *
 ******************************************************************************/
type MenuServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewMenuDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个MenuDAOImplement实例
 *
 * @Return Value             : MenuDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 11:11:05
 *
 ******************************************************************************/
func NewMenuServiceImplement() *MenuServiceImplement {
	return &MenuServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.InsertOne
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) InsertOne(user *global.User, entity *model.Menu) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "InsertOneMenu", "插入一个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)
	record, err := dao.SelectOne(entity.MenuId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.DeleteOne
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) DeleteOne(user *global.User, menuId int) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "DeleteOneMenu", "删除一个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)
	record, err := dao.SelectOne(menuId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(menuId)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.SelectOne
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) SelectOne(user *global.User, menuId int) (*model.Menu, error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "SelectOneMenu", "查询一个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)
	result, err := dao.SelectOne(menuId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.UpdateOne
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) UpdateOne(user *global.User, entity *model.Menu) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "UpdateOneMenu", "修改一个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)
	record, err := dao.SelectOne(entity.MenuId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.Insert
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) Insert(user *global.User, entities *[]model.Menu) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "InsertMenu", "插入多个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.MenuId)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
	}

	err := dao.Insert(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.Delete
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) Delete(user *global.User, entities *[]model.Menu) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "DeleteMenu", "删除多个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.MenuId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Delete(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.Select
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.Menu, error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "SelectMenu", "查询Menu")

	condition := DefaultConditionOfMenuAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewMenuDAO(session, user.UserId)
	result, err := dao.Select(predicates, []grmi.Field{meta.Menu_Sort})
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.SelectAndPaging
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) SelectAndPaging(user *global.User, urlParameters map[string]string) (grmi.PagingResult, error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "SelectMenu", "查询Menu")

	condition := DefaultConditionOfMenuAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	dao := dal.NewMenuDAO(session, user.UserId)
	condition.Fill(urlParameters)
	result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.Update
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) Update(user *global.User, entities *[]model.Menu) error {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "UpdateMenu", "修改多个Menu")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMenuDAO(session, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.MenuId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Update(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.DiguiMenu
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) DiguiMenu(menulist *[]model.Menu, menu model.Menu) model.Menu {

	list := *menulist

	min := make([]model.Menu, 0)
	for j := 0; j < len(list); j++ {
		if menu.MenuId != list[j].ParentId {
			continue
		}
		mi := model.Menu{}
		mi.MenuId = list[j].MenuId
		mi.MenuName = list[j].MenuName
		mi.Title = list[j].Title
		mi.Icon = list[j].Icon
		mi.Path = list[j].Path
		mi.MenuType = list[j].MenuType
		mi.Action = list[j].Action
		mi.Permission = list[j].Permission
		mi.ParentId = list[j].ParentId
		mi.NoCache = list[j].NoCache
		mi.BreadCrumb = list[j].BreadCrumb
		mi.Component = list[j].Component
		mi.Sort = list[j].Sort
		mi.Visible = list[j].Visible
		mi.CreateTime = list[j].CreateTime
		mi.LastUser = list[j].LastUser
		mi.LastModify = list[j].LastModify
		mi.Children = []model.Menu{}
		utils.TrimStruct(&mi, mi)
		if mi.MenuType != "F" {
			ms := impl.DiguiMenu(menulist, mi)
			utils.TrimStruct(&ms, ms)
			min = append(min, ms)

		} else {
			min = append(min, mi)
		}

	}
	menu.Children = min
	return menu
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.SelectMenu
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) SelectMenu(user *global.User, urlParameters map[string]string) (menus []model.Menu, err error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "SelectMenu", "查询Menu")

	condition := DefaultConditionOfMenuAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewMenuDAO(session, user.UserId)
	menuList, err := dao.Select(predicates, []grmi.Field{meta.Menu_Sort})
	if err != nil {
		return nil, err
	}
	menus = make([]model.Menu, 0)
	for i := 0; i < len(menuList); i++ {
		if menuList[i].ParentId != 0 {
			continue
		}
		menusInfo := impl.DiguiMenu(&menuList, menuList[i])

		menus = append(menus, menusInfo)
	}
	return menus, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.DiguiMenuLable
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) DiguiMenuLable(menulist *[]model.Menu, menu model.MenuLable) model.MenuLable {
	list := *menulist

	min := make([]model.MenuLable, 0)
	for j := 0; j < len(list); j++ {
		if menu.Id != list[j].ParentId {
			continue
		}
		mi := model.MenuLable{}
		mi.Id = list[j].MenuId
		mi.Label = list[j].Title
		mi.Children = []model.MenuLable{}
		if list[j].MenuType != "F" {
			ms := impl.DiguiMenuLable(menulist, mi)
			min = append(min, ms)
		} else {
			min = append(min, mi)
		}

	}
	menu.Children = min
	return menu
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.SelectMenuLable
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) SelectMenuLable(user *global.User, urlParameters map[string]string) (menus []model.MenuLable, err error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "SelectMenuLable", "查询Menu")

	condition := DefaultConditionOfMenuAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewMenuDAO(session, user.UserId)
	menuList, err := dao.Select(predicates, []grmi.Field{meta.Menu_Sort})
	if err != nil {
		return nil, err
	}
	menus = make([]model.MenuLable, 0)
	for i := 0; i < len(menuList); i++ {
		if menuList[i].ParentId != 0 {
			continue
		}
		e := model.MenuLable{}
		e.Id = menuList[i].MenuId
		e.Label = menuList[i].Title
		menusInfo := impl.DiguiMenuLable(&menuList, e)

		menus = append(menus, menusInfo)
	}
	return menus, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MenuService.MenuTreeRoleselect
 *
 ******************************************************************************/
func (impl *MenuServiceImplement) MenuTreeRoleselect(user *global.User, roleId int) (map[string]interface{}, error) {

	grmi.Log(user, "/services/base/implments/Menu.service.impl.go", "MenuTreeRoleselect", "角色菜单")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	data := make(map[string]interface{})
	urlParameters := make(map[string]string)
	result, err := impl.SelectMenuLable(user, urlParameters)
	if err != nil {
		return data, err
	}
	dao := dal.NewRoleMenuDAO(session, user.UserId)
	menuIds, err := dao.GetRoleMeunId(roleId)
	if err != nil {
		return data, err
	}
	data["menus"] = result
	data["checkedKeys"] = menuIds
	return data, nil
}
