package implments

import (
	apiDal "LAPP_LF_MOM_BACKEND/dao/api"
	dal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	"LAPP_LF_MOM_BACKEND/infra/logger"
	apiMeta "LAPP_LF_MOM_BACKEND/meta/api"
	meta "LAPP_LF_MOM_BACKEND/meta/om"
	apiModel "LAPP_LF_MOM_BACKEND/models/api"
	baseModel "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"errors"
	uuid "github.com/iris-contrib/go.uuid"
	"strconv"
	"time"
)

/******************************************************************************
 *
 * @Struct Name              : OmToMesServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : OmAndMes的服务实现
 *
 * @Author                   : zhangxin
 *
 * @Date                     : 2021-05-10
 *
 ******************************************************************************/
type OmToMesServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewOmToMesServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个OmAndMesServiceImplement实例
 *
 * @Return Value             : OmAndMesServiceImplement实例
 *
 * @Author                   : zhangxin
 *
 * @Date                     : 2021-05-10
 *
 ******************************************************************************/
func NewOmToMesServiceImplement() *OmToMesServiceImplement {
	return &OmToMesServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.TransferWorkOrderToMes
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) TransferWorkOrderToMes(plantNr int) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	workOrderStatusRecDao := dal.NewWorkOrderStatusRecLstDAO(session, plantNr, user)
	// 通过查询WorkOrderStatusRecLst表获取需要导入到mes的work order 拼接数据 
	workOrderJoinLi, err := workOrderStatusRecDao.GetWorkOrderToMes()
	if err != nil {
		log.Error("TransferWorkOrderToMes get workOrder from db failed, error:" + err.Error())
		return
	}

	mesWorkOrderLi := make([]apiModel.ACCWOWORKORDERHEADER, 0, len(workOrderJoinLi))
	workOrderIds := make([]string, 0, len(workOrderJoinLi))
	// 拼接mes系统的work order 数据
	for _, workOrderJoin := range workOrderJoinLi {
		workOrderIds = append(workOrderIds, workOrderJoin.WorkOrder.WorkOrderId)
		orderHeader := apiModel.ACCWOWORKORDERHEADER{
			WONO:           workOrderJoin.WorkOrder.WorkOrderId,
			LINE:           workOrderJoin.WorkOrder.UsedResourceId,
			PARTNO:         workOrderJoin.WorkOrder.ArtId,
			REV:            "0",
			PLANSTARTTIME:  workOrderJoin.WorkOrder.PlanStartTime,
			PLANFINISHTIME: workOrderJoin.WorkOrder.PlanEndTime,
			PLANQUANTITY:   int(workOrderJoin.WorkOrderQty.PlanQty),
			STATUS:         model.MesOrderStatusRelease,
		}
		mesWorkOrderLi = append(mesWorkOrderLi, orderHeader)
	}
	log.Debug("TransferWorkOrderToMes need transfer workOrder length:"+strconv.Itoa(len(workOrderJoinLi))+"workOrderIds:", workOrderIds)
	slaves := db.Eloquent.Slaves()
	if len(slaves) == 0 {
		log.Error("TransferWorkOrderToMes mes db not exist")
		return
	}
	mesDB := slaves[0]
	mesSession := mesDB.NewSession()
	headerDao := apiDal.NewACCWOWORKORDERHEADERDAO(mesSession, user)
	err = headerDao.Insert(&mesWorkOrderLi)
	if err != nil {
		log.Error("TransferWorkOrderToMes insert mes order header failed, error:" + err.Error())
		// 进行失败计数 和 数据传输状态更新
		impl.AfterTransferWorkOrder(&workOrderJoinLi, plantNr, false)
		return
	} else {
		// 进行数据传输状态更新
		impl.AfterTransferWorkOrder(&workOrderJoinLi, plantNr, true)
		log.Debug("TransferWorkOrderToMes transfer work order to mes success workOrderIds:", workOrderIds)
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.AfterTransferWorkOrderFailed
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) AfterTransferWorkOrder(workOrderJoinLi *[]model.VOmWorkorderJoinRec, plantNr int, result bool) {
	log, _ := logger.NewLogger("crontab", "OM")
	statusRecLi := make([]model.WorkOrderStatusRecLst, 0, len(*workOrderJoinLi))
	for _, workOrderJoin := range *workOrderJoinLi {
		statusRec := workOrderJoin.StatusRec
		if result {
			statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_HANDLED
		} else {
			statusRec.OutputErrNum += 1
			if statusRec.OutputErrNum >= model.MesOutputRetryNum {
				statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_HANDLE_FAILED
			} else {
				statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_UNHANDLED
			}
		}

		statusRecLi = append(statusRecLi, statusRec)
	}
	session := db.Eloquent.Master().NewSession()
	statusRecDao := dal.NewWorkOrderStatusRecLstDAO(session, plantNr, "crontab")
	err := statusRecDao.Update(&statusRecLi)
	if err != nil {
		log.Error("AfterTransferWorkOrderFailed update work order status rec failed, error:" + err.Error())
		return
	}
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.TransferSerialOrderToMes
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) TransferSerialOrderToMes(plantNr int) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	// 通过OM_SerialOrderStatusRecLst表来查询需要导入到mes系统的serialOrder拼接数据
	serialOrderStatusRecDao := dal.NewSerialOrderStatusRecLstDAO(session, plantNr, user)
	serialOrderJoinLi, err := serialOrderStatusRecDao.GetSerialOrderToMes()
	if err != nil {
		log.Error("TransferSerialOrderToMes get serial order from db failed, error:" + err.Error())
		return
	}
	serialOrderIds := make([]string, 0, len(serialOrderJoinLi))
	mesSerialOrderLi := make([]apiModel.ACCWOWORKORDERDETAIL, 0, len(serialOrderJoinLi))
	// 进行 mes系统的detail数据拼接
	for _, serialOrderJoin := range serialOrderJoinLi {
		serialOrderIds = append(serialOrderIds, serialOrderJoin.SerialOrderId)
		orderHeader := apiModel.ACCWOWORKORDERDETAIL{
			WONO:   serialOrderJoin.WorkOrderId,
			LINE:   serialOrderJoin.UsedResourceId,
			PARTNO: serialOrderJoin.ArtId,
			REV:    "0",
			UNITSN: serialOrderJoin.SerialOrderId,
			STATUS: model.MesOrderStatusRelease,
		}
		mesSerialOrderLi = append(mesSerialOrderLi, orderHeader)
	}
	log.Debug("TransferSerialOrderToMes transfer serialOrder len:"+strconv.Itoa(len(serialOrderJoinLi))+" serialOrderIds:", serialOrderIds)

	slaves := db.Eloquent.Slaves()
	if len(slaves) == 0 {
		log.Error("TransferSerialOrderToMes mes db not exist")
		return
	}
	mesDB := slaves[0]
	mesSession := mesDB.NewSession()
	detailDao := apiDal.NewACCWOWORKORDERDETAILDAO(mesSession, user)
	err = detailDao.Insert(&mesSerialOrderLi)
	if err != nil {
		log.Error("TransferSerialOrderToMes insert mes order header failed, error:" + err.Error())
		// 进行失败计数及 数据传输状态更新
		impl.AfterTransferSerialOrder(&serialOrderJoinLi, plantNr, false)
	} else {
		// 数据传输状态更新
		impl.AfterTransferSerialOrder(&serialOrderJoinLi, plantNr, true)
		log.Debug("TransferSerialOrderToMes transfer work order to mes success, serialOrderIds:", serialOrderIds)
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.AfterTransferSerialOrderFailed
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) AfterTransferSerialOrder(serialOrderJoinLi *[]model.VOmSerialOrderJoinRec, plantNr int, result bool) {
	log, _ := logger.NewLogger("crontab", "OM")
	statusRecLi := make([]model.SerialOrderStatusRecLst, 0, len(*serialOrderJoinLi))
	for _, serialOrderJoin := range *serialOrderJoinLi {
		statusRec := serialOrderJoin.StatusRec
		if result {
			statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_HANDLED
		} else {
			statusRec.OutputErrNum += 1
			if statusRec.OutputErrNum >= model.MesOutputRetryNum {
				statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_HANDLE_FAILED
			} else {
				statusRec.OutputStatus = baseModel.OUTPUT_TRIGGER_UNHANDLED
			}
		}
		statusRecLi = append(statusRecLi, statusRec)
	}
	session := db.Eloquent.Master().NewSession()
	statusRecDao := dal.NewSerialOrderStatusRecLstDAO(session, plantNr, "crontab")
	err := statusRecDao.Update(&statusRecLi)
	if err != nil {
		log.Error("AfterTransferSerialOrderFailed update serial order status rec failed, error:" + err.Error())
		return
	}
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.FeedbackFromMes
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) FeedbackFromMes(plantNr int) {
	uid, err := uuid.NewV1()
	if err != nil {
		return
	}
	feedbackId := uid.String()
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	slaves := db.Eloquent.Slaves()
	if len(slaves) == 0 {
		log.Error("TransferSerialOrderToMes mes db not exist", "feedback id:"+feedbackId)
		return
	}
	mesEngine := slaves[0]
	mesSession := mesEngine.NewSession()
	// 开启mes数据库事务
	if err := mesSession.Begin(); err != nil {
		log.Error("FeedbackFromMes begin mes tx failed, error:"+err.Error(), "feedback id:"+feedbackId)
		return
	}
	headerDao := apiDal.NewACCWOWORKORDERHEADERDAO(mesSession, user)
	detailDao := apiDal.NewACCWOWORKORDERDETAILDAO(mesSession, user)
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	// 开启aps数据库事务
	if err := session.Begin(); err != nil {
		log.Error("FeedbackFromMes begin mes tx failed, error:"+err.Error(), "feedback id:"+feedbackId)
		return
	}
	workOrderDao := dal.NewWorkOrderDAO(session, plantNr, user)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(session, plantNr, user)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(session, plantNr, user)
	workOrderStatusRecDao := dal.NewWorkOrderStatusRecLstDAO(session, plantNr, user)
	serialOrderDao := dal.NewSerialOrderDAO(session, plantNr, user)
	serialOrderStatusDao := dal.NewSerialOrderStatusDAO(session, plantNr, user)
	serialOrderStatusRecDao := dal.NewSerialOrderStatusRecLstDAO(session, plantNr, user)

	// 获取status是 MesOrderStatusRelease 的header list
	headerLi, err := headerDao.Select([]grmi.Predicate{apiMeta.ACCWOWORKORDERHEADER_STATUS.NewPredicate(grmi.Equal, model.MesOrderStatusRelease)}, []grmi.Field{apiMeta.ACCWOWORKORDERHEADER_WONO}, 10)
	if err != nil {
		log.Error("FeedbackFromMes get header data from mes db failed, error:"+err.Error(), "feedback id:"+feedbackId)
		_ = mesSession.Rollback()
		_ = session.Rollback()
		return
	}
	if len(headerLi) == 0 {
		log.Debug("FeedbackFromMes get header data from mes db is zero", "feedback id:"+feedbackId)
		_ = mesSession.Rollback()
		_ = session.Rollback()
		return
	}
	workOrderIds := make([]string, 0, len(headerLi))
	// 通过读取header下面的detail 处理每一个header的数据
	for _, mesWorkOrder := range headerLi {
		workOrderJoin, err := workOrderDao.SelectOneJoin(mesWorkOrder.WONO)
		if err != nil {
			log.Error("FeedbackFromMes get workOrder from db failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
			_ = session.Rollback()
			_ = mesSession.Rollback()
			return
		}
		if workOrderJoin == nil {
			log.Error("FeedbackFromMes workOrder not exist workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
			_ = session.Rollback()
			_ = mesSession.Rollback()
			return
		}
		cancelQty := workOrderJoin.WorkOrderQty.ActQty3
		workOrderIds = append(workOrderIds, mesWorkOrder.WONO)
		feedbackWorkOrder, err := impl.dealWorkOrderHeader(mesWorkOrder, headerDao, detailDao, serialOrderDao, serialOrderStatusDao, serialOrderStatusRecDao, user, feedbackId, int(cancelQty))
		if err != nil {
			log.Error("FeedbackFromMes deal workOrder header failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
			_ = mesSession.Rollback()
			_ = session.Rollback()
			return
		}
		if feedbackWorkOrder.ACCWOWORKORDERHEADER == nil {
			log.Info("FeedbackFromMes mes work order header not need deal", "feedback id:"+feedbackId)
			//_ = mesSession.Rollback()
			//_ = session.Rollback()
			//return
			continue
		}

		// 更新work order 数量变化
		workOrderQty := workOrderJoin.WorkOrderQty
		workOrderStatus := workOrderJoin.WorkOrderStatus
		workOrder := workOrderJoin.WorkOrder
		workOrderQty.ActQty = float64(feedbackWorkOrder.QUANTITY)
		workOrderQty.ActGoodQty = float64(feedbackWorkOrder.AccomplishedNum)
		workOrderQty.ActScrapQty = float64(feedbackWorkOrder.ScrapyNum)
		workOrderQty.ActQty1 = float64(feedbackWorkOrder.NGNum)
		err = workOrderQtyDao.UpdateOne(&workOrderQty)
		if err != nil {
			log.Error("FeedbackFromMes update workOrder qty failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
			_ = session.Rollback()
			_ = mesSession.Rollback()
			return
		}
		// 更新work order 状态变化
		if feedbackWorkOrder.STATUS == model.MesOrderStatusAccomplished {
			if workOrderStatus.Status != baseModel.WO_STATUS_FINISHED {
				statusRec := model.WorkOrderStatusRecLst{
					WorkOrderId: workOrderStatus.WorkOrderId,
					PrevStatus:  workOrderStatus.Status,
					Status:      baseModel.WO_STATUS_FINISHED,
					StartTime:   feedbackWorkOrder.STARTTIME,
					EndTime:     feedbackWorkOrder.FINISHTIME,
				}
				err = workOrderStatusRecDao.InsertOne(&statusRec)
				if err != nil {
					log.Error("FeedbackFromMes insert workOrder status rec failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
					_ = session.Rollback()
					_ = mesSession.Rollback()
					return
				}
				workOrderStatus.Status = baseModel.WO_STATUS_FINISHED
				err = workOrderStatusDao.UpdateOne(&workOrderStatus)
				if err != nil {
					log.Error("FeedbackFromMes update workOrder status failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
					_ = session.Rollback()
					_ = mesSession.Rollback()
					return
				}
			}
		} else {
			if workOrderQty.ActQty > 0 && workOrderStatus.Status != baseModel.WO_STATUS_RUNNING && workOrderQty.ActQty > workOrderQty.ActQty3 {
				statusRec := model.WorkOrderStatusRecLst{
					WorkOrderId: workOrderStatus.WorkOrderId,
					PrevStatus:  workOrderStatus.Status,
					Status:      baseModel.WO_STATUS_RUNNING,
					StartTime:   feedbackWorkOrder.STARTTIME,
					EndTime:     feedbackWorkOrder.FINISHTIME,
				}
				err = workOrderStatusRecDao.InsertOne(&statusRec)
				if err != nil {
					log.Error("FeedbackFromMes insert workOrder status running rec failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
					_ = session.Rollback()
					_ = mesSession.Rollback()
					return
				}
				workOrderStatus.Status = baseModel.WO_STATUS_RUNNING
				err = workOrderStatusDao.UpdateOne(&workOrderStatus)
				if err != nil {
					log.Error("FeedbackFromMes update workOrder status running failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
					_ = session.Rollback()
					_ = mesSession.Rollback()
					return
				}
			}
		}
		// 更新work order 的时间开始时间和时间结束时间
		if workOrder.ActStartTime != feedbackWorkOrder.STARTTIME || workOrder.ActEndTime != feedbackWorkOrder.FINISHTIME {
			workOrder.ActStartTime = feedbackWorkOrder.STARTTIME
			workOrder.ActEndTime = feedbackWorkOrder.FINISHTIME
			err = workOrderDao.UpdateOne(&workOrder)
			if err != nil {
				log.Error("FeedbackFromMes update workOrder failed, error:"+err.Error()+" workOrderId: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
				_ = session.Rollback()
				_ = mesSession.Rollback()
				return
			}
		}
		log.Info("FeedbackFromMes feedback success one workOrder, workOrderID:"+workOrder.WorkOrderId, "feedback id:"+feedbackId)
	}
	_ = session.Commit()
	_ = mesSession.Commit()
	log.Info("FeedbackFromMes feedback task success, workOrderIds:", workOrderIds, "feedback id:"+feedbackId)
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/OmToMesServiceImplement.dealWorkOrderHeader
 *
 ******************************************************************************/
func (impl *OmToMesServiceImplement) dealWorkOrderHeader(mesWorkOrder apiModel.ACCWOWORKORDERHEADER,
	headerDao apiDal.ACCWOWORKORDERHEADERDAO,
	detailDao apiDal.ACCWOWORKORDERDETAILDAO,
	serialOrderDao dal.SerialOrderDAO,
	serialOrderStatusDao dal.SerialOrderStatusDAO,
	serialOrderStatusRecDao dal.SerialOrderStatusRecLstDAO,
	user string,
	feedbackId string,
	cancelQty int) (feedbackWorkOrder apiModel.AccWorkOrderHeaderJoin, err error) {
	log, _ := logger.NewLogger(user, "OM")
	// 查询改header下的detail list
	detailLi, err := detailDao.Select([]grmi.Predicate{apiMeta.ACCWOWORKORDERDETAIL_WONO.NewPredicate(grmi.Equal, mesWorkOrder.WONO)}, []grmi.Field{apiMeta.ACCWOWORKORDERDETAIL_UNITSN})
	if err != nil {
		return feedbackWorkOrder, err
	}
	if len(detailLi) == 0 {
		log.Debug("dealWorkOrderHeader get detail order from db is zero, workOrderId:"+mesWorkOrder.WONO, "feedback id:"+feedbackId)
		return
	}
	// 获取第一个detail 用于记录header的实际开始时间 start time
	firstDetail := detailLi[0]
	if firstDetail.STATUS == model.MesOrderStatusRelease {
		log.Debug("dealWorkOrderHeader workOrder not begin work, workOrderId:"+mesWorkOrder.WONO, "feedback id:"+feedbackId)
		return
	}
	serialOrderLi, err := serialOrderDao.Select([]grmi.Predicate{meta.SerialOrder_WorkOrderId.NewPredicate(grmi.Equal, mesWorkOrder.WONO)}, nil)
	if err != nil {
		log.Error("dealWorkOrderHeader get serial order list failed, error:"+err.Error(), " workOrderID: "+mesWorkOrder.WONO, "feedback id:"+feedbackId)
		return feedbackWorkOrder, err
	}
	if len(serialOrderLi) == 0 {
		log.Error("dealWorkOrderHeader select serialOrderLi is zero, workOrderId:"+mesWorkOrder.WONO, "feedback id:"+feedbackId)
		return feedbackWorkOrder, errors.New("未获取到该批次工单下的序列工单")
	}
	serialOrderMap := make(map[string]model.SerialOrder, len(serialOrderLi))
	for _, serialOrder := range serialOrderLi {
		serialOrderMap[serialOrder.SerialOrderId] = serialOrder
	}
	// header 完成的数量
	var finishQty int
	// header OK的数量
	var accomplishedNum int
	// header NG的数量
	var NgNum int
	// header 报废的数量
	var scrapyNum int
	// 进行数量统计
	for _, detail := range detailLi {
		var innerStatus int
		if detail.STATUS == model.MesOrderStatusRelease {
			break
		} else if detail.STATUS == model.MesOrderStatusAccomplished {
			innerStatus = baseModel.WO_STATUS_FINISHED
			accomplishedNum++
		} else if detail.STATUS == model.MesOrderStatusScraped {
			innerStatus = baseModel.WO_STATUS_FINISHED
			scrapyNum++
		} else if detail.STATUS == model.MesOrderStatusNG {
			innerStatus = baseModel.WO_STATUS_FINISHED
			NgNum++
		} else {
			log.Error("dealWorkOrderHeader get unknown work order detail, workOrderId:"+mesWorkOrder.WONO+" status: "+strconv.Itoa(detail.STATUS), "feedback id:"+feedbackId)
		}
		serialOrder, exist := serialOrderMap[detail.UNITSN]
		if !exist {
			log.Error("dealWorkOrderHeader serialOrder not exist, workOrderId:"+mesWorkOrder.WONO+" serialOrderId: "+detail.UNITSN, "feedback id:"+feedbackId)
			continue
		}
		if serialOrder.SerialOrderStatus.Status < innerStatus {
			serialOrderStatus := serialOrder.SerialOrderStatus
			statusRec := model.SerialOrderStatusRecLst{
				SerialOrderId: detail.UNITSN,
				PrevStatus:    serialOrderStatus.Status,
				Status:        innerStatus,
				StartTime:     detail.SYNCTIME,
				EndTime:       detail.SYNCTIME,
			}
			_, exist := baseModel.AccomplishWorkLineMap[serialOrder.PlanResourceId]
			if exist {
				serialOrder.ActEndTime = detail.SYNCTIME
				err = serialOrderDao.UpdateOne(&serialOrder)
				if err != nil {
					log.Error("dealWorkOrderHeader update serialOrder ActEndTime failed, error:"+err.Error()+" serialOrderId: "+detail.UNITSN, "feedback id:"+feedbackId)
					return feedbackWorkOrder, err
				}
			}
			err = serialOrderStatusRecDao.InsertOne(&statusRec)
			if err != nil {
				log.Error("dealWorkOrderHeader insert serialOrder status rec failed, error:"+err.Error()+" serialOrderId: "+detail.UNITSN, "feedback id:"+feedbackId)
				return feedbackWorkOrder, err
			}
			serialOrderStatus.Status = innerStatus
			err = serialOrderStatusDao.UpdateOne(&serialOrderStatus)
			if err != nil {
				log.Error("dealWorkOrderHeader update serialOrder status failed, error:"+err.Error()+" serialOrderId: "+detail.UNITSN, "feedback id:"+feedbackId)
				return feedbackWorkOrder, err
			}
		}
	}
	// 更新header 的数据
	finishQty = accomplishedNum + NgNum + scrapyNum + cancelQty
	mesWorkOrder.QUANTITY = finishQty
	mesWorkOrder.STARTTIME = firstDetail.SYNCTIME
	mesWorkOrder.SYNCTIME = grmi.DateTime(time.Now())
	if mesWorkOrder.PLANQUANTITY == mesWorkOrder.QUANTITY {
		mesWorkOrder.STATUS = model.MesOrderStatusAccomplished
		lastDetail := detailLi[len(detailLi)-1]
		mesWorkOrder.FINISHTIME = lastDetail.SYNCTIME
	}
	err = headerDao.UpdateOne(&mesWorkOrder)
	if err != nil {
		log.Error("dealWorkOrderHeader update work order failed, error:"+err.Error()+" workOrderId:"+mesWorkOrder.WONO, "feedback id:"+feedbackId)
		return
	}
	// 拼接返回的header数据
	feedbackWorkOrder.ACCWOWORKORDERHEADER = &mesWorkOrder
	feedbackWorkOrder.NGNum = NgNum
	feedbackWorkOrder.ScrapyNum = scrapyNum
	feedbackWorkOrder.AccomplishedNum = accomplishedNum
	feedbackWorkOrder.CancelNum = cancelQty
	return feedbackWorkOrder, nil

}
