package schedule

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/infra/logger"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
)

func ApsRelease(plantNr int) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "Scheduler")
	master := db.Eloquent.Master()
	session := master.NewSession()
	workLineDao := dal.NewWorkLineDAO(session, plantNr, user)
	workLineLi, err := workLineDao.SelectAll()
	if err != nil {
		log.Error("ApsRelease get all work line failed, error:" + err.Error())
		return
	}
	for _, workLine := range workLineLi {
		_ = StartWorkLineRelease(workLine, plantNr)
	}
}

func StartWorkLineRelease(workLine model.WorkLine, plantNr int) error {
	user := "crontab"
	log, _ := logger.NewLogger(user, "Scheduler")
	schedulerSrv := SchedulerSrv{
		PlantNr: plantNr,
	}
	// 加载项目主数据
	err := schedulerSrv.LoadProjectData()
	if err != nil {
		log.Error("StartWorkLineRelease load project data failed, error:"+err.Error(), "workLineId: "+workLine.WorkLineid)
		return err
	}
	// 加载产线主数据
	err = schedulerSrv.LoadWorkLineData(workLine.WorkLineid)
	if err != nil {
		log.Error("StartWorkLineRelease load work line data, error:"+err.Error(), "workLineId: "+workLine.WorkLineid)
		return err
	}
	// 生产派工
	err = schedulerSrv.ReleaseSchedule(workLine.WorkLineid)
	if err != nil {
		log.Error("StartWorkLineRelease release schedule failed, error:"+err.Error(), "workLineId: "+workLine.WorkLineid)
		return err
	}
	return nil
}
