package implments

import (
	baseDal "LAPP_LF_MOM_BACKEND/dao/base"
	logDal "LAPP_LF_MOM_BACKEND/dao/log"
	meDal "LAPP_LF_MOM_BACKEND/dao/me"
	dal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	"LAPP_LF_MOM_BACKEND/infra/logger"
	logMeta "LAPP_LF_MOM_BACKEND/meta/log"
	meta "LAPP_LF_MOM_BACKEND/meta/om"
	baseModel "LAPP_LF_MOM_BACKEND/models/base"
	logModel "LAPP_LF_MOM_BACKEND/models/log"
	meModel "LAPP_LF_MOM_BACKEND/models/me"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/models"
	"errors"
	"fmt"
	"github.com/go-xorm/xorm"
	"strconv"
	"sync"
	"time"
)

/******************************************************************************
 *
 * @Struct Name              : ParseMesWorkOrderServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : DemandHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
type ParseMesWorkOrderServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewDemandHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个DemandHeadDAOImplement实例
 *
 * @Return Value             : DemandHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
func NewParseMesWorkOrderServiceImplement() *ParseMesWorkOrderServiceImplement {
	return &ParseMesWorkOrderServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.OMParseDemandFromFile
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) OMParseDemandFromFile(plantNr int) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	demandHeadDao := dal.NewDemandHeadDAO(session, plantNr, user)
	demandHeadLi, err := demandHeadDao.SelectUnparsedFile()
	if err != nil {
		log.Error("ParseMesWorkOrder OMParseDemandFromFile select unparsed data failed, error: " + err.Error())

		return
	}

	for index, demandHead := range demandHeadLi {
		demandHead.Status = model.DemandHeadParsingStatus
		demandHeadLi[index] = demandHead
	}
	err = demandHeadDao.Update(&demandHeadLi)
	if err != nil {
		log.Error("ParseMesWorkOrder OMParseDemandFromFile update demand head failed, error: " + err.Error())

		return
	}
	var wg sync.WaitGroup
	wg.Add(len(demandHeadLi))
	for _, demandHead := range demandHeadLi {
		if demandHead.Source == model.ParseSourceMES {
			go impl.DealMESFileDemandHead(demandHead, &wg)
		} else if demandHead.Source == model.ParseSourceInterval {
			go impl.DealIntervalFileDemandHead(demandHead, &wg)
		}
	}
	wg.Wait()
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealMESFileDemandHead
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealMESFileDemandHead(demandHead model.DemandHead, wg *sync.WaitGroup) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	defer wg.Done()
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	sessionTX := engine.NewSession()
	defer sessionTX.Close()
	err := sessionTX.Begin()
	if err != nil {
		return
	}
	demandHeadDao := dal.NewDemandHeadDAO(session, demandHead.PlantNr, user)
	demandLstDao := dal.NewDemandLstDAO(sessionTX, demandHead.PlantNr, user)
	workOrderDao := dal.NewWorkOrderDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusRecDao := dal.NewWorkOrderStatusRecLstDAO(sessionTX, demandHead.PlantNr, user)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(sessionTX, demandHead.PlantNr, user)
	artDemandHeadDao := logDal.NewArtDemandHeadDAO(sessionTX, demandHead.PlantNr, user)
	artDemandLstDao := logDal.NewArtDemandLstDAO(sessionTX, demandHead.PlantNr, user)
	projectDao := meDal.NewProjectDAO(session, demandHead.PlantNr, user)
	project, err := projectDao.SelectOne(baseModel.A30PorjectId)
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, error: " + err.Error())
		return
	}
	if project == nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, no data")
		return
	}
	demandLstLi, err := demandLstDao.SelectAndOrderBy(demandHead.FileNr, "FileNr")
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get art demandLst failed, error: " + err.Error())
		return
	}
	demandMap := make(map[string]map[grmi.Date][]model.DemandLst)
	for _, demandLst := range demandLstLi {
		demandPartCodeMap, exist := demandMap[demandLst.PartCode]
		if !exist {
			demandMap[demandLst.PartCode] = make(map[grmi.Date][]model.DemandLst)
			demandPartCodeMap = demandMap[demandLst.PartCode]
		}
		lstLi, exist := demandPartCodeMap[grmi.Date(demandLst.PlanDttm)]
		if !exist {
			demandPartCodeMap[grmi.Date(demandLst.PlanDttm)] = make([]model.DemandLst, 0)
			lstLi = demandPartCodeMap[grmi.Date(demandLst.PlanDttm)]
		}
		lstLi = append(lstLi, demandLst)
		demandPartCodeMap[grmi.Date(demandLst.PlanDttm)] = lstLi
		demandMap[demandLst.PartCode] = demandPartCodeMap
	}
	batchDemandLstLi := make([]model.TempDemandLstData, 0)
	for partCode, demandPartCodeMap := range demandMap {
		for planEndDate, demandLstLi := range demandPartCodeMap {
			// 批次中最低生产状态
			var minStatus = baseModel.WO_STATUS_UNPLANNED
			// 批次中最高生产状态
			var maxStatus = baseModel.WO_STATUS_UNPLANNED

			tempDemandLstData := model.TempDemandLstData{}
			tempDemandLstData.PartCode = partCode
			tempDemandLstData.PlanEndDate = planEndDate
			tempDemandLstData.DemandLstLi = demandLstLi
			for index, demandLst := range demandLstLi {
				if index == 0 {
					serial, err := strconv.Atoi(demandLst.Serial)
					if err != nil {
						demandHead.Status = model.DemandHeadUnParsedStatus
						demandHead.ErrNum += 1
						demandHead.ErrorInfo = err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						_ = sessionTX.Rollback()
						return
					}
					tempDemandLstData.Serial = serial
					tempDemandLstData.Seq = demandLst.Seq
				} else if index == len(demandLstLi)-1 {
					serial, err := strconv.Atoi(demandLst.Serial)
					if err != nil {
						demandHead.Status = model.DemandHeadUnParsedStatus
						demandHead.ErrNum += 1
						demandHead.ErrorInfo = err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						_ = sessionTX.Rollback()
						return
					}
					tempDemandLstData.LastSerial = serial
					tempDemandLstData.LastSeq = demandLst.Seq
				}
				// 外部status 转换成系统status 并进行数量统计
				var status int
				if demandLst.State == model.WO_STATUS_RELEASED {
					status = baseModel.WO_STATUS_RELEASED
				} else if demandLst.State == model.WO_STATUS_RUNNING1 || demandLst.State == model.WO_STATUS_RUNNING2 {
					status = baseModel.WO_STATUS_RUNNING
					tempDemandLstData.RunningQty += 1
				} else if demandLst.State == model.WO_STATUS_FINISHED1 || demandLst.State == model.WO_STATUS_FINISHED2 {
					status = baseModel.WO_STATUS_FINISHED
					tempDemandLstData.FinishedQty += 1
				} else if demandLst.State == model.WO_STATUS_DISPATCHED {
					status = baseModel.WO_STATUS_DISPATCHED
					tempDemandLstData.FinishedQty += 1
				} else if demandLst.State == model.WO_STATUS_CANCELED {
					status = baseModel.WO_STATUS_CANCELED
					tempDemandLstData.FinishedQty += 1
					tempDemandLstData.CancelQty += 1
				} else {
					log.Error("ParseMesWorkOrder DealMesDBDemandHeadByDay failed get unknown state :" + strconv.Itoa(demandLst.State))
					demandHead.Status = model.DemandHeadUnParsedStatus
					demandHead.ErrNum += 1
					demandHead.ErrorInfo = "不支持的工单状态"
					_ = demandHeadDao.UpdateOne(&demandHead)
					_ = sessionTX.Rollback()
					return
				}
				if status != baseModel.WO_STATUS_CANCELED {
					if minStatus == baseModel.WO_STATUS_UNPLANNED {
						minStatus = status
					}
					if maxStatus == baseModel.WO_STATUS_UNPLANNED {
						maxStatus = status
					}
					if minStatus > status {
						minStatus = status
					}
					if maxStatus < status {
						maxStatus = status
					}
				}
				tempDemandLstData.Qty += 1
			}
			var batchStatus = baseModel.WO_STATUS_RUNNING
			if tempDemandLstData.CancelQty == tempDemandLstData.Qty {
				batchStatus = baseModel.WO_STATUS_CANCELED
			} else {
				if maxStatus == minStatus && minStatus == baseModel.WO_STATUS_RELEASED {
					batchStatus = maxStatus
				} else if minStatus >= baseModel.WO_STATUS_FINISHED {
					batchStatus = maxStatus
				}
			}
			tempDemandLstData.Status = batchStatus
			batchDemandLstLi = append(batchDemandLstLi, tempDemandLstData)
		}
	}
	sortedLi := impl.SortTempDemandDataLi(batchDemandLstLi)
	for _, tempDemandLstData := range sortedLi {
		if len(tempDemandLstData.DemandLstLi) == 0 {
			continue
		}
		workOrder, workOrderStatus, workOrderQty, err := impl.DealWorkOrder(demandHead.PlantNr,
			project,
			&tempDemandLstData.DemandLstLi[0],
			float64(tempDemandLstData.Qty),
			float64(tempDemandLstData.RunningQty),
			float64(tempDemandLstData.FinishedQty),
			float64(tempDemandLstData.CancelQty),
			workOrderDao,
			workOrderStatusDao,
			workOrderStatusRecDao,
			workOrderQtyDao,
			tempDemandLstData.Status)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrorInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
		// 处理供应商门户需求及其相关表
		err = impl.DealArtDemand(demandHead.PlantNr,
			project,
			tempDemandLstData.Serial,
			tempDemandLstData.Seq,
			tempDemandLstData.LastSerial,
			tempDemandLstData.LastSeq,
			float64(tempDemandLstData.CancelQty),
			tempDemandLstData.DemandLstLi,
			workOrder,
			workOrderStatus,
			workOrderQty,
			artDemandHeadDao,
			artDemandLstDao)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrorInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
	}
	demandHead.Status = model.DemandHeadParsedStatus
	demandHead.ErrNum = 0
	demandHead.ErrorInfo = ""
	err = demandHeadDao.UpdateOne(&demandHead)
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}
	err = demandLstDao.DeleteWhere([]grmi.Predicate{meta.DemandLst_FileNr.NewPredicate(grmi.Equal, demandHead.FileNr)})
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}

	_ = sessionTX.Commit()
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealMESFileDemandHead
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealWorkOrder(pid int,
	project *meModel.Project,
	demandLst *model.DemandLst,
	qty float64,
	runningQty float64,
	finishedQty float64,
	cancelQty float64,
	workOrderDao dal.WorkOrderDAO,
	workOrderStatusDao dal.WorkOrderStatusDAO,
	workOrderStatusRecDao dal.WorkOrderStatusRecLstDAO,
	workOrderQtyDao dal.WorkOrderQtyDAO,
	stateCode int) (workOrder model.WorkOrder, workOrderStatus model.WorkOrderStatus, workOrderQty model.WorkOrderQty, err error) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	workOrderLi, err := workOrderDao.SelectByEndDate(demandLst.PartCode, demandLst.PlanDttm.Restore().Format("2006-01-02"), baseModel.A30PorjectId)
	if err != nil {
		return workOrder, workOrderStatus, workOrderQty, err
	}
	var newWorkOrderSign = true
	if len(workOrderLi) != 0 {
		newWorkOrderSign = false
		workOrder = workOrderLi[0]
		workOrderStatusPoint, err := workOrderStatusDao.SelectOne(workOrder.WorkOrderId)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder get work order status failed, error: " + err.Error())
			return workOrder, workOrderStatus, workOrderQty, err
		}
		if workOrderStatusPoint == nil {
			log.Error("ParseMesWorkOrder DealWorkOrder get work order status failed" + "存在workOrder,不存在对应的workOrderStatus, workOrderId: " + workOrder.WorkOrderId)
			return workOrder, workOrderStatus, workOrderQty, grmi.NewBusinessError("存在workOrder,不存在对应的workOrderStatus, workOrderId: " + workOrder.WorkOrderId)
		}
		workOrderStatus = *workOrderStatusPoint
		workOrderQtyPoint, err := workOrderQtyDao.SelectOne(workOrder.WorkOrderId)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder get work order qty failed, error: " + err.Error())
			return workOrder, workOrderStatus, workOrderQty, err
		}
		if workOrderQtyPoint == nil {
			log.Error("ParseMesWorkOrder DealWorkOrder get work order qty failed, error: " + "存在workOrder,不存在对应的workOrderQty, workOrderId: " + workOrder.WorkOrderId)
			return workOrder, workOrderStatus, workOrderQty, grmi.NewBusinessError("存在workOrder,不存在对应的workOrderQty, workOrderId: " + workOrder.WorkOrderId)
		}
		workOrderQty = *workOrderQtyPoint
		if workOrderStatus.Status != stateCode {
			var workOrderStatusRec model.WorkOrderStatusRecLst
			workOrderStatusRec.WorkOrderId = workOrder.WorkOrderId
			workOrderStatusRec.PrevStatus = workOrderStatus.Status
			workOrderStatusRec.Status = stateCode
			err = workOrderStatusRecDao.InsertOne(&workOrderStatusRec)
			if err != nil {
				log.Error("ParseMesWorkOrder DealWorkOrder insert work order status rec failed, error: " + err.Error())
				return workOrder, workOrderStatus, workOrderQty, err
			}
			workOrderStatus.Status = stateCode
			err = workOrderStatusDao.UpdateOne(&workOrderStatus)
			if err != nil {
				log.Error("ParseMesWorkOrder DealWorkOrder update work order status failed, error: " + err.Error())
				return workOrder, workOrderStatus, workOrderQty, err
			}
		}
		workOrderQty.PlanQty = qty
		workOrderQty.ReleasedQty = qty
		workOrderQty.ActQty = finishedQty
		workOrderQty.ActQty1 = runningQty
		err = workOrderQtyDao.UpdateOne(&workOrderQty)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder update work order qty failed, error: " + err.Error())
			return workOrder, workOrderStatus, workOrderQty, err
		}

	}
	if newWorkOrderSign {
		//article, err := articleDao.SelectOne(demandLst.PartCode)
		//if err != nil {
		//	log.Error("ParseMesWorkOrder DealWorkOrder get article failed, error: " + err.Error())
		//	return workOrder, workOrderStatus, workOrderQty, err
		//}
		//if article == nil {
		//	err = errors.New("不存在对应的物料, artID: " + demandLst.PartCode)
		//	log.Error("ParseMesWorkOrder DealWorkOrder get article failed, error: " + err.Error())
		//	return workOrder, workOrderStatus, workOrderQty, err
		//}
		snr := new(models.Snrtab)
		snr.Finr = pid
		workOrderId, err := snr.GetNextSnr(project.WorkOrderSnr)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder get  work order id failed, error: " + err.Error())

			return workOrder, workOrderStatus, workOrderQty, err
		}
		endTime := demandLst.PlanDttm.Restore()
		endDate := endTime.Format("2006-01-02")
		planStartTimeStr := endDate + " 00:00:00"
		planEndTimeStr := endDate + " 23:59:59"
		planStartTime, _ := time.ParseInLocation("2006-01-02 15:04:05", planStartTimeStr, utils.TimezoneLocation)
		planEndTime, _ := time.ParseInLocation("2006-01-02 15:04:05", planEndTimeStr, utils.TimezoneLocation)
		workOrder = model.WorkOrder{
			WorkOrderId: workOrderId,
			ArtId:       demandLst.PartCode,
			OrderType:   baseModel.ODER_TYPE_SEQ,
			OrderInfo:   demandLst.BarCodeDesc,
			PlanQty:     qty,
			//QtyUomId:            article.UomId,
			//PlanResourceId:      article.PlanResourceId,
			//UsedResourceId:      article.UsedResourceId,
			//OpTimePerItem:       article.OpTimePerItem,
			//PlanResourceGroupId: article.PlanResourceGroupId,
			ProjectId:      baseModel.A30PorjectId,
			PlanResourceId: demandLst.ConfigDesc,
			UsedResourceId: demandLst.ConfigDesc,
			//QuantityPerHour:     article.QuantityPerHour,
			RatePerHourToggle: true,
			//BatchTime:           article.BatchTime,
			//BatchingMethod:      article.BatchingMethod,
			PlanStartDate: grmi.Date(demandLst.PlanDttm),
			PlanEndDate:   grmi.Date(demandLst.PlanDttm),
			PlanStartTime: grmi.DateTime(planStartTime),
			PlanEndTime:   grmi.DateTime(planEndTime),
		}
		workOrderStatus = model.WorkOrderStatus{
			WorkOrderId: workOrderId,
			Status:      stateCode,
		}
		workOrderQty = model.WorkOrderQty{
			WorkOrderId: workOrderId,
			PlanQty:     qty,
			ReleasedQty: qty,
			ActQty:      finishedQty,
			ActQty1:     runningQty,
			ActQty3:     cancelQty,
		}
		err = workOrderDao.InsertOne(&workOrder)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder insert  work order  failed, error: " + err.Error())

			return workOrder, workOrderStatus, workOrderQty, err
		}
		err = workOrderStatusDao.InsertOne(&workOrderStatus)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder insert  work order status failed, error: " + err.Error())

			return workOrder, workOrderStatus, workOrderQty, err
		}
		err = workOrderQtyDao.InsertOne(&workOrderQty)
		if err != nil {
			log.Error("ParseMesWorkOrder DealWorkOrder insert  work order qty failed, error: " + err.Error())
			return workOrder, workOrderStatus, workOrderQty, err
		}
	}
	return workOrder, workOrderStatus, workOrderQty, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealArtDemand
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealArtDemand(pid int,
	project *meModel.Project,
	serial int,
	seq int,
	lastSerial int,
	lastSeq int,
	cancelQty float64,
	demandLstLi []model.DemandLst,
	workOrder model.WorkOrder,
	workOrderStatus model.WorkOrderStatus,
	workOrderQty model.WorkOrderQty,
	artDemandHeadDao logDal.ArtDemandHeadDAO,
	artDemandLstDao logDal.ArtDemandLstDAO) (err error) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	// 此时批次需求状态为26-80之间 不包含80 需要在供应商门户处生成需求数据
	artDemandHeadLi, err := artDemandHeadDao.SelectWithoutAuthority([]grmi.Predicate{logMeta.ArtDemandHead_WorkOrderId.NewPredicate(grmi.Equal, workOrder.WorkOrderId)}, []grmi.Field{logMeta.ArtDemandHead_DemandId})
	if err != nil {
		log.Error("ParseMesWorkOrder DealArtDemand get  art demand head, error: " + err.Error())
		return err
	}
	var demandId string
	demandTime := workOrder.PlanEndTime.Restore()
	weekIndex := utils.ParseWeekIndex(demandTime)
	if len(artDemandHeadLi) == 0 {
		snr := new(models.Snrtab)
		snr.Finr = pid
		demandId, err = snr.GetNextSnr(project.LogDemandSnr)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand generate  art demand id failed, error: " + err.Error())
			return err
		}
		artDemandHead := logModel.ArtDemandHead{
			OrderType:       workOrder.OrderType,
			UnproducedQty:   workOrderQty.PlanQty - workOrderQty.ActQty - workOrderQty.ActQty1,
			DemandId:        demandId,
			ArtId:           workOrder.ArtId,
			DemandType:      "byDay",
			DemandYear:      demandTime.Year(),
			DemandMonth:     int(demandTime.Month()),
			DemandWeek:      weekIndex,
			DemandTime:      workOrder.PlanEndTime,
			DemandDate:      grmi.Date(demandTime),
			DemandQty:       workOrderQty.PlanQty,
			Status:          logModel.WaitReceivingStatus,
			OrderStatus:     workOrderStatus.Status,
			QtyUomId:        workOrder.QtyUomId,
			ProjectId:       workOrder.ProjectId,
			WorkOrderId:     workOrder.WorkOrderId,
			DemandCtrlPara1: serial,
			DemandCtrlPara2: seq,
			DemandCtrlPara5: lastSerial,
			DemandCtrlPara6: lastSeq,
			DemandCtrlPara3: workOrder.OrderInfo,
			PlanResourceId:  workOrder.PlanResourceId,
			CancelQty: cancelQty,
		}
		if artDemandHead.UnproducedQty == 0 {
			artDemandHead.DemandStatus = logModel.DemandOrderStatusAccomplish
		}
		err = artDemandHeadDao.InsertOne(&artDemandHead)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand insert  art demand failed, error: " + err.Error())

			return err
		}

	} else {
		artDemandHead := artDemandHeadLi[0]
		demandId = artDemandHead.DemandId
		if artDemandHead.OrderStatus != workOrderStatus.Status {
			artDemandHead.ChangeStatus = logModel.DemandChangeStatusTrue
			artDemandHead.DemandCtrlPara4 = "OrderStatus"
		}
		if artDemandHead.DemandCtrlPara1 != serial || artDemandHead.DemandCtrlPara2 != seq || artDemandHead.DemandCtrlPara5 != lastSerial || artDemandHead.DemandCtrlPara6 != lastSeq {
			artDemandHead.ChangeStatus = logModel.DemandChangeStatusTrue
			artDemandHead.DemandCtrlPara4 = "sort"
		}
		if artDemandHead.DemandQty != workOrderQty.PlanQty {
			artDemandHead.ChangeStatus = logModel.DemandChangeStatusTrue
			artDemandHead.DemandCtrlPara4 = "PlanQty"
		}
		if artDemandHead.CancelQty != cancelQty {
			artDemandHead.ChangeStatus = logModel.DemandChangeStatusTrue
			artDemandHead.DemandCtrlPara4 = "PlanQty"
		}
		artDemandHead.OrderStatus = workOrderStatus.Status
		artDemandHead.DemandQty = workOrderQty.PlanQty
		artDemandHead.DemandCtrlPara1 = serial
		artDemandHead.DemandCtrlPara2 = seq
		artDemandHead.DemandCtrlPara5 = lastSerial
		artDemandHead.DemandCtrlPara6 = lastSeq
		artDemandHead.CancelQty = cancelQty
		artDemandHead.UnproducedQty = workOrderQty.PlanQty - workOrderQty.ActQty - workOrderQty.ActQty1
		if artDemandHead.UnproducedQty == 0 {
			artDemandHead.DemandStatus = logModel.DemandOrderStatusAccomplish
		}
		err = artDemandHeadDao.UpdateOne(&artDemandHead)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand update  art demand failed, error: " + err.Error())

			return err
		}
	}
	oldArtDemandLstLi, err := artDemandLstDao.SelectWithoutAuthority([]grmi.Predicate{logMeta.ArtDemandLst_DemandId.NewPredicate(grmi.Equal, demandId)}, []grmi.Field{logMeta.ArtDemandLst_DemandCtrlPara1, logMeta.ArtDemandLst_DemandCtrlPara2})
	if err != nil {
		log.Error("ParseMesWorkOrder DealArtDemand select art demandLst failed, error: " + err.Error())
		return err
	}
	type DemandLstWithBool struct {
		DemandLst logModel.ArtDemandLst
		Sign      bool
	}
	artDemandLstMap := make(map[int]DemandLstWithBool)
	for _, artDemandLst := range oldArtDemandLstLi {
		demandLstWithBool := DemandLstWithBool{
			DemandLst: artDemandLst,
			Sign:      false,
		}
		artDemandLstMap[artDemandLst.Pos] = demandLstWithBool
	}
	artDemandLstInsertLi := make([]logModel.ArtDemandLst, 0)
	artDemandLstUpdateLi := make([]logModel.ArtDemandLst, 0)
	for _, demandLst := range demandLstLi {
		serial, err := strconv.Atoi(demandLst.Serial)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand change type serial failed, error: " + err.Error())
			return err
		}
		innerStatus := demandLst.State
		var artDemandStatus int
		// 外部status 转换成内部status
		if innerStatus == model.WO_STATUS_RELEASED {
			artDemandStatus = baseModel.WO_STATUS_RELEASED
		} else if innerStatus == model.WO_STATUS_RUNNING1 || innerStatus == model.WO_STATUS_RUNNING2 {
			artDemandStatus = baseModel.WO_STATUS_RUNNING
		} else if innerStatus == model.WO_STATUS_FINISHED1 || innerStatus == model.WO_STATUS_FINISHED2 {
			artDemandStatus = baseModel.WO_STATUS_FINISHED
		} else if innerStatus == model.WO_STATUS_DISPATCHED {
			artDemandStatus = baseModel.WO_STATUS_DISPATCHED
		} else if innerStatus == model.WO_STATUS_CANCELED {
			artDemandStatus = baseModel.WO_STATUS_CANCELED
		}
		oldDemandLstWithBool, exist := artDemandLstMap[demandLst.DemandNr]
		var artDemandLst logModel.ArtDemandLst

		if exist {
			oldDemandLstWithBool.Sign = true
			oldDemandLst := oldDemandLstWithBool.DemandLst
			oldDemandLst.DemandYear = demandTime.Year()
			oldDemandLst.DemandMonth = int(demandTime.Month())
			oldDemandLst.DemandWeek = weekIndex
			oldDemandLst.DemandTime = workOrder.PlanEndTime
			oldDemandLst.DemandDate = grmi.Date(demandTime)
			oldDemandLst.Status = logModel.WaitReceivingStatus
			oldDemandLst.OrderStatus = artDemandStatus
			oldDemandLst.QtyUomId = workOrder.QtyUomId
			oldDemandLst.DemandCtrlPara1 = serial
			oldDemandLst.DemandCtrlPara2 = demandLst.Seq
			oldDemandLstWithBool.DemandLst = oldDemandLst
			artDemandLstMap[demandLst.Pos] = oldDemandLstWithBool
			artDemandLst = oldDemandLst
		} else {
			artDemandLst = logModel.ArtDemandLst{
				OrderType:       workOrder.OrderType,
				DemandId:        demandId,
				ArtId:           workOrder.ArtId,
				Pos:             demandLst.DemandNr,
				DemandType:      "byDay",
				DemandYear:      demandTime.Year(),
				DemandMonth:     int(demandTime.Month()),
				DemandWeek:      weekIndex,
				DemandTime:      workOrder.PlanEndTime,
				DemandDate:      grmi.Date(demandTime),
				DemandQty:       1,
				Status:          logModel.WaitReceivingStatus,
				OrderStatus:     artDemandStatus,
				QtyUomId:        workOrder.QtyUomId,
				DemandCtrlPara1: serial,
				DemandCtrlPara2: demandLst.Seq,
				DemandCtrlPara3: demandLst.BarCodeDesc,
				ProjectId:       workOrder.ProjectId,
				PlanResourceId:  workOrder.PlanResourceId,
			}
		}
		if artDemandStatus >= baseModel.WO_STATUS_RUNNING {
			artDemandLst.UnproducedQty = 0
			artDemandLst.DemandStatus = logModel.DemandOrderStatusAccomplish
		} else {
			artDemandLst.UnproducedQty = 1
		}
		if exist {
			artDemandLstUpdateLi = append(artDemandLstUpdateLi, artDemandLst)
		} else {
			artDemandLstInsertLi = append(artDemandLstInsertLi, artDemandLst)
		}
	}
	// 批量插入时 一次最多插入50条
	demandLstTempLi := make([]logModel.ArtDemandLst, 0, 50)
	for index, demandLst := range artDemandLstInsertLi {
		if index%50 == 0 {
			err = artDemandLstDao.Insert(&demandLstTempLi)
			if err != nil {
				log.Error("ParseMesWorkOrder DealArtDemand insert  art demandLst failed, error: " + err.Error())
				return err
			}
			demandLstTempLi = make([]logModel.ArtDemandLst, 0, 50)

		}
		demandLstTempLi = append(demandLstTempLi, demandLst)
	}
	if len(demandLstTempLi) != 0 {

		err = artDemandLstDao.Insert(&demandLstTempLi)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand insert  art demandLst failed, error: " + err.Error())
			return err
		}
	}

	// 批量更新时 一次最多插入50条
	demandLstTempLi = make([]logModel.ArtDemandLst, 0, 50)
	for index, demandLst := range artDemandLstUpdateLi {
		if index%50 == 0 {
			err = artDemandLstDao.Update(&demandLstTempLi)
			if err != nil {
				log.Error("ParseMesWorkOrder DealArtDemand update  art demandLst failed, error: " + err.Error())
				return err
			}
			demandLstTempLi = make([]logModel.ArtDemandLst, 0, 50)

		}
		demandLstTempLi = append(demandLstTempLi, demandLst)
	}
	if len(demandLstTempLi) != 0 {

		err = artDemandLstDao.Update(&demandLstTempLi)
		if err != nil {
			log.Error("ParseMesWorkOrder DealArtDemand update  art demandLst failed, error: " + err.Error())
			return err
		}
	}
	log.Info(fmt.Sprintf("ParseMesWorkOrder DealArtDemand success, art id: %v, num:%d", workOrder.ArtId, len(demandLstLi)))
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.OMParseDemandFromDB
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) OMParseDemandFromDB(plantNr int) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	demandHeadDao := dal.NewDemandHeadFromDBDAO(session, plantNr, user)
	demandHeadLi, err := demandHeadDao.SelectUnparsedTask()
	if err != nil {
		log.Error("ParseMesWorkOrder OMParseDemandFromDB select unparsed data failed, error: " + err.Error())

		return
	}
	if len(demandHeadLi) == 0 {
		log.Debug("ParseMesWorkOrder OMParseDemandFromDB select unparsed data is zero")
		return
	}
	for index, demandHead := range demandHeadLi {
		demandHead.Status = model.DemandHeadParsingStatus
		demandHeadLi[index] = demandHead
	}
	err = demandHeadDao.Update(&demandHeadLi)
	if err != nil {
		log.Error("ParseMesWorkOrder OMParseDemandFromDB update demand head failed, error: " + err.Error())

		return
	}
	var wg sync.WaitGroup
	wg.Add(len(demandHeadLi))
	for _, demandHead := range demandHeadLi {
		if demandHead.TaskType == model.ParseTaskTypeByDay {
			go impl.DealMesDBDemandHeadByDay(demandHead, &wg)
		} else {
			go impl.DealMESDBDemandHeadByTime(demandHead, &wg)
		}
	}
	wg.Wait()
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealMesDBDemandHeadByDay
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealMesDBDemandHeadByDay(demandHead model.DemandHeadFromDB, wg *sync.WaitGroup) {
	defer wg.Done()
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	sessionTX := engine.NewSession()
	defer sessionTX.Close()
	err := sessionTX.Begin()
	if err != nil {
		return
	}

	demandHeadDao := dal.NewDemandHeadFromDBDAO(session, demandHead.PlantNr, "crontab")
	demandLstDao := dal.NewDemandLstDAO(sessionTX, demandHead.PlantNr, user)
	workOrderDao := dal.NewWorkOrderDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusRecDao := dal.NewWorkOrderStatusRecLstDAO(sessionTX, demandHead.PlantNr, user)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(sessionTX, demandHead.PlantNr, user)
	artDemandHeadDao := logDal.NewArtDemandHeadDAO(sessionTX, demandHead.PlantNr, user)
	artDemandLstDao := logDal.NewArtDemandLstDAO(sessionTX, demandHead.PlantNr, user)
	projectDao := meDal.NewProjectDAO(session, demandHead.PlantNr, user)
	project, err := projectDao.SelectOne(baseModel.A30PorjectId)
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, error: " + err.Error())
		return
	}
	if project == nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, no data")
		return
	}
	demandLstLi, err := demandLstDao.SelectAndOrderBy(demandHead.TaskNr, "TaskNr")
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get art demandLst failed, error: " + err.Error())
		return
	}
	demandMap := make(map[string]map[grmi.Date][]model.DemandLst)
	for _, demandLst := range demandLstLi {
		demandPartCodeMap, exist := demandMap[demandLst.PartCode]
		if !exist {
			demandMap[demandLst.PartCode] = make(map[grmi.Date][]model.DemandLst)
			demandPartCodeMap = demandMap[demandLst.PartCode]
		}
		lstLi, exist := demandPartCodeMap[grmi.Date(demandLst.PlanDttm)]
		if !exist {
			demandPartCodeMap[grmi.Date(demandLst.PlanDttm)] = make([]model.DemandLst, 0)
			lstLi = demandPartCodeMap[grmi.Date(demandLst.PlanDttm)]
		}
		lstLi = append(lstLi, demandLst)
		demandPartCodeMap[grmi.Date(demandLst.PlanDttm)] = lstLi
		demandMap[demandLst.PartCode] = demandPartCodeMap
	}
	batchDemandLstLi := make([]model.TempDemandLstData, 0)
	for partCode, demandPartCodeMap := range demandMap {
		for planEndDate, demandLstLi := range demandPartCodeMap {
			// 批次中最低生产状态
			var minStatus = baseModel.WO_STATUS_UNPLANNED
			// 批次中最高生产状态
			var maxStatus = baseModel.WO_STATUS_UNPLANNED

			tempDemandLstData := model.TempDemandLstData{}
			tempDemandLstData.PartCode = partCode
			tempDemandLstData.PlanEndDate = planEndDate
			tempDemandLstData.DemandLstLi = demandLstLi
			for index, demandLst := range demandLstLi {
				if index == 0 {
					serial, err := strconv.Atoi(demandLst.Serial)
					if err != nil {
						demandHead.Status = model.DemandHeadUnParsedStatus
						demandHead.ErrNum += 1
						demandHead.ErrInfo = err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						_ = sessionTX.Rollback()
						return
					}
					tempDemandLstData.Serial = serial
					tempDemandLstData.Seq = demandLst.Seq
				} else if index == len(demandLstLi)-1 {
					serial, err := strconv.Atoi(demandLst.Serial)
					if err != nil {
						demandHead.Status = model.DemandHeadUnParsedStatus
						demandHead.ErrNum += 1
						demandHead.ErrInfo = err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						_ = sessionTX.Rollback()
						return
					}
					tempDemandLstData.LastSerial = serial
					tempDemandLstData.LastSeq = demandLst.Seq
				}
				// 外部status 转换成系统status 并进行数量统计
				var status int
				if demandLst.State == model.WO_STATUS_RELEASED {
					status = baseModel.WO_STATUS_RELEASED
				} else if demandLst.State == model.WO_STATUS_RUNNING1 || demandLst.State == model.WO_STATUS_RUNNING2 {
					status = baseModel.WO_STATUS_RUNNING
					tempDemandLstData.RunningQty += 1
				} else if demandLst.State == model.WO_STATUS_FINISHED1 || demandLst.State == model.WO_STATUS_FINISHED2 {
					status = baseModel.WO_STATUS_FINISHED
					tempDemandLstData.FinishedQty += 1
				} else if demandLst.State == model.WO_STATUS_DISPATCHED {
					status = baseModel.WO_STATUS_DISPATCHED
					tempDemandLstData.FinishedQty += 1
				} else if demandLst.State == model.WO_STATUS_CANCELED {
					status = baseModel.WO_STATUS_CANCELED
					tempDemandLstData.FinishedQty += 1
					tempDemandLstData.CancelQty += 1
				} else {
					log.Error("ParseMesWorkOrder DealMesDBDemandHeadByDay failed get unknown state :" + strconv.Itoa(demandLst.State))
					demandHead.Status = model.DemandHeadUnParsedStatus
					demandHead.ErrNum += 1
					demandHead.ErrInfo = "不支持的工单状态"
					_ = demandHeadDao.UpdateOne(&demandHead)
					_ = sessionTX.Rollback()
					return
				}
				if status != baseModel.WO_STATUS_CANCELED {
					if minStatus == baseModel.WO_STATUS_UNPLANNED {
						minStatus = status
					}
					if maxStatus == baseModel.WO_STATUS_UNPLANNED {
						maxStatus = status
					}
					if minStatus > status {
						minStatus = status
					}
					if maxStatus < status {
						maxStatus = status
					}
				}
				tempDemandLstData.Qty += 1
			}
			var batchStatus = baseModel.WO_STATUS_RUNNING
			if tempDemandLstData.CancelQty == tempDemandLstData.Qty {
				batchStatus = baseModel.WO_STATUS_CANCELED
			} else {
				if maxStatus == minStatus && minStatus == baseModel.WO_STATUS_RELEASED {
					batchStatus = maxStatus
				} else if minStatus >= baseModel.WO_STATUS_FINISHED {
					batchStatus = maxStatus
				}
			}
			tempDemandLstData.Status = batchStatus
			batchDemandLstLi = append(batchDemandLstLi, tempDemandLstData)
		}
	}
	sortedLi := impl.SortTempDemandDataLi(batchDemandLstLi)
	for _, tempDemandLstData := range sortedLi {
		if len(tempDemandLstData.DemandLstLi) == 0 {
			continue
		}
		workOrder, workOrderStatus, workOrderQty, err := impl.DealWorkOrder(demandHead.PlantNr,
			project,
			&tempDemandLstData.DemandLstLi[0],
			float64(tempDemandLstData.Qty),
			float64(tempDemandLstData.RunningQty),
			float64(tempDemandLstData.FinishedQty),
			float64(tempDemandLstData.CancelQty),
			workOrderDao,
			workOrderStatusDao,
			workOrderStatusRecDao,
			workOrderQtyDao,
			tempDemandLstData.Status)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
		// 处理供应商门户需求及其相关表
		err = impl.DealArtDemand(demandHead.PlantNr,
			project,
			tempDemandLstData.Serial,
			tempDemandLstData.Seq,
			tempDemandLstData.LastSerial,
			tempDemandLstData.LastSeq,
			float64(tempDemandLstData.CancelQty),
			tempDemandLstData.DemandLstLi,
			workOrder,
			workOrderStatus,
			workOrderQty,
			artDemandHeadDao,
			artDemandLstDao)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
	}
	demandHead.Status = model.DemandHeadParsedStatus
	demandHead.ErrNum = 0
	demandHead.ErrInfo = ""
	err = demandHeadDao.UpdateOne(&demandHead)
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}
	err = demandLstDao.DeleteWhere([]grmi.Predicate{meta.DemandLst_TaskNr.NewPredicate(grmi.Equal, demandHead.TaskNr)})
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}

	_ = sessionTX.Commit()
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealIntervalFileDemandHead
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealIntervalFileDemandHead(demandHead model.DemandHead, wg *sync.WaitGroup) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	defer wg.Done()
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	sessionTX := engine.NewSession()
	defer sessionTX.Close()
	err := sessionTX.Begin()
	if err != nil {
		return
	}
	demandHeadDao := dal.NewDemandHeadDAO(session, demandHead.PlantNr, user)
	custOrderDao := dal.NewCustOrderDAO(session, demandHead.PlantNr, user)
	workOrderDao := dal.NewWorkOrderDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(sessionTX, demandHead.PlantNr, user)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(sessionTX, demandHead.PlantNr, user)
	articleDao := baseDal.NewArticleDAO(session, demandHead.PlantNr, user)
	projectDao := meDal.NewProjectDAO(session, demandHead.PlantNr, user)
	project, err := projectDao.SelectOne(baseModel.ProjectId)
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, error: " + err.Error())
		return
	}
	if project == nil {
		log.Error("ParseMesWorkOrder DealMESFileDemandHead get project failed, no data")
		return
	}
	custOrderLi, err := custOrderDao.Select([]grmi.Predicate{meta.CustOrder_TaskNr.NewPredicate(grmi.Equal, demandHead.FileNr)}, []grmi.Field{meta.CustOrder_CustOrderId})
	if err != nil {
		log.Error("ParseINTWorkOrder DealIntervalFileDemandHead get custOrderLi failed, error: " + err.Error())
		return
	}
	// 批次明细数量
	var qty int
	// 物料id
	var partCode string
	// 交付时间日期
	var planDDT = grmi.Date(time.Time{})
	// 临时记录的demandLst
	var preCustOrder model.CustOrder
	tempLi := make([]model.CustOrder, 0, 30)
	for _, custOrder := range custOrderLi {
		if partCode == "" {
			partCode = custOrder.ArtId
		}
		if planDDT == grmi.Date(time.Time{}) {
			planDDT = grmi.Date(custOrder.DDT)
		}
		if partCode != custOrder.ArtId || planDDT != grmi.Date(custOrder.DDT) {
			// 处理workOrder及其相关表
			err := impl.DealINTWorkOrder(sessionTX, demandHead.PlantNr,
				project,
				&preCustOrder,
				float64(qty),
				workOrderDao,
				workOrderStatusDao,
				workOrderQtyDao,
				articleDao)
			if err != nil {
				demandHead.Status = model.DemandHeadUnParsedStatus
				demandHead.ErrNum += 1
				demandHead.ErrorInfo = err.Error()
				_ = demandHeadDao.UpdateOne(&demandHead)
				_ = sessionTX.Rollback()
				return
			}

			// 重置临时变量的状态
			partCode = custOrder.ArtId
			qty = 0
			tempLi = make([]model.CustOrder, 0, 30)
			planDDT = grmi.Date(custOrder.DDT)
		}
		// 外部status 转换成系统status 并进行数量统计
		qty += 1
		tempLi = append(tempLi, custOrder)
		preCustOrder = custOrder
	}
	err = impl.DealINTWorkOrder(sessionTX, demandHead.PlantNr,
		project,
		&preCustOrder,
		float64(qty),
		workOrderDao,
		workOrderStatusDao,
		workOrderQtyDao,
		articleDao)
	if err != nil {
		demandHead.Status = model.DemandHeadUnParsedStatus
		demandHead.ErrNum += 1
		demandHead.ErrorInfo = err.Error()
		_ = demandHeadDao.UpdateOne(&demandHead)
		_ = sessionTX.Rollback()
		return
	}
	demandHead.Status = model.DemandHeadParsedStatus
	demandHead.ErrNum = 0
	demandHead.ErrorInfo = ""
	err = demandHeadDao.UpdateOne(&demandHead)
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}
	_ = sessionTX.Commit()
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealINTWorkOrder
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealINTWorkOrder(session *xorm.Session,pid int,
	project *meModel.Project,
	custOrder *model.CustOrder,
	qty float64,
	workOrderDao dal.WorkOrderDAO,
	workOrderStatusDao dal.WorkOrderStatusDAO,
	workOrderQtyDao dal.WorkOrderQtyDAO,
	articleDao baseDal.ArticleDAO,
) (err error) {
	user := "crontab"
	var workOrder model.WorkOrder
	var workOrderStatus model.WorkOrderStatus
	var workOrderQty model.WorkOrderQty
	log, _ := logger.NewLogger(user, "OM")

	workOrderLi, err := workOrderDao.SelectByEndDate(custOrder.ArtId, custOrder.DDT.Restore().Format("2006-01-02"), baseModel.ProjectId)
	if err != nil {
		return err
	}
	var newWorkOrderSign = true
	if len(workOrderLi) != 0 {
		for _, dbWorkOrder := range workOrderLi {
			if dbWorkOrder.WorkOrderStatus.Status != baseModel.WO_STATUS_UNPLANNED {
				workOrder = dbWorkOrder
				newWorkOrderSign = false
				break
			}
		}
	}

	if newWorkOrderSign {
		article, err := articleDao.SelectOne(custOrder.ArtId)
		if err != nil {
			log.Error("DealINTWorkOrder DealWorkOrder get article failed, error: " + err.Error())
			return err
		}
		if article == nil {
			err = errors.New("不存在对应的物料, artID: " + custOrder.ArtId)
			log.Error("DealINTWorkOrder DealWorkOrder get article failed, error: " + err.Error())
			return err
		}
		snr := new(models.Snrtab)
		snr.Finr = pid
		workOrderId, err := snr.GetNextSnrWithSession(session, project.WorkOrderSnr)
		if err != nil {
			log.Error("DealINTWorkOrder DealWorkOrder get  work order id failed, error: " + err.Error())

			return err
		}
		workOrder = model.WorkOrder{
			WorkOrderId:         workOrderId,
			ArtId:               custOrder.ArtId,
			OrderType:           baseModel.ODER_TYPE_SEQ,
			OrderInfo:           custOrder.ArtDesc,
			OrderType1:          custOrder.ArtTypeId,
			PlanQty:             qty,
			QtyUomId:            article.UomId,
			PlanResourceId:      article.PlanResourceId,
			UsedResourceId:      article.UsedResourceId,
			OpTimePerItem:       article.OpTimePerItem,
			PlanResourceGroupId: article.PlanResourceGroupId,
			ProjectId:           article.ProjectId,
			QuantityPerHour:     article.QuantityPerHour,
			RatePerHourToggle:   true,
			BatchTime:           article.BatchTime,
			BatchingMethod:      article.BatchingMethod,
			PlanStartDate:       grmi.Date(time.Now()),
			PlanEndDate:         grmi.Date(custOrder.DDT),
			PlanEndTime:         custOrder.DDT,
		}
		workOrderStatus = model.WorkOrderStatus{
			WorkOrderId: workOrderId,
			Status:      baseModel.WO_STATUS_UNPLANNED,
		}
		workOrderQty = model.WorkOrderQty{
			WorkOrderId: workOrderId,
			PlanQty:     qty,
		}
		err = workOrderDao.InsertOne(&workOrder)
		if err != nil {
			log.Error("DealINTWorkOrder insert  work order  failed, error: " + err.Error())

			return err
		}
		err = workOrderStatusDao.InsertOne(&workOrderStatus)
		if err != nil {
			log.Error("DealINTWorkOrder insert  work order status failed, error: " + err.Error())

			return err
		}
		err = workOrderQtyDao.InsertOne(&workOrderQty)
		if err != nil {
			log.Error("DealINTWorkOrder insert  work order qty failed, error: " + err.Error())
			return err
		}
	} else {
		workOrderQty = workOrder.WorkOrderQty
		if workOrderQty.PlanQty != qty {
			workOrderQty.PlanQty = qty
			err = workOrderQtyDao.UpdateOne(&workOrderQty)
			if err != nil {
				log.Error("DealINTWorkOrder DealWorkOrder update work order qty, error: " + err.Error())
				return err
			}
		}
	}
	return nil
}

/******************************************************************************
*
* @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.SortTempDemandDataLi
*
******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) SortTempDemandDataLi(tempDemandLi []model.TempDemandLstData) []model.TempDemandLstData {
	for i := 0; i < len(tempDemandLi)-1; i++ {
		for j := 0; j < len(tempDemandLi)-1-i; j++ {
			if tempDemandLi[j].Serial > tempDemandLi[j+1].Serial {
				tempDemandLi[j+1], tempDemandLi[j] = tempDemandLi[j], tempDemandLi[j+1]
			}
		}
	}
	for i := 0; i < len(tempDemandLi)-1; i++ {
		for j := 0; j < len(tempDemandLi)-1-i; j++ {
			if tempDemandLi[j].Seq > tempDemandLi[j+1].Seq {
				tempDemandLi[j+1], tempDemandLi[j] = tempDemandLi[j], tempDemandLi[j+1]
			}
		}
	}
	return tempDemandLi
}

/******************************************************************************
*
* @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealMESDBDemandHeadByTime
*
******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealMESDBDemandHeadByTime(demandHead model.DemandHeadFromDB, wg *sync.WaitGroup) {
	defer wg.Done()
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	sessionTX := engine.NewSession()
	defer sessionTX.Close()
	err := sessionTX.Begin()
	if err != nil {
		return
	}
	demandHeadDao := dal.NewDemandHeadFromDBDAO(session, demandHead.PlantNr, user)
	demandLstDao := dal.NewDemandLstDAO(sessionTX, demandHead.PlantNr, user)
	workOrderDao := dal.NewWorkOrderDAO(sessionTX, demandHead.PlantNr, user)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(sessionTX, demandHead.PlantNr, user)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(sessionTX, demandHead.PlantNr, user)
	artDemandHeadDao := logDal.NewArtDemandHeadCacheDAO(sessionTX, demandHead.PlantNr, user)
	artDemandLstDao := logDal.NewArtDemandLstCacheDAO(sessionTX, demandHead.PlantNr, user)
	projectDao := meDal.NewProjectDAO(session, demandHead.PlantNr, user)
	project, err := projectDao.SelectOne(baseModel.A30PorjectId)
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESDBDemandHeadByTime get project failed, error: " + err.Error())
		return
	}
	if project == nil {
		log.Error("ParseMesWorkOrder DealMESDBDemandHeadByTime get project failed, no data")
		return
	}
	demandLstLi, err := demandLstDao.SelectAndOrderBy(demandHead.TaskNr, "TaskNr")
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESDBDemandHeadByTime get art demandLst failed, error: " + err.Error())
		return
	}
	configKeyLi, err := demandLstDao.SelectDistinctConfigKey(demandHead.TaskNr, "TaskNr")
	if err != nil {
		log.Error("ParseMesWorkOrder DealMESDBDemandHeadByTime get distinct config key failed, error: " + err.Error())
		return
	}
	if len(configKeyLi) == 0 {
		log.Error("ParseMesWorkOrder DealMESDBDemandHeadByTime get distinct config key is zero, taskNr:" + strconv.Itoa(demandHead.TaskNr))
		return
	}
	configKeyMap := make(map[string][]model.DemandLst)
	for _, configKey := range configKeyLi {
		configKeyMap[configKey] = make([]model.DemandLst, 0)
	}
	for _, demandLst := range demandLstLi {
		confKey := demandLst.ConfigKey
		configKeyMap[confKey] = append(configKeyMap[confKey], demandLst)
	}
	tempDemandLi := make([]model.TempDemandLstData, 0)

	for _, lstLi := range configKeyMap {
		tempDemandData := model.TempDemandLstData{}
		tempDemandData.DemandLstLi = make([]model.DemandLst, 0)
		// 批次中最低生产状态
		var minStatus = baseModel.WO_STATUS_UNPLANNED
		// 批次中最高生产状态
		var maxStatus = baseModel.WO_STATUS_UNPLANNED
		for _, demandLst := range lstLi {
			if tempDemandData.Serial == 0 {
				tempDemandData.Serial, _ = strconv.Atoi(demandLst.Serial)
			}
			if tempDemandData.Seq == 0 {
				tempDemandData.Seq = demandLst.Seq
			}
			if tempDemandData.PartCode == "" {
				tempDemandData.PartCode = demandLst.PartCode
			}
			if tempDemandData.PlanEndDate == grmi.Date(time.Time{}) {
				tempDemandData.PlanEndDate = grmi.Date(demandLst.PlanDttm)
			}
			if tempDemandData.PartCode != demandLst.PartCode || tempDemandData.PlanEndDate != grmi.Date(demandLst.PlanDttm) {
				var batchStatus = baseModel.WO_STATUS_RUNNING
				if tempDemandData.CancelQty == tempDemandData.Qty {
					batchStatus = baseModel.WO_STATUS_CANCELED
				} else {
					if maxStatus == minStatus && minStatus == baseModel.WO_STATUS_RELEASED {
						batchStatus = maxStatus
					} else if minStatus >= baseModel.WO_STATUS_FINISHED {
						batchStatus = maxStatus
					}
				}
				tempDemandData.Status = batchStatus
				tempDemandLi = append(tempDemandLi, tempDemandData)
				tempDemandData = model.TempDemandLstData{}
				tempDemandData.Serial, _ = strconv.Atoi(demandLst.Serial)
				tempDemandData.Seq = demandLst.Seq
				tempDemandData.PartCode = demandLst.PartCode
				tempDemandData.DemandLstLi = make([]model.DemandLst, 0)
				tempDemandData.PlanEndDate = grmi.Date(demandLst.PlanDttm)
				minStatus = baseModel.WO_STATUS_UNPLANNED
				maxStatus = baseModel.WO_STATUS_UNPLANNED
			}

			// 外部status 转换成系统status 并进行数量统计
			var status int
			if demandLst.State == model.WO_STATUS_RELEASED {
				status = baseModel.WO_STATUS_RELEASED
			} else if demandLst.State == model.WO_STATUS_RUNNING1 || demandLst.State == model.WO_STATUS_RUNNING2 {
				status = baseModel.WO_STATUS_RUNNING
				tempDemandData.RunningQty += 1
			} else if demandLst.State == model.WO_STATUS_FINISHED1 || demandLst.State == model.WO_STATUS_FINISHED2 {
				status = baseModel.WO_STATUS_FINISHED
				tempDemandData.FinishedQty += 1
			} else if demandLst.State == model.WO_STATUS_DISPATCHED {
				status = baseModel.WO_STATUS_DISPATCHED
				tempDemandData.FinishedQty += 1
			} else if demandLst.State == model.WO_STATUS_CANCELED {
				status = baseModel.WO_STATUS_CANCELED
				tempDemandData.FinishedQty += 1
				tempDemandData.CancelQty += 1
			} else {
				log.Error("ParseMesWorkOrder DealMESFileDemandHead failed get unknown state :" + strconv.Itoa(demandLst.State))
				return
			}
			if status != baseModel.WO_STATUS_CANCELED {
				if minStatus == baseModel.WO_STATUS_UNPLANNED {
					minStatus = status
				}
				if maxStatus == baseModel.WO_STATUS_UNPLANNED {
					maxStatus = status
				}
				if minStatus > status {
					minStatus = status
				}
				if maxStatus < status {
					maxStatus = status
				}
			}
			tempDemandData.Qty += 1
			tempDemandData.DemandLstLi = append(tempDemandData.DemandLstLi, demandLst)
		}
		if len(tempDemandData.DemandLstLi) != 0 {
			var batchStatus = baseModel.WO_STATUS_RUNNING
			if tempDemandData.CancelQty == tempDemandData.Qty {
				batchStatus = baseModel.WO_STATUS_CANCELED
			} else {
				if maxStatus == minStatus && minStatus == baseModel.WO_STATUS_RELEASED {
					batchStatus = maxStatus
				} else if minStatus >= baseModel.WO_STATUS_FINISHED {
					batchStatus = maxStatus
				}
			}
			tempDemandData.Status = batchStatus
			tempDemandLi = append(tempDemandLi, tempDemandData)
		}
	}
	sortedLi := impl.SortTempDemandDataLi(tempDemandLi)
	//var tempCount int
	//for _, item := range sortedLi {
	//	tempCount += len(item.DemandLstLi)
	//}
	err = impl.ClearOldData(workOrderDao, artDemandHeadDao, artDemandLstDao)
	if err != nil {
		demandHead.Status = model.DemandHeadUnParsedStatus
		demandHead.ErrNum += 1
		demandHead.ErrInfo = "删除老数据失败：" + err.Error()
		_ = demandHeadDao.UpdateOne(&demandHead)
		_ = sessionTX.Rollback()
		return
	}
	for _, tempDemandData := range sortedLi {
		if len(tempDemandData.DemandLstLi) == 0 {
			continue
		}
		workOrder, workOrderStatus, workOrderQty, err := impl.DealCacheWorkOrder(demandHead.PlantNr,
			project,
			&tempDemandData.DemandLstLi[0],
			float64(tempDemandData.Qty),
			float64(tempDemandData.RunningQty),
			float64(tempDemandData.FinishedQty),
			float64(tempDemandData.CancelQty),
			workOrderDao,
			workOrderStatusDao,
			workOrderQtyDao,
			tempDemandData.Status)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
		err = impl.DealCacheArtDemand(demandHead.PlantNr,
			project,
			float64(tempDemandData.CancelQty),
			tempDemandData.DemandLstLi,
			workOrder,
			workOrderStatus,
			workOrderQty,
			artDemandHeadDao,
			artDemandLstDao)
		if err != nil {
			demandHead.Status = model.DemandHeadUnParsedStatus
			demandHead.ErrNum += 1
			demandHead.ErrInfo = err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = sessionTX.Rollback()
			return
		}
	}
	demandHead.Status = model.DemandHeadParsedStatus
	demandHead.ErrNum = 0
	demandHead.ErrInfo = ""
	err = demandHeadDao.UpdateOne(&demandHead)
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}
	err = demandLstDao.DeleteWhere([]grmi.Predicate{meta.DemandLst_TaskNr.NewPredicate(grmi.Equal, demandHead.TaskNr)})
	if err != nil {
		_ = sessionTX.Rollback()
		return
	}

	_ = sessionTX.Commit()
	return
}

/******************************************************************************
*
* @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealIntervalFileDemandHead
*
******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) ClearOldData(workOrderDao dal.WorkOrderDAO, headDao logDal.ArtDemandHeadCacheDAO, lstDao logDal.ArtDemandLstCacheDAO) error {
	today := time.Now().Format("2006-01-02")
	err := workOrderDao.DeleteByProjectAndEndDate(baseModel.A30PorjectId, today, model.CacheWorkOrderType)
	if err != nil {
		return err
	}
	err = headDao.DeleteWhere([]grmi.Predicate{logMeta.ArtDemandHeadCache_ProjectId.NewPredicate(grmi.Equal, baseModel.A30PorjectId)})
	if err != nil {
		return err
	}
	err = lstDao.DeleteWhere([]grmi.Predicate{logMeta.ArtDemandLstCache_ProjectId.NewPredicate(grmi.Equal, baseModel.A30PorjectId)})
	return err
}

/******************************************************************************
*
* @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealCacheWorkOrder
*
******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealCacheWorkOrder(pid int,
	project *meModel.Project,
	demandLst *model.DemandLst,
	qty float64,
	runningQty float64,
	finishedQty float64,
	cancelQty float64,
	workOrderDao dal.WorkOrderDAO,
	workOrderStatusDao dal.WorkOrderStatusDAO,
	workOrderQtyDao dal.WorkOrderQtyDAO,
	stateCode int) (workOrder model.WorkOrder, workOrderStatus model.WorkOrderStatus, workOrderQty model.WorkOrderQty, err error) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	snr := new(models.Snrtab)
	snr.Finr = pid
	workOrderId, err := snr.GetNextSnr(project.WorkOrderCacheSnr)
	if err != nil {
		log.Error("ParseMesWorkOrder DealCacheWorkOrder get work order id failed, error: " + err.Error())
		return workOrder, workOrderStatus, workOrderQty, err
	}
	workOrderId = "A30Ca-" + time.Now().Format("060102") + workOrderId
	endTime := demandLst.PlanDttm.Restore()
	endDate := endTime.Format("2006-01-02")
	planStartTimeStr := endDate + " 00:00:00"
	planEndTimeStr := endDate + " 23:59:59"
	planStartTime, _ := time.ParseInLocation("2006-01-02 15:04:05", planStartTimeStr, utils.TimezoneLocation)
	planEndTime, _ := time.ParseInLocation("2006-01-02 15:04:05", planEndTimeStr, utils.TimezoneLocation)
	workOrder = model.WorkOrder{
		WorkOrderId:       workOrderId,
		ArtId:             demandLst.PartCode,
		OrderType:         baseModel.ODER_TYPE_SEQ,
		OrderInfo:         demandLst.BarCodeDesc,
		OrderType2:        model.CacheWorkOrderType,
		PlanResourceId:    demandLst.ConfigDesc,
		UsedResourceId:    demandLst.ConfigDesc,
		PlanQty:           qty,
		ProjectId:         baseModel.A30PorjectId,
		RatePerHourToggle: true,
		PlanStartDate:     grmi.Date(demandLst.PlanDttm),
		PlanEndDate:       grmi.Date(demandLst.PlanDttm),
		PlanStartTime:     grmi.DateTime(planStartTime),
		PlanEndTime:       grmi.DateTime(planEndTime),
	}
	workOrderStatus = model.WorkOrderStatus{
		WorkOrderId: workOrderId,
		Status:      stateCode,
	}
	workOrderQty = model.WorkOrderQty{
		WorkOrderId: workOrderId,
		PlanQty:     qty,
		ReleasedQty: qty,
		ActQty:      finishedQty,
		ActQty1:     runningQty,
		ActQty3: cancelQty,
	}
	err = workOrderDao.InsertOne(&workOrder)
	if err != nil {
		log.Error("ParseMesWorkOrder DealCacheWorkOrder insert  work order  failed, error: " + err.Error())

		return workOrder, workOrderStatus, workOrderQty, err
	}
	err = workOrderStatusDao.InsertOne(&workOrderStatus)
	if err != nil {
		log.Error("ParseMesWorkOrder DealCacheWorkOrder insert  work order status failed, error: " + err.Error())

		return workOrder, workOrderStatus, workOrderQty, err
	}
	err = workOrderQtyDao.InsertOne(&workOrderQty)
	if err != nil {
		log.Error("ParseMesWorkOrder DealCacheWorkOrder insert  work order qty failed, error: " + err.Error())
		return workOrder, workOrderStatus, workOrderQty, err
	}
	return workOrder, workOrderStatus, workOrderQty, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/ParseMesWorkOrder.DealCacheArtDemand
 *
 ******************************************************************************/
