package dao

import "server/global"

type ProjectProcess struct {
	global.GVA_MODEL
	ProjectProcessName string        `json:"projectProcessName" form:"projectProcessName" gorm:"comment:项目审批名称"`
	ProjectId          int           `json:"projectId" form:"projectId" gorm:"comment:项目id"`
	Project            Project       `json:"project" form:"project" gorm:"foreignKey:ProjectId;references:id;"`
	Applicant          int           `json:"applicant" form:"applicant" gorm:"comment:申请人"`
	User               SysUser       `json:"user" form:"user" gorm:"foreignKey:Applicant;references:id;"`
	CurrentNodeOrder   int           `json:"currentNodeOrder" form:"currentNodeOrder" gorm:"comment:当前审批节点id"`
	Node               Node          `json:"node" form:"node" gorm:"foreignKey:CurrentNodeOrder;references:id;"`
	ProcessApprovalId  int           `json:"processApprovalId" form:"processApprovalId" gorm:"comment:当前审批流程id"`
	Process            Process       `json:"process" form:"process" gorm:"foreignKey:ProcessApprovalId;references:id"`
	ProjectType        string        `json:"projectType" form:"projectType" gorm:"comment:项目类型"`
	Descriptions       []Description `json:"descriptions" form:"descriptions" gorm:"foreignKey:ProjectProcessId;"`
}

func (ProjectProcess) TableName() string {
	return "project_process"
}

func QueryProjectApplicantList(limit, offset, applicant int) (projectProcesses []ProjectProcess, total int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&ProjectProcess{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if applicant != 0 {
		db = db.Where("applicant = ?", applicant)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("id desc").Limit(limit).Offset(offset).Preload("Project").Preload("User").Preload("Node").Preload("Process").Preload("Descriptions").Find(&projectProcesses).Error
	return projectProcesses, total, err
}

func QueryProjectProcessList(limit, offset, applicant int) (projectProcesses []ProjectProcess, total int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&ProjectProcess{}).Joins("JOIN node ON project_process.current_node_order = node.id").Where("node.approver_id = ?", applicant)
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("id desc").Limit(limit).Offset(offset).Preload("Project").Preload("User").Preload("Node").Preload("Process").Preload("Descriptions").Find(&projectProcesses).Error
	return projectProcesses, total, err
}

func (pp ProjectProcess) CreateProjectProcess() error {
	return global.GVA_DB.Create(&pp).Error
}

func (pp ProjectProcess) UpdateProjectProcess() error {
	return global.GVA_DB.Where("id = ?", pp.ID).Updates(&pp).Error
}

func (pp ProjectProcess) DeleteProjectProcess() error {
	return global.GVA_DB.Unscoped().Delete(&pp).Error
}
