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

package implments

import (
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"fmt"
	"github.com/go-xorm/xorm"
	"time"
	"xorm.io/core"
)

/******************************************************************************
 *
 * @Struct Name              : RoleMenuDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : RoleMenu的数据访问对象实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 13:39:52
 *
 ******************************************************************************/
type RoleMenuDAOImplement struct {
	session *xorm.Session
	meta    *grmi.Entity
	userid  string
}

/******************************************************************************
 *
 * @Function Name            : NewRoleMenuDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个RoleMenuDAOImplement实例
 *
 * @Function Parameters      : xorm会话
 *

 * @Return Value             : RoleMenuDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-20 13:39:52
 *
 ******************************************************************************/
func NewRoleMenuDAOImplement(session *xorm.Session, userid string) *RoleMenuDAOImplement {
	return &RoleMenuDAOImplement{session, &meta.RoleMenu, userid}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.InsertOne
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) InsertOne(entity *model.RoleMenu) error {

	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Insert(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.DeleteOne
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) DeleteOne(roleId int, menuId int) error {
	_, err := impl.session.Table(impl.meta.TableName).ID(core.PK{roleId, menuId}).Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.SelectOne
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) SelectOne(roleId int, menuId int) (*model.RoleMenu, error) {
	var data model.RoleMenu
	ok, err := impl.session.Table(impl.meta.TableName).ID(core.PK{roleId, menuId}).Get(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	if !ok {
		return nil, nil
	}
	return &data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) UpdateOne(entity *model.RoleMenu) error {

	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.Insert
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) Insert(entities *[]model.RoleMenu) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]

		entity.LastUser = impl.userid
	}
	_, err := impl.session.Table(impl.meta.TableName).Insert(entities)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.Delete
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) Delete(entities *[]model.RoleMenu) error {
	for _, entity := range *entities {

		_, err := impl.session.Table(impl.meta.TableName).ID(entity.GetKey()).Delete(impl.meta.Indicator)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.DeleteWhere
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) DeleteWhere(predicates []grmi.Predicate) error {

	parameters := []interface{}{}
	where := "1 = 1 "

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	_, err := session.Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.Select
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) Select(predicates []grmi.Predicate, orderByFields []grmi.Field) ([]model.RoleMenu, error) {

	parameters := []interface{}{}
	where := "1 = 1 "

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	if orderByFields != nil {
		for _, field := range orderByFields {
			session = session.OrderBy(field.ColumnName)
		}
	}

	data := make([]model.RoleMenu, 0, 10)
	err := session.Find(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	return data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.SelectAndPaging
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) SelectAndPaging(paging *grmi.Paging, predicates []grmi.Predicate, orderByFields []grmi.Field) (grmi.PagingResult, error) {

	parameters := []interface{}{}
	where := "1 = 1 "

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	count, err := session.Count(impl.meta.Indicator)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}

	orderBy := " order by "
	if orderByFields != nil {
		for _, field := range orderByFields {
			if orderBy == " order by " {
				orderBy += field.ColumnName
			} else {
				orderBy += ", " + field.ColumnName
			}
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.RoleMenu, 0, 10)
	where = " where " + where
	err = impl.session.Table(impl.meta.TableName).SQL("select * from ["+impl.meta.TableName+"]"+where+orderBy+" offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return grmi.PagingResult{Records: data, Count: count, PageNumber: paging.Number, PageSize: paging.Size}, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.Update
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) Update(entities *[]model.RoleMenu) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]

		entity.LastUser = impl.userid
		_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) UpdateWhere(predicates []grmi.Predicate, entity *model.RoleMenu, columns ...string) error {

	parameters := []interface{}{}
	where := "1 = 1 "

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	columns = append(columns, meta.RoleMenu_LastUser.Name)
	entity.LastUser = impl.userid
	_, err := session.Cols(columns...).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.GetByRoleId
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) GetByRoleId(roleId int) ([]model.Menu, error) {
	menus := make([]model.Menu, 0)
	err := impl.session.Table("Menu").Join("LEFT", "RoleMenu", "RoleMenu.MenuId=Menu.MenuId").Where("RoleMenu.RoleId=? and Menu.MenuType in ('M','C') and Menu.Visible = 0", roleId).Asc("Menu.Sort").Find(&menus)
	if err != nil {
		return menus, err
	}
	return menus, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.GetRoleMeunId
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) GetRoleMeunId(roleId int) ([]int, error) {
	var menuIds []int
	menuList := make([]model.Menu, 0)
	err := impl.session.Table("RoleMenu").Join("LEFT", "Menu", "RoleMenu.MenuId=Menu.MenuId").Where("RoleMenu.RoleId = ? ", roleId).And(" RoleMenu.MenuId not in(select Menu.ParentId from RoleMenu LEFT JOIN Menu on Menu.MenuId=RoleMenu.MenuId where RoleMenu.RoleId =? )", roleId).Asc("Menu.Sort").Find(&menuList)
	if err != nil {
		return nil, err
	}
	for i := 0; i < len(menuList); i++ {
		menuIds = append(menuIds, menuList[i].MenuId)
	}
	return menuIds, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.InsertRoleMenu
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) InsertRoleMenu(roleId int, menuId []int) (bool, error) {
	var roleInfo model.Role
	if _, err := impl.session.Table("Role").Where("RoleId = ?", roleId).Get(&roleInfo); err != nil {
		return false, err
	}
	menuList := make([]model.Menu, 0)
	if err := impl.session.Table("Menu").In("MenuId", menuId).Find(&menuList); err != nil {
		fmt.Println()
		return false, err
	}
	if len(menuList) > 0 {
		NowTime := utils.TimeFormat(time.Now(), "yyyy-MM-dd HH:mm:ss")
		//ORM不支持批量插入所以需要拼接 sql 串
		sql := "INSERT INTO `RoleMenu` (`RoleId`,`MenuId`,`RoleName`,`LastModify`,`LastUser`,`CreateTime`) VALUES "

		sql2 := "INSERT INTO CasbinRule  (`p_type`,`v0`,`v1`,`v2`) VALUES "
		isCasbin := false
		for i := 0; i < len(menuList); i++ {
			if len(menuList)-1 == i {
				//最后一条数据 以分号结尾
				sql += fmt.Sprintf("(%d,%d,'%s','%s','%s','%s')", roleInfo.RoleId, menuList[i].MenuId, roleInfo.RoleName, NowTime, "sys", NowTime)
				if menuList[i].MenuType == "A" {
					isCasbin = true
					sql2 += fmt.Sprintf("('p','%s','%s','%s');", roleInfo.RoleKey, menuList[i].Path, menuList[i].Action)
				} else {
					sql2 = sql2[:len(sql2)-1]
				}
			} else {
				sql += fmt.Sprintf("(%d,%d,'%s','%s','%s','%s'),", roleInfo.RoleId, menuList[i].MenuId, roleInfo.RoleName, NowTime, "sys", NowTime)
				if menuList[i].MenuType == "A" {
					isCasbin = true
					sql2 += fmt.Sprintf("('p','%s','%s','%s'),", roleInfo.RoleKey, menuList[i].Path, menuList[i].Action)
				}
			}
		}
		_, err := impl.session.Exec(sql)
		if err != nil {
			return false, err
		}
		if isCasbin {
			_, err = impl.session.Exec(sql2)
			if err != nil {
				return false, err
			}
		}
	}
	return true, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/base/RoleMenuDAO.DeleteRoleMenu
 *
 ******************************************************************************/
func (impl *RoleMenuDAOImplement) DeleteRoleMenu(roleId int, roleKey string) (bool, error) {

	_, err := impl.session.Table(impl.meta.TableName).Where("RoleId = ?", roleId).Delete(impl.meta.Indicator)
	if err != nil {
		return false, grmi.NewDataBaseError(err)
	}
	//删除casbinRule数据
	sql3 := "delete from CasbinRule where v0= '" + roleKey + "'"
	_, err = impl.session.Exec(sql3)
	if err != nil {
		return false, err
	}
	return true, nil
}