func (impl *ParseMesWorkOrderServiceImplement) DealCacheArtDemand(pid int,
	project *meModel.Project,
	cancelQty float64,
	demandLstLi []model.DemandLst,
	workOrder model.WorkOrder,
	workOrderStatus model.WorkOrderStatus,
	workOrderQty model.WorkOrderQty,
	headDao logDal.ArtDemandHeadCacheDAO,
	lstDao logDal.ArtDemandLstCacheDAO) (err error) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	// 此时批次需求状态为26-80之间 不包含80 需要在供应商门户处生成需求数据
	var demandId string
	demandTime := workOrder.PlanEndTime.Restore()
	weekIndex := utils.ParseWeekIndex(demandTime)
	snr := new(models.Snrtab)
	snr.Finr = pid
	demandId, err = snr.GetNextSnr(project.LogDemandCacheSnr)
	if err != nil {
		log.Error("ParseMesWorkOrder DealArtDemand generate  art demand id failed, error: " + err.Error())
		return err
	}
	demandId = "A30-" + time.Now().Format("060102") + demandId
	artDemandHead := logModel.ArtDemandHeadCache{
		OrderType:       workOrder.OrderType,
		UnproducedQty:   workOrderQty.PlanQty - workOrderQty.ActQty - workOrderQty.ActQty1,
		DemandId:        demandId,
		ArtId:           workOrder.ArtId,
		DemandType:      "byDay",
		DemandYear:      demandTime.Year(),
		DemandMonth:     int(demandTime.Month()),
		DemandWeek:      weekIndex,
		DemandTime:      workOrder.PlanEndTime,
		DemandDate:      grmi.Date(demandTime),
		DemandQty:       workOrderQty.PlanQty,
		Status:          logModel.WaitReceivingStatus,
		OrderStatus:     workOrderStatus.Status,
		QtyUomId:        workOrder.QtyUomId,
		ProjectId:       workOrder.ProjectId,
		WorkOrderId:     workOrder.WorkOrderId,
		DemandCtrlPara3: workOrder.OrderInfo,
		PlanResourceId:  workOrder.PlanResourceId,
		CancelQty: cancelQty,
	}
	if artDemandHead.UnproducedQty == 0 {
		artDemandHead.DemandStatus = logModel.DemandOrderStatusAccomplish
	}
	err = headDao.InsertOne(&artDemandHead)
	if err != nil {
		log.Error("ParseMesWorkOrder DealCacheArtDemand insert  art demand failed, error: " + err.Error())

		return err
	}
	artDemandLstInsertLi := make([]logModel.ArtDemandLstCache, 0)
	for _, demandLst := range demandLstLi {
		serial, err := strconv.Atoi(demandLst.Serial)
		if err != nil {
			log.Error("ParseMesWorkOrder DealCacheArtDemand change type serial failed, error: " + err.Error())
			return err
		}
		innerStatus := demandLst.State
		var artDemandStatus int
		// 外部status 转换成内部status
		if innerStatus == model.WO_STATUS_RELEASED {
			artDemandStatus = baseModel.WO_STATUS_RELEASED
		} else if innerStatus == model.WO_STATUS_RUNNING1 || innerStatus == model.WO_STATUS_RUNNING2 {
			artDemandStatus = baseModel.WO_STATUS_RUNNING
		} else if innerStatus == model.WO_STATUS_FINISHED1 || innerStatus == model.WO_STATUS_FINISHED2 {
			artDemandStatus = baseModel.WO_STATUS_FINISHED
		} else if innerStatus == model.WO_STATUS_DISPATCHED {
			artDemandStatus = baseModel.WO_STATUS_DISPATCHED
		} else if innerStatus == model.WO_STATUS_CANCELED {
			artDemandStatus = baseModel.WO_STATUS_CANCELED
		}
		artDemandLst := logModel.ArtDemandLstCache{
			OrderType:       workOrder.OrderType,
			DemandId:        demandId,
			ArtId:           workOrder.ArtId,
			Pos:             demandLst.DemandNr,
			DemandType:      "byDay",
			DemandYear:      demandTime.Year(),
			DemandMonth:     int(demandTime.Month()),
			DemandWeek:      weekIndex,
			DemandTime:      workOrder.PlanEndTime,
			DemandDate:      grmi.Date(demandTime),
			DemandQty:       1,
			Status:          logModel.WaitReceivingStatus,
			OrderStatus:     artDemandStatus,
			QtyUomId:        workOrder.QtyUomId,
			DemandCtrlPara1: serial,
			DemandCtrlPara2: demandLst.Seq,
			DemandCtrlPara3: demandLst.BarCodeDesc,
			ProjectId:       baseModel.A30PorjectId,
			PlanResourceId:  workOrder.PlanResourceId,
		}
		if artDemandStatus >= baseModel.WO_STATUS_RUNNING {
			artDemandLst.UnproducedQty = 0
			artDemandLst.DemandStatus = logModel.DemandOrderStatusAccomplish
		} else {
			artDemandLst.UnproducedQty = 1
		}
		artDemandLstInsertLi = append(artDemandLstInsertLi, artDemandLst)
	}
	// 批量插入时 一次最多插入50条
	demandLstTempLi := make([]logModel.ArtDemandLstCache, 0, 50)
	for index, demandLst := range artDemandLstInsertLi {
		if index%50 == 0 {
			err = lstDao.Insert(&demandLstTempLi)
			if err != nil {
				log.Error("ParseMesWorkOrder DealCacheArtDemand insert art demandLst failed, error: " + err.Error())
				return err
			}
			demandLstTempLi = make([]logModel.ArtDemandLstCache, 0, 50)

		}
		demandLstTempLi = append(demandLstTempLi, demandLst)
	}
	if len(demandLstTempLi) != 0 {

		err = lstDao.Insert(&demandLstTempLi)
		if err != nil {
			log.Error("ParseMesWorkOrder DealCacheArtDemand insert  art demandLst failed, error: " + err.Error())
			return err
		}
	}
	log.Info(fmt.Sprintf("ParseMesWorkOrder DealArtDemand success, art id: %v, num:%d", workOrder.ArtId, len(demandLstLi)))
	return nil
}
