package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// ClassifyMenu 报告分类-子目录表
type ClassifyMenu struct {
	MenuId     int       `orm:"column(menu_id);pk"`
	MenuName   string    `description:"子目录名称"`
	ClassifyId int       `description:"一级分类ID"`
	Sort       int       `description:"排序"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"更新时间"`
}

func (item *ClassifyMenu) TableName() string {
	return "classify_menu"
}

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

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

func (item *ClassifyMenu) InsertMulti(items []*ClassifyMenu) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.InsertMulti(len(items), items)
	return
}

// GetClassifyMenuById 主键获取子目录
func GetClassifyMenuById(id int) (item *ClassifyMenu, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM classify_menu WHERE menu_id = ? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetClassifyMenuList 获取子目录列表
func GetClassifyMenuList(condition string, pars []interface{}) (list []*ClassifyMenu, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM classify_menu WHERE 1 = 1 `
	sql += condition
	sql += ` ORDER BY sort ASC, create_time ASC`
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// ClassifyMenuSaveReq 保存分类子目录请求体
type ClassifyMenuSaveReq struct {
	MenuId     int    `description:"子目录ID, 0为新增, 大于0为编辑"`
	MenuName   string `description:"子目录名称"`
	//ClassifyId int    `description:"一级分类ID"`
}

// InsertAndUpdateClassifyMenu 新增/编辑/删除分类子目录
func InsertAndUpdateClassifyMenu(insertMenus []*ClassifyMenu, editMenus []*ClassifyMenu, deleteMenuIds []int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 编辑
	sql := ``
	if len(editMenus) > 0 {
		for i := range editMenus {
			sql = fmt.Sprintf(`UPDATE classify_menu SET menu_name = '%s', sort = %d, modify_time = NOW() WHERE menu_id = %d`,
				editMenus[i].MenuName, editMenus[i].Sort, editMenus[i].MenuId)
			if _, e := tx.Raw(sql).Exec(); e != nil {
				err = e
				return
			}
		}
	}

	// 删除
	if len(deleteMenuIds) > 0 {
		for i := range deleteMenuIds {
			sql = fmt.Sprintf(`DELETE FROM classify_menu WHERE menu_id = %d LIMIT 1`, deleteMenuIds[i])
			if _, e := tx.Raw(sql).Exec(); e != nil {
				err = e
				return
			}
			// 删除关联关系
			sql = fmt.Sprintf(`DELETE FROM classify_menu_relation WHERE menu_id = %d`, deleteMenuIds[i])
			if _, e := tx.Raw(sql).Exec(); e != nil {
				err = e
				return
			}
		}
	}

	// 新增
	if len(insertMenus) > 0 {
		_, e := tx.InsertMulti(len(insertMenus), insertMenus)
		if e != nil {
			err = e
			return
		}
	}
	return
}
