// Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.

package implments

import (
	baseDal "LAPP_ACURA_MOM_BACKEND/dao/base"
	omdal "LAPP_ACURA_MOM_BACKEND/dao/om"
	dal "LAPP_ACURA_MOM_BACKEND/dao/qm"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	baseMeta "LAPP_ACURA_MOM_BACKEND/meta/base"
	meta "LAPP_ACURA_MOM_BACKEND/meta/qm"
	common "LAPP_ACURA_MOM_BACKEND/models/base"
	omModel "LAPP_ACURA_MOM_BACKEND/models/om"
	model "LAPP_ACURA_MOM_BACKEND/models/qm"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"fmt"
	"strconv"
	"time"
)

/******************************************************************************
 *
 * @Description              : DefectRecord的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:18:57
 *
 ******************************************************************************/
var DefaultConditionOfDefectRecord = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.DefectRecord_RecNr.UrlParameterName:          grmi.NewConditionItem(meta.DefectRecord_RecNr, grmi.Equal, true),
		meta.DefectRecord_SerialOrderId.UrlParameterName:  grmi.NewConditionItem(meta.DefectRecord_SerialOrderId, grmi.Equal, false),
		meta.DefectRecord_OperationNr.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_OperationNr, grmi.Equal, false),
		meta.DefectRecord_Qty.UrlParameterName:            grmi.NewConditionItem(meta.DefectRecord_Qty, grmi.Equal, false),
		meta.DefectRecord_ViewId.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_ViewId, grmi.Equal, false),
		meta.DefectRecord_ViewDescr.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_ViewDescr, grmi.Equal, false),
		meta.DefectRecord_ViewPicture.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_ViewPicture, grmi.Equal, false),
		meta.DefectRecord_ViewCode.UrlParameterName:       grmi.NewConditionItem(meta.DefectRecord_ViewCode, grmi.Equal, false),
		meta.DefectRecord_Width.UrlParameterName:          grmi.NewConditionItem(meta.DefectRecord_Width, grmi.Equal, false),
		meta.DefectRecord_Height.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_Height, grmi.Equal, false),
		meta.DefectRecord_EndProduct.UrlParameterName:     grmi.NewConditionItem(meta.DefectRecord_EndProduct, grmi.Equal, false),
		meta.DefectRecord_AreaId.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_AreaId, grmi.Equal, false),
		meta.DefectRecord_XStart.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_XStart, grmi.Equal, false),
		meta.DefectRecord_XEnd.UrlParameterName:           grmi.NewConditionItem(meta.DefectRecord_XEnd, grmi.Equal, false),
		meta.DefectRecord_YStart.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_YStart, grmi.Equal, false),
		meta.DefectRecord_YEnd.UrlParameterName:           grmi.NewConditionItem(meta.DefectRecord_YEnd, grmi.Equal, false),
		meta.DefectRecord_XPos.UrlParameterName:           grmi.NewConditionItem(meta.DefectRecord_XPos, grmi.Equal, false),
		meta.DefectRecord_YPos.UrlParameterName:           grmi.NewConditionItem(meta.DefectRecord_YPos, grmi.Equal, false),
		meta.DefectRecord_ReworkplaceId.UrlParameterName:  grmi.NewConditionItem(meta.DefectRecord_ReworkplaceId, grmi.Equal, false),
		meta.DefectRecord_Status.UrlParameterName:         grmi.NewConditionItem(meta.DefectRecord_Status, grmi.Equal, false),
		meta.DefectRecord_DefectGrpId.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_DefectGrpId, grmi.Equal, false),
		meta.DefectRecord_DefectGrpDescr.UrlParameterName: grmi.NewConditionItem(meta.DefectRecord_DefectGrpDescr, grmi.Equal, false),
		meta.DefectRecord_DefectReasonId.UrlParameterName: grmi.NewConditionItem(meta.DefectRecord_DefectReasonId, grmi.Equal, false),
		meta.DefectRecord_DefectDescr.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_DefectDescr, grmi.Equal, false),
		meta.DefectRecord_InspectTime.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_InspectTime, grmi.Approximate, false),
		meta.DefectRecord_InspectShiftId.UrlParameterName: grmi.NewConditionItem(meta.DefectRecord_InspectShiftId, grmi.Equal, false),
		meta.DefectRecord_Inspector.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_Inspector, grmi.Equal, false),
		meta.DefectRecord_ReworkTime.UrlParameterName:     grmi.NewConditionItem(meta.DefectRecord_ReworkTime, grmi.Approximate, false),
		meta.DefectRecord_ReworkShiftId.UrlParameterName:  grmi.NewConditionItem(meta.DefectRecord_ReworkShiftId, grmi.Equal, false),
		meta.DefectRecord_Reworker.UrlParameterName:       grmi.NewConditionItem(meta.DefectRecord_Reworker, grmi.Equal, false),
		meta.DefectRecord_BuildCode.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_BuildCode, grmi.Equal, false),
		meta.DefectRecord_DDCCustC1.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustC1, grmi.Equal, false),
		meta.DefectRecord_DDCCustC2.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustC2, grmi.Equal, false),
		meta.DefectRecord_DDCCustC3.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustC3, grmi.Equal, false),
		meta.DefectRecord_DDCCustC4.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustC4, grmi.Equal, false),
		meta.DefectRecord_DDCCustI1.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustI1, grmi.Equal, false),
		meta.DefectRecord_DDCCustI2.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustI2, grmi.Equal, false),
		meta.DefectRecord_DDCCustI3.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustI3, grmi.Equal, false),
		meta.DefectRecord_DDCCustI4.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustI4, grmi.Equal, false),
		meta.DefectRecord_DDCCustT1.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustT1, grmi.Approximate, false),
		meta.DefectRecord_DDCCustT2.UrlParameterName:      grmi.NewConditionItem(meta.DefectRecord_DDCCustT2, grmi.Approximate, false),
		meta.DefectRecord_WorkPlaceNr.UrlParameterName:    grmi.NewConditionItem(meta.DefectRecord_WorkPlaceNr, grmi.Equal, false),
		meta.DefectRecord_LastModify.UrlParameterName:     grmi.NewConditionItem(meta.DefectRecord_LastModify, grmi.Approximate, false),
		meta.DefectRecord_LastUser.UrlParameterName:       grmi.NewConditionItem(meta.DefectRecord_LastUser, grmi.Equal, false),
		meta.DefectRecord_CreateTime.UrlParameterName:     grmi.NewConditionItem(meta.DefectRecord_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : DefectRecord的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:18:57
 *
 ******************************************************************************/
var DefaultConditionOfDefectRecordAndPaging = grmi.NewCondition(
	DefaultConditionOfDefectRecord.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : DefectRecordServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : DefectRecord的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:18:57
 *
 ******************************************************************************/
type DefectRecordServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewDefectRecordDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个DefectRecordDAOImplement实例
 *
 * @Return Value             : DefectRecordDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:18:57
 *
 ******************************************************************************/
func NewDefectRecordServiceImplement() *DefectRecordServiceImplement {
	return &DefectRecordServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.InsertOne
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) InsertOne(user *global.User, entity *model.DefectRecord) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "InsertOneDefectRecord", "插入一个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.RecNr)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.DeleteOne
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) DeleteOne(user *global.User, recNr int) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "DeleteOneDefectRecord", "删除一个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(recNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(recNr)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.SelectOne
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) SelectOne(user *global.User, recNr int) (*model.DefectRecord, error) {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "SelectOneDefectRecord", "查询一个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(recNr)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.UpdateOne
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) UpdateOne(user *global.User, entity *model.DefectRecord) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "UpdateOneDefectRecord", "修改一个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.RecNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.Insert
 *
 ******************************************************************************/
