package dao

import "server/global"

type Node struct {
	global.GVA_MODEL
	NodeName        string     `json:"nodeName" form:"nodeName" gorm:"comment:审批节点名称"`
	ApproverId      int        `json:"approverId" form:"approverId" gorm:"comment:审批人id"`
	Approver        SysUser    `json:"approver" form:"approver" gorm:"foreignKey:ApproverId;references:id;"`
	NodeOrder       int        `json:"nodeOrder" form:"nodeOrder" gorm:"comment:节点顺序"`
	NodeDescription string     `json:"nodeDescription" form:"nodeDescription" gorm:"comment:节点描述"`
	Processes       []*Process `json:"processes" form:"processes" gorm:"many2many:process_nodes;"`
}

func (Node) TableName() string {
	return "node"
}

func QueryAllNode() (nodes []Node, err error) {
	err = global.GVA_DB.Model(&Node{}).Preload("Approver").Find(&nodes).Error
	return nodes, err
}

func QueryNodeList(limit, offset int) (nodes []Node, total int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&Node{})
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("id desc").Limit(limit).Offset(offset).Preload("Approver").Find(&nodes).Error
	return nodes, total, err
}

func QueryNodeById(id int) (node Node, err error) {
	err = global.GVA_DB.Model(&Node{}).Where("id = ?", id).Preload("Approver").First(&node).Error
	return node, err
}

func QueryNodeByApproverId(approverId int) (nodes []Node, err error) {
	err = global.GVA_DB.Model(&Node{}).Where("approver_id = ?", approverId).Preload("Approver").Find(&nodes).Error
	return nodes, err
}

func (n Node) CreateNode() error {
	return global.GVA_DB.Create(&n).Error
}

func (n Node) UpdateNode() error {
	return global.GVA_DB.Where("id = ?", n.ID).Updates(&n).Error
}

func (n Node) DeleteNode() error {
	return global.GVA_DB.Unscoped().Delete(&n).Error
}
