// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================

package wf_run

import (
	"database/sql"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
)

type RunSearch struct {
	FromId    uint   `json:"from_id"`
	FromTable string `json:"from_table"`
	IsDel     uint   `json:"is_del"`
	Status    uint   `json:"status"`
}

type RunAddData struct {
	Pid            uint   `p:"pid"              json:"pid"`              // work_run父流转公文ID 值大于0则这个是子流程，完成后或者要返回父流程
	Uid            uint   `p:"uid"              json:"uid"`              //
	FlowId         uint   `p:"flow_id"          json:"flow_id"`          // 流程id 正常流程
	FromTable      string `p:"from_table"       json:"from_table"`       // 单据表，不带前缀
	FromTitle      string `p:"from_title"       json:"from_title"`       // 业务表标题字段
	FromStatus     string `p:"from_status"       json:"from_status"`     // 业务表审批状态字段
	FromId         int    `p:"from_id"          json:"from_id"`          //
	RunName        string `p:"run_name"         json:"run_name"`         // 公文名称
	RunFlowId      uint   `p:"run_flow_id"      json:"run_flow_id"`      // 流转到什么流程 最新流程，查询优化，进入子流程时将简化查询，子流程与父流程同步
	RunFlowProcess string `p:"run_flow_process" json:"run_flow_process"` // 流转到第几步
	Dateline       uint   `p:"dateline"         json:"dateline"`         //
}

//获取流程运行信息
func GetRunning(where *RunSearch) (entity *Entity, err error) {
	entity, err = Model.Where(where).Order("id desc").FindOne()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("判断运行状态出错")
	}
	return
}

func GetRuns(where interface{}, args ...interface{}) (entities []*Entity, err error) {
	entities, err = Model.Where(where, args).Order("id asc").FindAll()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取流程运行状态失败")
	}
	return
}

//获取流程运行信息
func GetRunById(id uint) (entity *Entity, err error) {
	entity, err = Model.FindOne(id)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取运行数据失败")
		return
	}
	return
}

func Add(data *RunAddData, tx *gdb.TX) (id int64, err error) {
	var res sql.Result
	res, err = Model.TX(tx).Save(data)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("保存业务流程运行信息出错")
		return
	}
	id, err = res.LastInsertId()
	return
}

func UpdateRun(runId uint, data g.Map, tx *gdb.TX) error {
	_, err := Model.TX(tx).Where("id", runId).Update(data)
	return err
}