// 2021-03-18 chenglei.wei@le-it.com.cn
func (impl *DefectRecordServiceImplement) Insert(user *global.User, entities model.SerialOrderRuting) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "InsertDefectRecord", "插入多个DefectRecord")

	count := len(entities.DefectRecord)

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()

	workLinePlaceDao := baseDal.NewWorkLineWorkPlaceLstDAO(session, user.PlantNr, user.UserId)
	workLineDao := baseDal.NewWorkLineDAO(session, user.PlantNr, user.UserId)
	sdao := dal.NewSerialOrderRutingDAO(session, user.PlantNr, user.UserId)
	OrderInfo, err := sdao.SelectOne(entities.SerialorderId)
	if err != nil {
		return grmi.NewBusinessError("序列订单查询错误!")
	}
	if OrderInfo != nil && OrderInfo.Status == common.CHECK_STATUS_CLOSED {
		return grmi.NewBusinessError("该序列订单已经检测!")
	}

	orderId := entities.SerialorderId

	//获取物料id
	omDao := omdal.NewSerialOrderDAO(session, user.PlantNr, user.UserId)

	result, err := omDao.SelectOne(orderId)
	if err != nil {
		return err
	}
	if result == nil {
		return grmi.NewBusinessError("序列订单不存在!")
	}
	if result.OrderType == common.ORDER_TYPE_PRE {
		return grmi.NewBusinessError("该订单是预装工单!")
	}
	artId := result.ArtId

	orderStatusDAO := omdal.NewSerialOrderStatusDAO(session, user.PlantNr, user.UserId)
	info, err := orderStatusDAO.SelectOne(orderId)
	if err != nil {
		return err
	}
	if info == nil {
		return grmi.NewBusinessError("该记录不存在!")
	}
	if info.Status != common.WO_STATUS_FINISHED {
		return grmi.NewBusinessError("该工单前序未完成!")
	}
	if count <= 0 {
		//判断是否是修复
		if OrderInfo != nil && OrderInfo.Status == common.CHECK_STATUS_RUNNING {
			//判断是否修复
			recordDAO := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
			records, err := recordDAO.Select([]grmi.Predicate{meta.DefectRecord_SerialOrderId.NewPredicate(grmi.Equal, orderId), meta.DefectRecord_Status.NewPredicate(grmi.LessThen, common.ORDER_STATUS_CLOSED)}, nil)
			if err != nil {
				return err
			}
			if records != nil && len(records) > 0 {
				return grmi.NewBusinessError("该序列工单返工未完成!")
			}
			//更新状态
			entities.Status = common.CHECK_STATUS_CLOSED
			entities.IsPack = 0
			entities.ArtId = artId
			err = sdao.UpdateOne(&entities)
			if err != nil {
				return grmi.NewBusinessError("更新记录失败!")
			}
			//更新目检质量状态
			result.QualityCheck = common.QualityCheck_STATUS_FAIL
			result.QualityCheckTime = grmi.DateTime(time.Now())
			err = omDao.UpdateOne(result)
			if err != nil {
				return err
			}
			return nil
		} else {
			/*******无提交记录，即为正常订单********/
			entities.Status = common.CHECK_STATUS_CLOSED
			entities.IsPack = 0
			entities.ArtId = artId
			err = sdao.InsertOne(&entities)
			if err != nil {
				return grmi.NewBusinessError("提交记录失败!")
			}
			//查询产线信息,判断checkFirstPieceTogge是否为1
			workLinePlace, err := workLinePlaceDao.Select([]grmi.Predicate{baseMeta.WorkLineWorkPlaceLst_WorkPlaceNr.NewPredicate(grmi.Equal, entities.WorkPlaceNr)}, nil)
			if err != nil {
				return grmi.NewBusinessError(err.Error())
			}
			if len(workLinePlace) == 0 {
				return grmi.NewBusinessError("没有关联的产线!")
			}
			workInfo, err := workLineDao.SelectOne(workLinePlace[0].WorkLineId)
			if err != nil {
				return grmi.NewBusinessError(err.Error())
			}
			if workInfo.CheckFirstPieceTogge {
				if result.IsFirstPieceToggle {
					//更新订单状态为75
					info.Status = common.WO_STATUS_UNCHECKED
					err = orderStatusDAO.UpdateOne(info)
					if err != nil {
						return err
					}
					//return nil
				}
			}
			//更新目检质量状态
			result.QualityCheck = common.QualityCheck_STATUS_OK
			result.QualityCheckTime = grmi.DateTime(time.Now())
			err = omDao.UpdateOne(result)
			if err != nil {
				return err
			}
			return nil
		}
	}

	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	records, err := dao.Select([]grmi.Predicate{meta.DefectRecord_SerialOrderId.NewPredicate(grmi.Equal, orderId)}, nil)
	if err != nil {
		return err
	}
	if records != nil && len(records) > 0 {
		return grmi.NewBusinessError("该唯一码已经记录过数据!")
	}
	viewDAO := dal.NewViewDAO(session, user.PlantNr, user.UserId)
	groupDAO := dal.NewDefectGrpDAO(session, user.PlantNr, user.UserId)
	reasonDAO := dal.NewDefectReasonDAO(session, user.PlantNr, user.UserId)
	areaDAO := dal.NewViewValstDAO(session, user.PlantNr, user.UserId)
	articleViewDAO := dal.NewArtViewDAO(session, user.PlantNr, user.UserId)
	viewGroupDAO := dal.NewViewDefectGrplstDAO(session, user.PlantNr, user.UserId)
	groupReasonDAO := dal.NewDefectGrpReasonLstDAO(session, user.PlantNr, user.UserId)
	//添加记录
	entities.Status = common.CHECK_STATUS_RUNNING
	entities.ArtId = artId
	entities.IsPack = 0
	err = sdao.InsertOne(&entities)
	if err != nil {
		return grmi.NewBusinessError("提交记录失败!")
	}
	DefectRecord := make([]model.DefectRecord, 0)
	for i := 0; i < len(entities.DefectRecord); i++ {
		entity := entities.DefectRecord[i]
		if entity.XPos == 0 {
			return grmi.NewBusinessError("没有记录横坐标!")
		}
		if entity.YPos == 0 {
			return grmi.NewBusinessError("没有记录纵坐标!")
		}
		view, err := viewDAO.SelectOne(entity.ViewId)
		if err != nil {
			return err
		}
		if view == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到视图:%s!", entity.ViewId))
		}
		group, err := groupDAO.SelectOne(entity.DefectGrpId)
		if err != nil {
			return err
		}
		if group == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到缺陷分组:%s!", entity.DefectGrpId))
		}
		reason, err := reasonDAO.SelectOne(entity.DefectReasonId)
		if err != nil {
			return err
		}
		if reason == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到缺陷原因:%s!", entity.DefectReasonId))
		}
		area, err := areaDAO.SelectOne("public", entity.AreaId)
		if err != nil {
			return err
		}
		if area == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到缺陷原因:%s#%d!", entity.ViewId, entity.AreaId))
		}
		artView, err := articleViewDAO.SelectOne(artId, entity.ViewId)
		if err != nil {
			return err
		}
		if artView == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到Article(%s)和视图(%s)的关联!", artId, entity.ViewId))
		}
		viewGroup, err := viewGroupDAO.SelectOne(entity.ViewId, entity.DefectGrpId)
		if err != nil {
			return err
		}
		if viewGroup == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到视图(%s)和视缺陷分组(%s)的关联!", entity.ViewId, entity.DefectGrpId))
		}
		groupReason, err := groupReasonDAO.SelectOne(entity.DefectGrpId, entity.DefectReasonId)
		if err != nil {
			return err
		}
		if groupReason == nil {
			return grmi.NewBusinessError(fmt.Sprintf("没有找到缺陷分组(%s)和缺陷原因(%s)的关联!", entity.DefectGrpId, entity.DefectReasonId))
		}
		entity.SerialOrderId = entity.OrderId
		entity.Qty = 1
		entity.Status = strconv.Itoa(common.ORDER_STATUS_RELEASED)
		entity.ViewCode = entity.AreaId
		entity.ViewDescr = view.Descr
		entity.ViewPicture = view.Picture
		entity.Width = view.Width
		entity.Height = view.Height
		entity.XStart = area.XStart
		entity.XEnd = area.XStart + area.Width
		entity.YStart = area.YStart
		entity.YEnd = area.YStart + area.Height
		entity.DefectGrpDescr = group.Descr
		entity.DefectDescr = reason.Descr
		entity.InspectTime = grmi.DateTime(time.Now())
		entity.Inspector = user.UserId
		entity.WorkPlaceNr = entities.WorkPlaceNr
		DefectRecord = append(DefectRecord, entity)
	}
	//更新目检质量状态
	result.QualityCheck = common.QualityCheck_STATUS_FAIL
	result.QualityCheckTime = grmi.DateTime(time.Now())
	err = omDao.UpdateOne(result)
	if err != nil {
		return err
	}
	err = dao.Insert(&DefectRecord)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.Delete
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) Delete(user *global.User, entities *[]model.DefectRecord) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "DeleteDefectRecord", "删除多个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.RecNr)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Delete(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.Select
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) Select(user *global.User, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "SelectDefectRecord", "查询DefectRecord")

	condition := DefaultConditionOfDefectRecordAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.Update
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) Update(user *global.User, entities *[]model.DefectRecord) error {

	grmi.Log(user, "/services/qm/implments/DefectRecord.service.impl.go", "UpdateDefectRecord", "修改多个DefectRecord")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.RecNr)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Update(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/qm/DefectRecordService.Rework
 *
 ******************************************************************************/
func (impl *DefectRecordServiceImplement) Rework(user *global.User, recNr int, placeId int) error {

	grmi.Log(user, "/services/qm/implments/QM_DefectRecord.service.impl.go", "Rework", "返工")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewDefectRecordDAO(session, user.PlantNr, user.UserId)
	recDao := dal.NewReclinerReclstDAO(session, user.PlantNr, user.UserId)
	seriDao := omdal.NewSerialOrderDAO(session, user.PlantNr, user.UserId)
	statusDao := omdal.NewSerialOrderStatusDAO(session, user.PlantNr, user.UserId)
	sdao := dal.NewSerialOrderRutingDAO(session, user.PlantNr, user.UserId)
	placeDao := baseDal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)

	record, err := dao.SelectOne(recNr)
	if err != nil {
		session.Rollback()
		return err
	}
	if record == nil {
		session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}

	if record.Status != strconv.Itoa(common.ORDER_STATUS_RELEASED) {
		session.Rollback()
		return grmi.NewBusinessError("状态错误!")
	}
	seriInfo, err := seriDao.SelectBySerialOrder(record.SerialOrderId)
	if err != nil {
		session.Rollback()
		return err
	}
	if seriInfo == nil {
		session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}


	record.Status = strconv.Itoa(common.ORDER_STATUS_CLOSED)
	record.InspectTime = grmi.DateTime(time.Now())
	record.Inspector = user.UserId
	err = dao.UpdateOne(record)
	if err != nil {
		session.Rollback()
		return err
	}
	//查询缺陷是否已经都修复
	records, err := dao.Select([]grmi.Predicate{
		meta.DefectRecord_SerialOrderId.NewPredicate(grmi.Equal, seriInfo.SerialOrderId),
		meta.DefectRecord_Status.NewPredicate(grmi.LessThen, common.ORDER_STATUS_CLOSED),
	}, nil)
	if err != nil {
		session.Rollback()
		return err
	}
	if len(records) == 0{
		//查询订单状态
		statusInfo, err := statusDao.SelectOne(record.SerialOrderId)
		if err != nil {
			session.Rollback()
			return err
		}
		if statusInfo == nil {
			session.Rollback()
			return grmi.NewBusinessError("序列订单查询错误!")
		}
		if statusInfo.Status != common.WO_STATUS_FINISHED {
			return grmi.NewBusinessError("该工单前序未完成!")
		}

		OrderInfo, err := sdao.SelectOne(record.SerialOrderId)
		if err != nil {
			session.Rollback()
			return grmi.NewBusinessError("序列订单查询错误!")
		}
		OrderInfo.Status = common.CHECK_STATUS_CLOSED
		err = sdao.UpdateOne(OrderInfo)
		if err != nil {
			session.Rollback()
			return grmi.NewBusinessError("序列订单更新失败!")
		}
		//添加返修打印记录

		var nextNumberStr string

		orderId := record.SerialOrderId

		if len(orderId) < 11 {
			session.Rollback()
			return grmi.NewBusinessError("订单号长度不合法!")
		}
		//获取机器码
		machineCode := orderId[0:4]
		ColorValue := orderId[10:11]
		now := time.Now()
		year := now.Year()
		month := int(now.Month())
		day := now.Day()
		yearStr := common.YEAR_MAP[year]
		monthStr := common.MONTH_MAP[month]
		dayStr := common.DAY_MAP[day]
		temOrderId := machineCode + yearStr + monthStr + dayStr
		//计算map反转
		seriMap := make(map[int]string)
		for k, v := range common.ReworkMap {
			key := v
			val := k
			seriMap[key] = val
		}
		//查询当天的机器码对应的返修流水号
		reworkData, err := recDao.SelectOneRework(temOrderId)
		if reworkData != nil {
			lastOrderId := reworkData.ReclinerNr
			serialNumber := lastOrderId[7:9]

			nowNumber, ok := common.ReworkMap[serialNumber]
			nextNumber := utils.ValueToInt((nowNumber + 1), 0)
			if ok {
				if nextNumber <= 102 {
					nextNumberStr, ok = seriMap[nextNumber]
					if !ok {
						return grmi.NewBusinessError("流水号生成超出范围!")
					}
				} else {
					return grmi.NewBusinessError("流水号生成超出范围!")
				}
			}
		} else {
			nextNumberStr = seriMap[1]
		}
		if len(nextNumberStr) != 2 {
			session.Rollback()
			return grmi.NewBusinessError("流水号生成错误!")
		}

		//根据工位查询打印机Id
		placeInfo, err := placeDao.SelectOne(placeId)
		if err != nil {
			session.Rollback()
			return err
		}
		if placeInfo == nil {
			session.Rollback()
			return grmi.NewBusinessError("工位信息不存在!")
		}

		serialOrderId := machineCode + yearStr + monthStr + dayStr + nextNumberStr + "0" + ColorValue
		entity := new(model.ReclinerReclst)
		entity.SerialOrderId = seriInfo.SerialOrderId
		entity.ReclinerNr = serialOrderId
		entity.PrinterId = placeInfo.PrinterId
		entity.WorkPlaceNr = placeId
		entity.ArtId = seriInfo.ArtId
		entity.Line = seriInfo.PlanResourceId
		entity.RecType = model.QM_SERI_TYPE
		entity.Status = "N"
		err = recDao.InsertOne(entity)
		if err != nil {
			session.Rollback()
			return err
		}
		//更新原来的flag标识
		seriInfo.GenerateFlag = true
		err = seriDao.UpdateOne(seriInfo)
		if err != nil {
			session.Rollback()
			return err
		}
		//插入新的seriorder条码
		insertSeriOrder := omModel.SerialOrder{}
		insertSeriOrder = *seriInfo
		insertSeriOrder.QualityCheck = common.QualityCheck_STATUS_OK
		insertSeriOrder.SerialOrderId = serialOrderId
		insertSeriOrder.LinkSerialOrderId = seriInfo.SerialOrderId
		if seriInfo.OrderType == common.ODER_TYPE_REODER {
			insertSeriOrder.OriginSerialOrderId = seriInfo.OriginSerialOrderId
		} else {
			insertSeriOrder.OriginSerialOrderId = seriInfo.SerialOrderId
		}
		insertSeriOrder.OrderType = common.ODER_TYPE_REODER
		insertSeriOrder.GenerateFlag = false
		err = seriDao.InsertOne(&insertSeriOrder)
		if err != nil {
			session.Rollback()
			return err
		}
		//插入新的条码状态
		insertSeriOrderStatus := new(omModel.SerialOrderStatus)
		insertSeriOrderStatus.SerialOrderId = insertSeriOrder.SerialOrderId
		insertSeriOrderStatus.Status = common.WO_STATUS_FINISHED
		err = statusDao.InsertOne(insertSeriOrderStatus)
		if err != nil {
			session.Rollback()
			return err
		}
	}
	session.Commit()
	return nil
}
