package task

import (
	qmsvr "LAPP_ACURA_MOM_BACKEND/services/qm"
	qmmodel "LAPP_ACURA_MOM_BACKEND/models/qm"
	"LAPP_ACURA_MOM_BACKEND/web/middleware/glog"
	"context"
	"time"
)

//仓库
var recChan = make(chan qmmodel.ReclinerReclst, 100) //定义一个调度任务通道

var printNum = 50

func CreateRecPrintTaskTick() {
	tick := time.Tick(1 * time.Second)
	for {
		select {
		case <-tick:
			CreateRecPrintTask()
		}
	}
}

/****查询要打印的任务**********/
func CreateRecPrintTask() {

	//创建继承Baxkground的子节点Context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go doTaskPrintRec(ctx)

	data := make([]qmmodel.ReclinerReclst, 0)
	recList := make([]int, 0)
	//第一步，查询要打印的数据
	var serviceOfRec = qmsvr.NewReclinerReclstService()
	data, err := serviceOfRec.SelectUnPrint(printNum)
	if err != nil {
		glog.InfoExtln("返修错误", "err:", err)
		return
	}
	if len(data) == 0 {
		return
	}
	//锁定
	for _, v := range data {
		recList = append(recList, v.RecNr)
	}
	err = serviceOfRec.UpdateUnPrint(recList)
	if err != nil {
		glog.InfoExtln("返修错误", "err:", err)
		return
	}
	//第二步，把所有的服务调度放到channel
	for _, v := range data {
		recChan <- v
	}

}

/********打印逻辑************/
func doTaskPrintRec(ctx context.Context) {
	//第三步，启动协程，从channel里读取数据
	for {
		select {
		case <-ctx.Done():
			return
		case task, ok := <-recChan:

			if !ok {
				return //停机退出
			}
			var serviceOfRec = qmsvr.NewReclinerReclstService()
			err := serviceOfRec.CreateRecPrintInfo(task)
			if err !=nil{
				glog.InfoExtln("返修打印错误日志","err:",err)
				continue
			}
		}
	}
}
