package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"eta/eta_api/utils"
	"strings"
	"time"
)

type CloudDiskMenu struct {
	MenuId     int       `orm:"column(menu_id);pk" description:"目录ID"`
	MenuName   string    `description:"目录名称"`
	ParentId   int       `description:"父级ID"`
	Size       int64     `description:"目录大小"`
	AdminId    int       `description:"创建人ID"`
	AdminName  string    `description:"创建人名称"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"修改时间"`
}

func (m *CloudDiskMenu) TableName() string {
	return "cloud_disk_menu"
}

func (m *CloudDiskMenu) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.MenuId = int(id)
	return
}

func (m *CloudDiskMenu) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *CloudDiskMenu) GetItemById(id int) (err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cloud_disk_menu WHERE menu_id = ? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&m)
	return
}

func (m *CloudDiskMenu) GetItemByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cloud_disk_menu WHERE 1=1 `
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&m)
	return
}

func (m *CloudDiskMenu) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*CloudDiskMenu, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := ``
	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
}

type CloudDiskMenuCreateReq struct {
	MenuName string `description:"目录名称"`
	ParentId int    `description:"父级ID"`
}

type CloudDiskMenuRenameReq struct {
	MenuId   int    `description:"目录ID"`
	MenuName string `description:"目录名称"`
}

type CloudDiskMenuDeleteReq struct {
	MenuId int `description:"目录ID"`
}

// DeleteCloudDiskMenuAndResourcesByMenuIds 根据目录IDs删除目录及文件
func DeleteCloudDiskMenuAndResourcesByMenuIds(menuIds []int) (err error) {
	menuLens := len(menuIds)
	if menuLens == 0 {
		return
	}
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	sql := `DELETE FROM cloud_disk_menu WHERE menu_id IN (` + utils.GetOrmInReplace(menuLens) + `)`
	if _, err = tx.Raw(sql, menuIds).Exec(); err != nil {
		return
	}
	sql = `DELETE FROM cloud_disk_resource WHERE menu_id IN (` + utils.GetOrmInReplace(menuLens) + `)`
	if _, err = tx.Raw(sql, menuIds).Exec(); err != nil {
		return
	}
	return
}

type CloudDiskMenuTree struct {
	*CloudDiskMenu
	Children []*CloudDiskMenuTree
}
