package schedule

import (
	"LAPP_LF_MOM_BACKEND/conf"
	cacheDal "LAPP_LF_MOM_BACKEND/dao/cache"
	"LAPP_LF_MOM_BACKEND/db"
	cacheModel "LAPP_LF_MOM_BACKEND/models/cache"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/middleware/glog"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/google/uuid"
	"path/filepath"
	"testing"
	"time"
)

// 测试自动调度
func TestScheduler(t *testing.T) {
	var (
		y1, d1             int
		m1                 time.Month
		schedeng           SchedulerSrv
		startDate, endDate time.Time
		worklineid         string
		err                error
	)
	//初始化日志开始
	baseDir := ""
	flag.StringVar(&baseDir, "dir", "D:\\GoWrok\\src\\leit.com\\LAPP_LF_MOM_BACKEND\\log", "running in a directory")
	flag.Parse()

	defer glog.Flush()
	fmt.Println(baseDir)
	baseDir = utils.EnsureDir(baseDir)
	fmt.Println(baseDir)
	pathLogDir := filepath.Join(baseDir, "glog")
	fmt.Println(pathLogDir)
	glog.DefaultInit(true, pathLogDir)
	utils.TimezoneLocation, err = time.LoadLocation("Asia/Shanghai")
	glog.Infoln("启动日志", "InitDB return success")
	// 建立数据库连接
	//加载配置
	err = conf.ReadYamlConfig("D:\\GoWrok\\src\\leit.com\\LAPP_LF_MOM_BACKEND\\conf\\config.yaml")
	if err != nil {
		fmt.Printf("failed to read yaml config due to: %v", err)
		return
	}
	//初始化数据库
	err = db.InitDb()
	if err != nil {
		t.Error("数据库加载失败!")
	}
	fmt.Println("数据库加载成功")
	// 初始化scheduler,默认从当天起计划5天
	y1, m1, d1 = time.Now().Date()
	startDate = time.Date(y1, m1, d1, 0, 0, 0, 0, time.Local)
	endDate = startDate.Add(24 * 5 * time.Hour)
	fmt.Println()
	fmt.Println(startDate)
	fmt.Println()
	fmt.Println(endDate)
	fmt.Println()
	schedeng = SchedulerSrv{PlantNr: 100, StartDate: startDate, EndDate: endDate}
	schedeng.Tmsrv.StartDate = startDate
	schedeng.Tmsrv.EndDate = endDate
	// 指定加载的产线类型
	worklineid = "G-Frame Assy"
	fmt.Println(worklineid)
	// 加载激活的项目主数据
	err = schedeng.LoadProjectData()
	if err != nil {
		t.Error(err.Error())
	}
	fmt.Println()
	fmt.Printf("LoadProjectData:%v", schedeng.ProjDict)
	// 加载时间模型，基于调度引擎指定的时间区间
	schedeng.LoadTimemodelData(worklineid)
	fmt.Println()
	fmt.Printf("WorkShiftDict:%v", schedeng.Tmsrv.WorkShiftDict)
	fmt.Println()
	fmt.Printf("LoadTimemodelData:%v", schedeng.Tmsrv.WorkShiftDict)
	fmt.Println()
	// 加载产品换型主数据
	err = schedeng.LoadSetupData()
	if err != nil {
		t.Error(err.Error())
	}
	fmt.Println()
	fmt.Printf("LoadSetupData:%v", schedeng.SetupDict)
	// 加载产线主数据
	err = schedeng.LoadWorklineData(worklineid)
	if err != nil {
		t.Error(err.Error())
	}

	fmt.Println()
	fmt.Printf("LoadWorklineData:%v", schedeng.WorklineDict)
	fmt.Println()
	fmt.Printf("G-Frame Assy:%v", schedeng.WorklineDict["G-Frame Assy"])
	// 加载产线班组计划出勤数据
	err = schedeng.LoadWorkLineWorkShiftData()
	if err != nil {
		t.Error(err.Error())
	}
	fmt.Println()
	fmt.Printf("LoadWorkLineWorkShiftData:%v", schedeng.WorklineDict)
	fmt.Println()
	fmt.Printf("G-Frame Assy:%v", schedeng.WorklineDict["G-Frame Assy"])
	// 生成产线的时间曲线
	err = schedeng.GenerateWorkLineTimeCurve()
	if err != nil {
		t.Error(err.Error())
	}
	fmt.Println()
	fmt.Printf("TimeLineArray:%v", schedeng.WorklineDict["G-Frame Assy"].TimeCurve.TimeLineArray)
	fmt.Println()
	fmt.Printf("SchedTimeCurve:%v", schedeng.WorklineDict["G-Frame Assy"].SchedTimeCurve)
	// 加载工单数据（调度任务）
	err = schedeng.LoadSchedTaskData(worklineid)
	if err != nil {
		t.Error(err.Error())
	}

	// 对调度任务进行排序
	schedeng.SortUnplannedTask()
	fmt.Printf("SortUnplannedTask:%v", schedeng.UnPlannedTaskArray)
	fmt.Println()
	// 依次调度未计划工单
	err = schedeng.AutoSchedule()
	if err != nil {
		t.Error(err.Error())
	}

	//计算产线负载
	schedeng.WorklineDict["G-Frame Assy"].CalDailyWorkload()

	//保存到mongodb里
	data, _ := json.Marshal(schedeng)
	dao := cacheDal.NewSchedulerCacheDAO()
	cacheInfo := new(cacheModel.SchedulerCache)
	cacheInfo.TaskId = uuid.New().String()
	cacheInfo.WorkLineId = worklineid
	cacheInfo.Data = string(data)
	cacheInfo.CreateBy = "123456"
	cacheInfo.CreateTime = utils.TimeFormat(time.Now(), "yyyy-MM-dd HH:mm:ss")
	_, err = dao.InsertOne(cacheInfo)
	if err == nil {
		schedeng.TaskId = cacheInfo.TaskId
	}

	fmt.Printf("WorkShiftDict:%v", schedeng.WorklineDict)
	fmt.Println("G-Frame Assy")
	fmt.Printf("G-Frame Assy Task:%v", schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray)
	fmt.Println()
	fmt.Printf("G-Frame Assy TimeCurve:%v", schedeng.WorklineDict["G-Frame Assy"].TimeCurve)
	fmt.Println()
	fmt.Printf("G-Frame Assy SchedTimeCurve:%v", schedeng.WorklineDict["G-Frame Assy"].SchedTimeCurve)
	fmt.Println()
	fmt.Printf("G-Frame Assy WorkLoadArray:%v", schedeng.WorklineDict["G-Frame Assy"].WorkLoadArray)
	fmt.Println()
	// 排程任务
	fmt.Println("排程任务：")
	for i := 0; i < len(schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray); i++ {
		fmt.Println(i, " -- ", fmt.Sprintf("生产订单：%s 计划产线：%s 计划开始时间：%v 计划结束时间：%v ,间隔时间：%v ",
			schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray[i].TaskId, schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray[i].SchedResId,
			schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray[i].SchedStartTime, schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray[i].SchedEndTime,
			schedeng.WorklineDict["G-Frame Assy"].SchedTaskArray[i].Duration))
	}
	fmt.Println()
	// 输出排程结果
	err = schedeng.PrintScheduleResult()
	if err != nil {
		t.Error(err.Error())
	}
	fmt.Println()
	fmt.Printf("排程任务TaskId：%s",schedeng.TaskId)
}

