package dao

import "server/global"

type Process struct {
	global.GVA_MODEL
	ProcessName    string `json:"processName" form:"processName" gorm:"comment:审批流程名称"`
	ProcessContent string `json:"processContent" form:"processContent" gorm:"审批流程内容"`
	ProcessType    string `json:"processType" form:"processType" gorm:"审批流程类型"`
	Nodes          []Node `json:"nodes" form:"nodes" gorm:"many2many:process_nodes;"`
}

func (Process) TableName() string {
	return "process"
}

func QueryAllProcess() (processes []Process, err error) {
	err = global.GVA_DB.Model(&Process{}).Find(&processes).Error
	return processes, err
}

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

func QueryProcessById(id int) (process Process, err error) {
	err = global.GVA_DB.Model(&Process{}).Where("id = ?", id).Find(&process).Error
	return process, err
}

func (p Process) CreateProcess() error {
	err := global.GVA_DB.Create(&p).Error
	return err
}

func (p Process) UpdateProcess() error {
	// 清除现有的节点
	err := global.GVA_DB.Model(&p).Association("Nodes").Clear()

	// 添加新的节点
	err = global.GVA_DB.Model(&p).Association("Nodes").Append(p.Nodes)
	err = global.GVA_DB.Where("id = ?", p.ID).Updates(&p).Error
	return err
}

func (p Process) DeleteProcess() error {
	err := global.GVA_DB.Unscoped().Delete(&p).Error
	return err
}
