package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strings"
	"time"
)

type EnPermission struct {
	EnPermissionId   int       `orm:"column(en_permission_id);pk" description:"英文品种权限ID"`
	EnPermissionName string    `description:"品种权限名称"`
	CnPermissionName string    `description:"对应的中文权限名称"`
	ParentId         int       `description:"父级ID"`
	Sort             int       `description:"排序"`
	CreateTime       time.Time `description:"创建时间"`
	ModifyTime       time.Time `description:"修改时间"`
	Enabled          int       `description:"是否可用，1可用，0禁用"`
}

var EnPermissionColumns = struct {
	EnPermissionId   string
	EnPermissionName string
	CnPermissionName string
	ParentId         string
	Sort             string
	CreateTime       string
	ModifyTime       string
	Enabled          string
}{
	EnPermissionId:   "en_permission_id",
	EnPermissionName: "en_permission_name",
	CnPermissionName: "cn_permission_name",
	ParentId:         "parent_id",
	Sort:             "sort",
	CreateTime:       "create_time",
	ModifyTime:       "modify_time",
	Enabled:          "enabled",
}

func (m *EnPermission) TableName() string {
	return "en_permission"
}

func (m *EnPermission) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EnPermissionId = int(id)
	return
}

func (m *EnPermission) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(m, cols...)
	return
}

func (m *EnPermission) Del() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnPermissionColumns.EnPermissionId)
	_, err = o.Raw(sql, m.EnPermissionId).Exec()
	return
}

func (m *EnPermission) GetItemById(id int) (item *EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnPermissionColumns.EnPermissionId)
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *EnPermission) GetItemByCondition(condition string, pars []interface{}) (item *EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 `, m.TableName())
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *EnPermission) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *EnPermission) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *EnPermission) GetPageItemsByCondition(startSize, pageSize int, condition string, pars []interface{}, fieldArr []string, orderRule string) (total int, items []*EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSql, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type EnPermissionAddReq struct {
	PermissionName   string `description:"品种权限名称"`
	CnPermissionName string `description:"对应的中文权限名称"`
	ParentId         int    `description:"父级ID"`
	Enabled          int    `description:"是否可用，1可用，0禁用"`
}

type EnPermissionEditReq struct {
	PermissionId     int    `description:"英文品种权限ID"`
	PermissionName   string `description:"品种权限名称"`
	CnPermissionName string `description:"对应的中文权限名称"`
	ParentId         int    `description:"父级ID"`
}

type EnPermissionEnabledReq struct {
	PermissionId int `description:"英文品种权限ID"`
	Enabled      int `description:"是否可用，1可用，0禁用"`
}

type EnPermissionRemoveReq struct {
	PermissionId int `description:"英文品种权限ID"`
}

type EnPermissionPageListResp struct {
	List   []*EnPermissionItem
	Paging *paging.PagingItem `description:"分页数据"`
}

type EnPermissionItem struct {
	PermissionId     int    `description:"英文品种权限ID"`
	PermissionName   string `description:"品种权限名称"`
	CnPermissionName string `description:"对应的中文权限名称"`
	ParentId         int    `description:"父级ID"`
	Sort             int    `description:"排序"`
	CreateTime       string `description:"创建时间"`
	Child            []*EnPermissionItem
	Enabled          int `description:"是否可用，1可用，0禁用"`
}

type EnPermissionMoveReq struct {
	PermissionId     int `description:"品种id"`
	PrevPermissionId int `description:"上一个兄弟节点品种id"`
	NextPermissionId int `description:"下一个兄弟节点品种id"`
}

func GetEnPermissionUnionList(condition string, pars []interface{}) (items []*EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			(
				SELECT * FROM en_permission WHERE 1=1 %s
				UNION
				SELECT * FROM en_permission WHERE en_permission_id IN (
					SELECT parent_id FROM en_permission WHERE parent_id > 0 %s
				)
			) AS t
		ORDER BY
			parent_id ASC,
			sort ASC,
			create_time ASC`, condition, condition)
	_, err = o.Raw(sql, pars, pars).QueryRows(&items)
	return
}

func ClearEnPermissionsByPermissionId(permissionId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	tx, e := o.Begin()
	if e != nil {
		err = fmt.Errorf("orm begin err: %s", e.Error())
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	sql := `DELETE FROM en_classify_permission WHERE en_permission_id = ?`
	_, e = tx.Raw(sql, permissionId).Exec()
	if e != nil {
		err = fmt.Errorf("delete en_classify_permission err: %s", e.Error())
		return
	}

	sql = `DELETE FROM en_company_permission WHERE en_permission_id = ?`
	_, e = tx.Raw(sql, permissionId).Exec()
	if e != nil {
		err = fmt.Errorf("delete en_company_permission err: %s", e.Error())
		return
	}
	return
}

// UpdateEnPermissionSortByParentId 根据父类id更新排序
func UpdateEnPermissionSortByParentId(parentId, permissionId, nowSort int, updateSort string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` update en_permission set sort = ` + updateSort + ` WHERE parent_id=? AND sort > ? `
	if permissionId > 0 {
		sql += ` or ( en_permission_id > ` + fmt.Sprint(permissionId) + ` and sort = ` + fmt.Sprint(nowSort) + `)`
	}
	_, err = o.Raw(sql, parentId, nowSort).Exec()
	return
}

// GetMaxSortByParentId 获取最大的排序值
func (m *EnPermission) GetMaxSortByParentId(parentId int) (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT max(%s) AS sort FROM %s WHERE %s = ? `, EnPermissionColumns.Sort, m.TableName(), EnPermissionColumns.ParentId)
	err = o.Raw(sql, parentId).QueryRow(&maxSort)
	return
}

// GetMaxSort 获取最大的排序值
func (m *EnPermission) GetMaxSort() (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT max(%s) AS sort FROM %s`, EnPermissionColumns.Sort, m.TableName())
	err = o.Raw(sql).QueryRow(&maxSort)
	return
}

// GetFirstEnPermissionByParentId 获取当前父级分类下，且排序数相同 的排序第一条的数据
func (m *EnPermission) GetFirstEnPermissionByParentId(parentId int) (item *EnPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? order by sort asc, en_permission_id asc limit 1`, m.TableName(), EnPermissionColumns.ParentId)
	err = o.Raw(sql, parentId).QueryRow(&item)
	return
}

// SetEnabled 更新启动禁用
func (m *EnPermission) SetEnabled(parentId, enabled int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`UPDATE %s SET %s = ?  WHERE %s = ?`, m.TableName(), EnPermissionColumns.Enabled, EnPermissionColumns.ParentId)
	_, err = o.Raw(sql, enabled, parentId).Exec()
	return
}

// SetEnabledByPermissionId 更新启动禁用
func (m *EnPermission) SetEnabledByPermissionId(permissionId, enabled int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`UPDATE %s SET %s = ?  WHERE %s = ?`, m.TableName(), EnPermissionColumns.Enabled, EnPermissionColumns.EnPermissionId)
	_, err = o.Raw(sql, enabled, permissionId).Exec()
	return
}
