package models

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

// ClassifyMenuRelation 报告分类-子目录关联表
type ClassifyMenuRelation struct {
	Id         int       `orm:"column(id);pk"`
	MenuId     int       `description:"子目录ID"`
	ClassifyId int       `description:"二级分类ID"`
	CreateTime time.Time `description:"创建时间"`
}

func (item *ClassifyMenuRelation) TableName() string {
	return "classify_menu_relation"
}

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

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

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

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

// DeleteAndInsertClassifyMenuRelation 新增子目录关联
func DeleteAndInsertClassifyMenuRelation(classifyId, menuId 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 := `DELETE FROM classify_menu_relation WHERE classify_id = ?`
	if _, e := tx.Raw(sql, classifyId).Exec(); e != nil {
		err = e
		return
	}

	// 新增
	if menuId > 0 {
		relate := &ClassifyMenuRelation{
			ClassifyId: classifyId,
			MenuId:     menuId,
			CreateTime: time.Now().Local(),
		}
		_, e := tx.Insert(relate)
		if e != nil {
			err = e
		}
	}
	return
}
