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

package implments

import (
	"LAPP_LF_MOM_BACKEND/container"
	"LAPP_LF_MOM_BACKEND/dao/base"
	basedal "LAPP_LF_MOM_BACKEND/dao/base"
	omdal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/utils"
	"fmt"
	"strings"

	//medal "LAPP_LF_MOM_BACKEND/dao/me"
	dal "LAPP_LF_MOM_BACKEND/dao/log"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	bmeta "LAPP_LF_MOM_BACKEND/meta/base"
	meta "LAPP_LF_MOM_BACKEND/meta/log"
	bmodel "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/log"
	"LAPP_LF_MOM_BACKEND/web/models"
	"github.com/go-xorm/xorm"
	"time"
)

/******************************************************************************
 *
 * @Description              : PackOrder的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:13:21
 *
 ******************************************************************************/
var DefaultConditionOfPackOrder = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.PackOrder_PackOrderId.UrlParameterName:     grmi.NewConditionItem(meta.PackOrder_PackOrderId, grmi.Equal, true),
		meta.PackOrder_OrderInfo.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_OrderInfo, grmi.Equal, false),
		meta.PackOrder_PackTemplateId.UrlParameterName:  grmi.NewConditionItem(meta.PackOrder_PackTemplateId, grmi.Equal, false),
		meta.PackOrder_PackTypeId.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_PackTypeId, grmi.Equal, false),
		meta.PackOrder_TerminalId.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_TerminalId, grmi.Equal, false),
		meta.PackOrder_PersonNr.UrlParameterName:        grmi.NewConditionItem(meta.PackOrder_PersonNr, grmi.Equal, false),
		meta.PackOrder_ShiftId.UrlParameterName:         grmi.NewConditionItem(meta.PackOrder_ShiftId, grmi.Equal, false),
		meta.PackOrder_MaterialId.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_MaterialId, grmi.Equal, false),
		meta.PackOrder_Status.UrlParameterName:          grmi.NewConditionItem(meta.PackOrder_Status, grmi.Equal, false),
		meta.PackOrder_ShortPack.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_ShortPack, grmi.Equal, false),
		meta.PackOrder_ShortBy.UrlParameterName:         grmi.NewConditionItem(meta.PackOrder_ShortBy, grmi.Equal, false),
		meta.PackOrder_ShortTime.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_ShortTime, grmi.Approximate, false),
		meta.PackOrder_ShipStatus.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_ShipStatus, grmi.Equal, false),
		meta.PackOrder_PlanQty.UrlParameterName:         grmi.NewConditionItem(meta.PackOrder_PlanQty, grmi.Equal, false),
		meta.PackOrder_ActQty.UrlParameterName:          grmi.NewConditionItem(meta.PackOrder_ActQty, grmi.Equal, false),
		meta.PackOrder_OpenTime.UrlParameterName:        grmi.NewConditionItem(meta.PackOrder_OpenTime, grmi.Approximate, false),
		meta.PackOrder_CloseTime.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_CloseTime, grmi.Approximate, false),
		meta.PackOrder_BackFlushStatus.UrlParameterName: grmi.NewConditionItem(meta.PackOrder_BackFlushStatus, grmi.Equal, false),
		meta.PackOrder_BackFlushTime.UrlParameterName:   grmi.NewConditionItem(meta.PackOrder_BackFlushTime, grmi.Approximate, false),
		meta.PackOrder_BoxSid.UrlParameterName:          grmi.NewConditionItem(meta.PackOrder_BoxSid, grmi.Equal, false),
		meta.PackOrder_SyncSid.UrlParameterName:         grmi.NewConditionItem(meta.PackOrder_SyncSid, grmi.Equal, false),
		meta.PackOrder_PKOCustC1.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_PKOCustC1, grmi.Equal, false),
		meta.PackOrder_PKOCustC2.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_PKOCustC2, grmi.Equal, false),
		meta.PackOrder_PKOCustI1.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_PKOCustI1, grmi.Equal, false),
		meta.PackOrder_PKOCustI2.UrlParameterName:       grmi.NewConditionItem(meta.PackOrder_PKOCustI2, grmi.Equal, false),
		meta.PackOrder_WorkPlaceNr.UrlParameterName:     grmi.NewConditionItem(meta.PackOrder_WorkPlaceNr, grmi.Equal, false),
		meta.PackOrder_LastModify.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_LastModify, grmi.Approximate, false),
		meta.PackOrder_LastUser.UrlParameterName:        grmi.NewConditionItem(meta.PackOrder_LastUser, grmi.Equal, false),
		meta.PackOrder_CreateTime.UrlParameterName:      grmi.NewConditionItem(meta.PackOrder_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : PackOrder的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:13:21
 *
 ******************************************************************************/
var DefaultConditionOfPackOrderAndPaging = grmi.NewCondition(
	DefaultConditionOfPackOrder.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Description              : 查询Article对应包装模板
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-23
 *
 ******************************************************************************/
var ConditionOfPackTemplatesOfArticle = grmi.NewCondition(
	map[string]grmi.ConditionItem{},
	nil,
)

/******************************************************************************
 *
 * @Description              : 查询包装单所属包装项
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-23
 *
 ******************************************************************************/
var ConditionOfItemsOfPackOrder = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.PackOrderItemlst_PackOrderId.UrlParameterName: grmi.NewConditionItem(meta.PackOrderItemlst_PackOrderId, grmi.Equal, true),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : 查询包装单模板所属包装项模板
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23
 *
 ******************************************************************************/
var ConditionOfItemsOfPackOrderTemplate = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.PackTemplateItemlst_PackTemplateId.UrlParameterName: grmi.NewConditionItem(meta.PackTemplateItemlst_PackTemplateId, grmi.Equal, true),
	},
	nil,
)

/******************************************************************************
 *
 * @Struct Name              : PackOrderServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : PackOrder的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:13:21
 *
 ******************************************************************************/
type PackOrderServiceImplement struct {
	session *container.SessionContext
}

func (impl *PackOrderServiceImplement) SetSession(value *container.SessionContext) {

	impl.session = value
}

/******************************************************************************
 *
 * @Function Name            : NewPackOrderDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个PackOrderDAOImplement实例
 *
 * @Return Value             : PackOrderDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 16:13:21
 *
 ******************************************************************************/
func NewPackOrderServiceImplement() *PackOrderServiceImplement {
	return &PackOrderServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.InsertOne
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) InsertOne(user *models.Usertab, entity *model.PackOrder) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "InsertOnePackOrder", "插入一个PackOrder")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.DeleteOne
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) DeleteOne(user *models.Usertab, packOrderId string) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "DeleteOnePackOrder", "删除一个PackOrder")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.SelectOne
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) SelectOne(user *models.Usertab, packOrderId string) (*model.PackOrder, error) {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "SelectOnePackOrder", "查询一个PackOrder")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(packOrderId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.UpdateOne
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) UpdateOne(user *models.Usertab, entity *model.PackOrder) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "UpdateOnePackOrder", "修改一个PackOrder")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.Insert
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) Insert(user *models.Usertab, entities *[]model.PackOrder) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "InsertPackOrder", "插入多个PackOrder")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.PackOrderId)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
	}

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.Delete
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) Delete(user *models.Usertab, entities *[]model.PackOrder) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "DeletePackOrder", "删除多个PackOrder")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.Select
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) Select(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "SelectPackOrder", "查询PackOrder")

	condition := DefaultConditionOfPackOrderAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewPackOrderDAO(session, user.Pid, 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_LF_MOM_BACKEND/services/log/PackOrderService.SelectList
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) SelectList(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "SelectPackOrder", "查询PackOrder")

	condition := DefaultConditionOfPackOrderAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if !utils.ValueIsEmpty(urlParameters["serialOrderId"]) {
		itemdao := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
		data, err := itemdao.SelectOneByOrder(urlParameters["serialOrderId"])
		if err != nil {
			return nil, err
		}
		if data == nil {
			return nil, nil
		}
		//查询条码对应的包装单
		urlParameters["packOrderId"] = data.PackOrderId
		delete(urlParameters, "serialOrderId")
	}
	fmt.Println(urlParameters)
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewPackOrderDAO(session, user.Pid, 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_LF_MOM_BACKEND/services/log/PackOrderService.Update
 *
 ******************************************************************************/
func (impl *PackOrderServiceImplement) Update(user *models.Usertab, entities *[]model.PackOrder) error {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "UpdatePackOrder", "修改多个PackOrder")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.ClosePackOrder
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) ClosePackOrder(context *container.RequestContext, packOrderId string, poses []int) error {

	packOrderDAO := dal.NewPackOrderDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	order, err := packOrderDAO.SelectOne(packOrderId)
	if err != nil {
		return err
	}
	if order == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if order.Status != 26 {
		return grmi.NewBusinessError("包装单尚未激活!")
	}
	order.Status = 80
	packOrderItemlstDAO := dal.NewPackOrderItemlstDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	predicates, err := ConditionOfItemsOfPackOrder.BuildPredicates(map[string]string{
		meta.PackOrderItemlst_PackOrderId.UrlParameterName: order.PackOrderId,
	})
	if err != nil {
		return err
	}
	closedItems := make([]model.PackOrderItemlst, 0, 10)
	items, err := packOrderItemlstDAO.Select(predicates, ConditionOfPackTemplatesOfArticle.OrderByFields)
	if err != nil {
		return err
	}
	if poses == nil || len(poses) <= 0 {
		for _, item := range items {
			closedItems = append(closedItems, item)
		}
	} else {
		posMapping := make(map[int]int, len(poses))
		for _, pos := range poses {
			posMapping[pos] = pos
		}
		for _, item := range items {
			if _, ok := posMapping[item.Pos]; ok {
				closedItems = append(closedItems, item)
			}
		}
	}
	for i := 0; i < len(closedItems); i++ {
		closedItems[i].Status = 80
	}
	err = packOrderDAO.UpdateOne(order)
	if err != nil {
		return err
	}
	for i := 0; i < len(closedItems); i++ {
		err = packOrderItemlstDAO.UpdateOne(&closedItems[i])
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.OpenPackOrder
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) OpenPackOrder(context *container.RequestContext, orderId string) ([]model.PackTemplate, error) {

	/**** 校验条码 *****/
	bdal := basedal.NewLabelParserHeadDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	data, err := bdal.SelectOne("Barcode")
	if err != nil {
		return nil, err
	}

	var artId string
	if utils.ValueIsEmpty(data.Split) {
		lstdao := basedal.NewLabelParserDetailLstDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
		list, err := lstdao.Select([]grmi.Predicate{
			bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
		}, nil)
		if err != nil {
			return nil, err
		}
		data.Valst = list
		if len(orderId) < data.Length {
			return nil, grmi.NewBusinessError("序列订单错误!")
		}
		codeInfos := bmodel.ParseBarcode(orderId, data.Valst)
		artId = codeInfos["artId"]
	} else {
		artIds := strings.Split(orderId, data.Split)
		artId = artIds[0]
	}

	articleDAO := base.NewArticleDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return nil, err
	}
	if article == nil {
		return nil, grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}
	packTemplateDAO := dal.NewPackTemplateDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	predicates, err := ConditionOfItemsOfPackOrderTemplate.BuildPredicates(map[string]string{})
	if err != nil {
		return nil, err
	}
	packTemplates, err := packTemplateDAO.Select(predicates, ConditionOfPackTemplatesOfArticle.OrderByFields)
	if err != nil {
		return nil, err
	}
	if len(packTemplates) > 1 {
		return packTemplates, nil
	}
	if len(packTemplates) > 0 {
		err = self.CreatePackOrderWithTemplate(context.Session(), self.session.User(), &packTemplates[0])
		if err != nil {
			return nil, err
		}
		return packTemplates, nil
	} else {
		return nil, grmi.NewBusinessError("没找到关联的包装单模板!")
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.OpenPackOrderWithTemplate
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) OpenPackOrderWithTemplate(context *container.RequestContext, artId string, packTemplateId string) error {

	articleDAO := base.NewArticleDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return err
	}
	if article == nil {
		return grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}
	packTemplateDAO := dal.NewPackTemplateDAO(context.Session(), self.session.User().Pid, self.session.User().Userid)
	packTemplate, err := packTemplateDAO.SelectOne(packTemplateId)
	if err != nil {
		return err
	}
	if packTemplate == nil {
		return grmi.NewBusinessError("不存在指定包装单模板!")
	}
	err = self.CreatePackOrderWithTemplate(context.Session(), self.session.User(), packTemplate)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Function Name            : OpenPackOrder
 *-----------------------------------------------------------------------------
 *
 * @Description              : 根据Article标识创建包装单
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : Article标识
 *
 * @Return Value             : 包装单模板,当只有一项返回时,根据返回的模板创建包装单,不会为空,如果未找到模板直接报错.
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-18
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) CreatePackOrderWithTemplate(session *xorm.Session, user *models.Usertab, packTemplate *model.PackTemplate) error {

	packTemplateItemlstDAO := dal.NewPackTemplateItemlstDAO(session, user.Pid, user.Userid)
	predicates, err := ConditionOfItemsOfPackOrderTemplate.BuildPredicates(map[string]string{
		meta.PackTemplateItemlst_PackTemplateId.UrlParameterName: packTemplate.PackTemplateId,
	})
	if err != nil {
		return err
	}
	packTemplateItems, err := packTemplateItemlstDAO.Select(predicates, ConditionOfPackTemplatesOfArticle.OrderByFields)
	if err != nil {
		return err
	}
	packOrderId := "PACK" + time.Now().Format("20060102150405")
	packOrderDAO := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
	err = packOrderDAO.InsertOne(&model.PackOrder{
		PlantNr:        packTemplate.PlantNr,
		PackOrderId:    packOrderId,
		Status:         26,
		PackTemplateId: packTemplate.PackTemplateId,
		PackTypeId:     packTemplate.PackTypeId,
		MaterialId:     packTemplate.MaterialId,
		OpenTime:       grmi.DateTime(time.Now()),
		PlanQty:        float64(packTemplate.PlanQty),
	})
	if err != nil {
		return err
	}
	items := make([]*model.PackOrderItemlst, 0, 10)
	for _, packTemplateItem := range packTemplateItems {
		items = append(items, &model.PackOrderItemlst{
			PlantNr:     packTemplateItem.PlantNr,
			PackOrderId: packOrderId,
			Pos:         packTemplateItem.Pos,
			PosCode:     packTemplateItem.PosCode,
			MaterialId:  packTemplateItem.MaterialId,
			PlanQty:     float64(packTemplateItem.PlanQty),
			ActQty:      1,
			Status:      26,
			Seq:         packTemplateItem.Seq,
		})
	}
	packOrderItemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
	for _, item := range items {
		err = packOrderItemlstDAO.InsertOne(item)
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.IsCreatePackOrder
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) IsCreatePackOrder(user *models.Usertab, orderId string) (*model.CreatePackOrderInfo, error) {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "IsCreatePackOrder", "判断是否需要创建包装")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	/**** 校验条码 *****/
	bdal := basedal.NewLabelParserHeadDAO(session, user.Pid, user.Userid)
	data, err := bdal.SelectOne("Barcode")
	if err != nil {
		return nil, err
	}
	var artId string
	if utils.ValueIsEmpty(data.Split) {
		lstdao := basedal.NewLabelParserDetailLstDAO(session, self.session.User().Pid, self.session.User().Userid)
		list, err := lstdao.Select([]grmi.Predicate{
			bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
		}, nil)
		if err != nil {
			return nil, err
		}
		data.Valst = list
		if len(orderId) < data.Length {
			return nil, grmi.NewBusinessError("序列订单错误!")
		}
		codeInfos := bmodel.ParseBarcode(orderId, data.Valst)
		artId = codeInfos["artId"]
	} else {
		artIds := strings.Split(orderId, data.Split)
		artId = artIds[0]
	}

	articleDAO := base.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return nil, err
	}
	if article == nil {
		return nil, grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}

	//判断订单是否下线
	orderDao := omdal.NewSerialOrderStatusDAO(session, user.Pid, user.Userid)
	orderInfo, err := orderDao.SelectOne(orderId)
	if err != nil || orderInfo == nil {
		return nil, grmi.NewBusinessError("该条码不存在!")
	}
	if orderInfo.Status != bmodel.WO_STATUS_FINISHED {
		return nil, grmi.NewBusinessError("该条码订单状态没有完成!")
	}
	//判断条码是否已经生成过包装
	itemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
	dataList, err := itemlstDAO.Select([]grmi.Predicate{
		meta.PackOrderItemlst_SerialOrderId.NewPredicate(grmi.Equal, orderId),
	}, nil)
	if err != nil {
		return nil, err
	}
	if len(dataList) > 0 {
		return nil, grmi.NewBusinessError("该条码已经扫描过!")
	}

	/*********************************
	*  1.判断是否已经有激活的包装
	*********************************/

	dao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
	packOrders, err := dao.SelectActivePackOrder(artId)
	if err != nil {
		return nil, err
	}

	if len(packOrders) > 0 {
		strOrders := ""
		for _, v := range packOrders {
			strOrders += v.PackOrderId + " , "
		}
		result := new(model.CreatePackOrderInfo)
		result.InfoType = model.PackOrder_Waiting
		result.Message = "已经有开口的包装单: " + strOrders
		return result, nil
	}

	temdao := dal.NewPackTemplateDAO(session, user.Pid, user.Userid)
	packTemplants, err := temdao.SelectTemplates(artId)
	if err != nil {
		return nil, err
	}

	if len(packTemplants) == 0 {
		result := new(model.CreatePackOrderInfo)
		result.InfoType = model.PackOrder_Fail
		result.Message = "没有符合的包装模板"
		return result, nil
	}
	/*********************************
	*  2.有并且只有一个符合条件的包装模板
	*********************************/
	if len(packTemplants) == 1 {
		//开启session
		packsession := engine.NewSession()
		defer packsession.Close()
		//开启事务
		err = packsession.Begin()
		if err != nil {
			return nil, err
		}
		//生成流水号
		packTemplate := packTemplants[0]
		snr := new(models.Snrtab)
		snr.Finr = user.Pid
		packOrderId, err := snr.GetNextSnr("PackOrder")
		if err != nil {
			packsession.Rollback()
			return nil, grmi.NewBusinessError("生成包装流水号失败!")
		}
		packTemplateItemlstDAO := dal.NewPackTemplateItemlstDAO(session, user.Pid, user.Userid)

		packTemplateItems, err := packTemplateItemlstDAO.Select([]grmi.Predicate{
			meta.PackTemplateItemlst_PackTemplateId.NewPredicate(grmi.Equal, packTemplate.PackTemplateId),
		}, nil)
		if err != nil {
			packsession.Rollback()
			return nil, err
		}
		packOrderDAO := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
		err = packOrderDAO.InsertOne(&model.PackOrder{
			PlantNr:        packTemplate.PlantNr,
			PackOrderId:    packOrderId,
			Status:         bmodel.PACK_STATUS_RELEASED,
			PackTemplateId: packTemplate.PackTemplateId,
			PackTypeId:     packTemplate.PackTypeId,
			MaterialId:     packTemplate.MaterialId,
			WorkLine:       article.UsedResourceId,
			CreateDate:     utils.TimeFormat(time.Now(), "yyyyMMdd"),
			Lot:            utils.TimeFormat(time.Now(), "MMddyyyy"),
			SiteCode:       packTemplate.SiteCode,
			OpenTime:       grmi.DateTime(time.Now()),
			PlanQty:        float64(packTemplate.PlanQty),
		})
		if err != nil {
			packsession.Rollback()
			return nil, err
		}
		items := make([]*model.PackOrderItemlst, 0)
		for _, packTemplateItem := range packTemplateItems {
			items = append(items, &model.PackOrderItemlst{
				PlantNr:     packTemplateItem.PlantNr,
				PackOrderId: packOrderId,
				Pos:         packTemplateItem.Pos,
				PosCode:     packTemplateItem.PosCode,
				MaterialId:  packTemplateItem.MaterialId,
				PlanQty:     float64(packTemplateItem.PlanQty),
				ActQty:      0,
				Status:      bmodel.PACK_STATUS_RELEASED,
				Seq:         packTemplateItem.Seq,
			})
		}
		packOrderItemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
		for _, item := range items {
			err = packOrderItemlstDAO.InsertOne(item)
			if err != nil {
				packsession.Rollback()
				return nil, err
			}
		}
		//查询该零件对应的包装项位置
		dao := dal.NewPackOrderItemlstDAO(packsession, user.Pid, user.Userid)
		infoPos, err := dao.SelectOnePos(packOrderId, artId)
		if err != nil {
			return nil, err
		}
		if infoPos == nil {
			return nil, grmi.NewBusinessError("没有待扫描的条码!")
		}
		//校验位置对应的零件是否一致
		if infoPos.MaterialId != artId {
			return nil, grmi.NewBusinessError("编码位置对应的零件号和条码不一致!")
		}
		//1.更新对应的包装项信息
		PackOrderItemlst := new(model.PackOrderItemlst)
		PackOrderItemlst.PlantNr = user.Pid
		PackOrderItemlst.PackOrderId = packOrderId
		PackOrderItemlst.Pos = infoPos.Pos
		PackOrderItemlst.SerialOrderId = orderId
		PackOrderItemlst.ActQty = 1
		PackOrderItemlst.Status = bmodel.PACK_STATUS_RUNNING

		columns := []string{"SerialOrderId", "Status", "ActQty"}
		err = dao.UpdateWhere([]grmi.Predicate{
			meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
			meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
			meta.PackOrderItemlst_Status.NewPredicate(grmi.Equal, bmodel.PACK_STATUS_RELEASED),
			meta.PackOrderItemlst_Pos.NewPredicate(grmi.Equal, 1),
		}, PackOrderItemlst, columns...)

		if err != nil {
			packsession.Rollback()
			return nil, grmi.NewBusinessError("更新包装项失败!")
		}
		//2.判断是否满足关包
		dataInfo, err := dao.Select([]grmi.Predicate{
			meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
			meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
			meta.PackOrderItemlst_Status.NewPredicate(grmi.LessThen, bmodel.PACK_STATUS_RUNNING),
		}, nil)
		if err != nil {
			packsession.Rollback()
			return nil, grmi.NewBusinessError("更新包装项失败!")
		}
		if len(dataInfo) == 0 {
			//满足关包
			pdao := dal.NewPackOrderDAO(packsession, user.Pid, user.Userid)

			pack, err := pdao.SelectOne(packOrderId)
			if err != nil {
				packsession.Rollback()
				return nil, err
			}
			if pack == nil {
				packsession.Rollback()
				return nil, grmi.NewBusinessError("不存在指定记录!")
			}
			pack.PlantNr = user.Pid
			pack.PackOrderId = packOrderId
			pack.Status = bmodel.PACK_STATUS_CLOSED
			pack.CloseTime = grmi.DateTime(time.Now())
			pack.ActQty = pack.PlanQty
			err = pdao.UpdateOne(pack)
			if err != nil {
				packsession.Rollback()
				return nil, grmi.NewBusinessError("更新包装单状态失败!")
			}

			Itemlst := new(model.PackOrderItemlst)
			Itemlst.PlantNr = user.Pid
			Itemlst.PackOrderId = packOrderId
			Itemlst.Status = bmodel.PACK_STATUS_CLOSED

			columns := []string{"Status"}
			err = dao.UpdateWhere([]grmi.Predicate{
				meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
				meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
			}, Itemlst, columns...)
			if err != nil {
				packsession.Rollback()
				return nil, grmi.NewBusinessError("更新包装项状态失败!")
			}
		}
		packsession.Commit()
		result := new(model.CreatePackOrderInfo)
		result.InfoType = model.PackOrder_Success
		result.Message = "成功创建包装单!"
		return result, nil
	}
	/*********************************
	*  3.有并且有多个符合条件的包装模板集合
	*********************************/
	result := new(model.CreatePackOrderInfo)
	result.InfoType = model.PackOrder_Doing
	result.Message = "需要手动创建包装单!"
	result.Items = packTemplants
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/PackOrderService.SelectTemplates
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) SelectTemplates(user *models.Usertab, orderId string) (*model.CreatePackOrderInfo, error) {

	grmi.Log(user, "/services/log/implments/PackOrder.service.impl.go", "SelectTemplates", "查询可用模板")

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

	/**** 校验条码 *****/
	bdal := basedal.NewLabelParserHeadDAO(session, user.Pid, user.Userid)
	data, err := bdal.SelectOne("Barcode")
	if err != nil {
		return nil, err
	}
	var artId string
	if utils.ValueIsEmpty(data.Split) {
		lstdao := basedal.NewLabelParserDetailLstDAO(session, self.session.User().Pid, self.session.User().Userid)
		list, err := lstdao.Select([]grmi.Predicate{
			bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
		}, nil)
		if err != nil {
			return nil, err
		}
		data.Valst = list
		if len(orderId) < data.Length {
			return nil, grmi.NewBusinessError("序列订单错误!")
		}
		codeInfos := bmodel.ParseBarcode(orderId, data.Valst)
		artId = codeInfos["artId"]
	} else {
		artIds := strings.Split(orderId, data.Split)
		artId = artIds[0]
	}

	articleDAO := base.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return nil, err
	}
	if article == nil {
		return nil, grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}

	temdao := dal.NewPackTemplateDAO(session, user.Pid, user.Userid)
	packTemplants, err := temdao.SelectTemplates(artId)
	if err != nil {
		return nil, grmi.NewBusinessError("没找到关联的包装单模板!")
	}
	//判断订单是否下线
	orderDao := omdal.NewSerialOrderStatusDAO(session, user.Pid, user.Userid)
	orderInfo, err := orderDao.SelectOne(orderId)
	if err != nil || orderInfo == nil {
		return nil, grmi.NewBusinessError("该条码不存在!")
	}
	if orderInfo.Status != bmodel.WO_STATUS_FINISHED {
		return nil, grmi.NewBusinessError("该条码订单状态没有完成!")
	}
	//如果只有一个模板那么自动创建
	if len(packTemplants) == 1 {
		//开启session
		packsession := engine.NewSession()
		defer packsession.Close()
		//开启事务
		err = packsession.Begin()
		if err != nil {
			return nil, err
		}
		//生成流水号
		packTemplate := packTemplants[0]
		snr := new(models.Snrtab)
		snr.Finr = user.Pid
		packOrderId, err := snr.GetNextSnr("PackOrder")
		if err != nil {
			packsession.Rollback()
			return nil, grmi.NewBusinessError("生成包装流水号失败!")
		}
		packTemplateItemlstDAO := dal.NewPackTemplateItemlstDAO(session, user.Pid, user.Userid)

		packTemplateItems, err := packTemplateItemlstDAO.Select([]grmi.Predicate{
			meta.PackTemplateItemlst_PackTemplateId.NewPredicate(grmi.Equal, packTemplate.PackTemplateId),
		}, nil)
		if err != nil {
			packsession.Rollback()
			return nil, err
		}
		packOrderDAO := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
		err = packOrderDAO.InsertOne(&model.PackOrder{
			PlantNr:        packTemplate.PlantNr,
			PackOrderId:    packOrderId,
			Status:         bmodel.PACK_STATUS_RELEASED,
			PackTemplateId: packTemplate.PackTemplateId,
			PackTypeId:     packTemplate.PackTypeId,
			MaterialId:     packTemplate.MaterialId,
			WorkLine:       article.UsedResourceId,
			CreateDate:     utils.TimeFormat(time.Now(), "yyyyMMdd"),
			Lot:            utils.TimeFormat(time.Now(), "MMddyyyy"),
			SiteCode:       packTemplate.SiteCode,
			OpenTime:       grmi.DateTime(time.Now()),
			PlanQty:        float64(packTemplate.PlanQty),
		})
		if err != nil {
			packsession.Rollback()
			return nil, err
		}
		items := make([]*model.PackOrderItemlst, 0)
		for _, packTemplateItem := range packTemplateItems {
			items = append(items, &model.PackOrderItemlst{
				PlantNr:     packTemplateItem.PlantNr,
				PackOrderId: packOrderId,
				Pos:         packTemplateItem.Pos,
				PosCode:     packTemplateItem.PosCode,
				MaterialId:  packTemplateItem.MaterialId,
				PlanQty:     float64(packTemplateItem.PlanQty),
				ActQty:      0,
				Status:      bmodel.PACK_STATUS_RELEASED,
				Seq:         packTemplateItem.Seq,
			})
		}
		packOrderItemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
		for _, item := range items {
			err = packOrderItemlstDAO.InsertOne(item)
			if err != nil {
				packsession.Rollback()
				return nil, err
			}
		}
		packsession.Commit()
		result := new(model.CreatePackOrderInfo)
		result.InfoType = model.PackOrder_Success
		result.Message = "成功创建包装单!"
		result.Items = packTemplants
		return result, nil
	}
	result := new(model.CreatePackOrderInfo)
	result.InfoType = model.PackOrder_Doing
	result.Message = "手动创建包装单!"
	result.Items = packTemplants
	return result, nil
}

/******************************************************************************
 *
 * @Function Name            : CreatePackOrderByTemplate
 *-----------------------------------------------------------------------------
 *
 * @Description              : 根据Article标识创建包装单
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : Article标识
 *
 * @Return Value             : 包装单模板,当只有一项返回时,根据返回的模板创建包装单,不会为空,如果未找到模板直接报错.
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : 娄文智
 *
 * @Date                     : 2021-06-03
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) CreatePackOrderByTemplate(user *models.Usertab, packTemplate *model.PackTemplate) error {

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

	packTemplateItemlstDAO := dal.NewPackTemplateItemlstDAO(session, user.Pid, user.Userid)
	predicates, err := ConditionOfItemsOfPackOrderTemplate.BuildPredicates(map[string]string{
		meta.PackTemplateItemlst_PackTemplateId.UrlParameterName: packTemplate.PackTemplateId,
	})
	if err != nil {
		return err
	}
	packTemplateItems, err := packTemplateItemlstDAO.Select(predicates, ConditionOfPackTemplatesOfArticle.OrderByFields)
	if err != nil {
		return err
	}

	articleDAO := base.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := articleDAO.SelectOne(packTemplate.MaterialId)
	if err != nil {
		return err
	}
	if article == nil {
		return grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}

	//查询项目定义
	//medal.NewProjectDAO(session, user.Pid, user.Userid)
	//生成流水号
	snr := new(models.Snrtab)
	snr.Finr = user.Pid
	packOrderId, err := snr.GetNextSnr("PackOrder")
	if err != nil {
		return grmi.NewBusinessError("生成包装流水号失败!")
	}
	packOrderDAO := dal.NewPackOrderDAO(session, user.Pid, user.Userid)
	err = packOrderDAO.InsertOne(&model.PackOrder{
		PlantNr:        packTemplate.PlantNr,
		PackOrderId:    packOrderId,
		Status:         bmodel.PACK_STATUS_RELEASED,
		PackTemplateId: packTemplate.PackTemplateId,
		PackTypeId:     packTemplate.PackTypeId,
		MaterialId:     packTemplate.MaterialId,
		WorkLine:       article.UsedResourceId,
		CreateDate:     utils.TimeFormat(time.Now(), "yyyyMMdd"),
		Lot:            utils.TimeFormat(time.Now(), "MMddyyyy"),
		SiteCode:       packTemplate.SiteCode,
		OpenTime:       grmi.DateTime(time.Now()),
		PlanQty:        float64(packTemplate.PlanQty),
	})
	if err != nil {
		return err
	}
	items := make([]*model.PackOrderItemlst, 0, 10)
	for _, packTemplateItem := range packTemplateItems {
		items = append(items, &model.PackOrderItemlst{
			PlantNr:     packTemplateItem.PlantNr,
			PackOrderId: packOrderId,
			Pos:         packTemplateItem.Pos,
			PosCode:     packTemplateItem.PosCode,
			MaterialId:  packTemplateItem.MaterialId,
			PlanQty:     float64(packTemplateItem.PlanQty),
			ActQty:      0,
			Status:      bmodel.PACK_STATUS_RELEASED,
			Seq:         packTemplateItem.Seq,
		})
	}
	packOrderItemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
	for _, item := range items {
		err = packOrderItemlstDAO.InsertOne(item)
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Function Name            : CheckPackOrderItem
 *-----------------------------------------------------------------------------
 *
 * @Description              : 根据Article标识创建包装单
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : Article标识
 *
 * @Return Value             : 包装单模板,当只有一项返回时,根据返回的模板创建包装单,不会为空,如果未找到模板直接报错.
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : 娄文智
 *
 * @Date                     : 2021-06-03
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) CheckPackOrderItem(user *models.Usertab, packOrderId string, orderId string) (string, error) {

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	/**** 校验条码 *****/
	bdal := basedal.NewLabelParserHeadDAO(session, user.Pid, user.Userid)
	data, err := bdal.SelectOne("Barcode")
	if err != nil {
		return "", err
	}
	lstdao := basedal.NewLabelParserDetailLstDAO(session, user.Pid, user.Userid)
	list, err := lstdao.Select([]grmi.Predicate{
		bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
	}, nil)
	if err != nil {
		return "", err
	}
	data.Valst = list
	if len(orderId) < data.Length {
		return "", grmi.NewBusinessError("序列订单错误!")
	}
	codeInfos := bmodel.ParseBarcode(orderId, data.Valst)
	artId := codeInfos["artId"]

	//判断订单是否下线
	orderDao := omdal.NewSerialOrderStatusDAO(session, user.Pid, user.Userid)
	orderInfo, err := orderDao.SelectOne(orderId)
	if err != nil || orderInfo == nil {
		return "", grmi.NewBusinessError("该条码不存在!")
	}
	if orderInfo.Status != bmodel.WO_STATUS_FINISHED {
		return "", grmi.NewBusinessError("该条码订单状态没有完成!")
	}

	articleDAO := base.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return "", err
	}
	if article == nil {
		return "", grmi.NewBusinessError("没有在数据库中找到扫码内容对应的信息!")
	}
	itemlstDAO := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
	//判断条码是否符合包装规则
	dataLens, err := itemlstDAO.Select([]grmi.Predicate{
		meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_MaterialId.NewPredicate(grmi.Equal, artId),
	}, nil)
	if err != nil {
		return "", err
	}
	if len(dataLens) == 0 {
		return "", grmi.NewBusinessError("该条码不符合该包装规则!")
	}

	//判断条码是否已经生成过包装
	dataList, err := itemlstDAO.Select([]grmi.Predicate{
		meta.PackOrderItemlst_SerialOrderId.NewPredicate(grmi.Equal, orderId),
	}, nil)
	if err != nil {
		return "", err
	}
	if len(dataList) > 0 {
		return "", grmi.NewBusinessError("该条码已经扫描过!")
	}
	packsession := engine.NewSession()
	defer packsession.Close()
	//开启事务
	err = packsession.Begin()
	if err != nil {
		return "", err
	}
	//查询待检测包装位置
	dao := dal.NewPackOrderItemlstDAO(packsession, user.Pid, user.Userid)
	infoPos, err := dao.SelectOnePos(packOrderId, artId)
	if err != nil {
		return "", err
	}
	if infoPos == nil {
		return "", grmi.NewBusinessError("没有待扫描的条码!")
	}
	//校验位置对应的零件是否一致
	if infoPos.MaterialId != artId {
		return "", grmi.NewBusinessError("编码位置对应的零件号和条码不一致!")
	}
	//1.更新对应的包装项信息

	PackOrderItemlst := new(model.PackOrderItemlst)
	PackOrderItemlst.PlantNr = user.Pid
	PackOrderItemlst.PackOrderId = packOrderId
	PackOrderItemlst.Pos = infoPos.Pos
	PackOrderItemlst.SerialOrderId = orderId
	PackOrderItemlst.ActQty = 1
	PackOrderItemlst.Status = bmodel.PACK_STATUS_RUNNING

	columns := []string{"SerialOrderId", "Status", "ActQty"}
	err = dao.UpdateWhere([]grmi.Predicate{
		meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_Status.NewPredicate(grmi.Equal, bmodel.PACK_STATUS_RELEASED),
		meta.PackOrderItemlst_Pos.NewPredicate(grmi.Equal, infoPos.Pos),
	}, PackOrderItemlst, columns...)

	if err != nil {
		packsession.Rollback()
		return "", grmi.NewBusinessError("更新包装项失败!")
	}
	//2.判断是否满足关包
	dataInfo, err := dao.Select([]grmi.Predicate{
		meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_Status.NewPredicate(grmi.LessThen, bmodel.PACK_STATUS_RUNNING),
	}, nil)
	if err != nil {
		packsession.Rollback()
		return "", grmi.NewBusinessError("更新包装项失败!")
	}
	isClose := false
	if len(dataInfo) == 0 {
		isClose = true
		//满足关包
		pdao := dal.NewPackOrderDAO(packsession, user.Pid, user.Userid)

		pack, err := pdao.SelectOne(packOrderId)
		if err != nil {
			packsession.Rollback()
			return "", err
		}
		if pack == nil {
			packsession.Rollback()
			return "", grmi.NewBusinessError("不存在指定记录!")
		}
		pack.PlantNr = user.Pid
		pack.PackOrderId = packOrderId
		pack.Status = bmodel.PACK_STATUS_CLOSED
		pack.CloseTime = grmi.DateTime(time.Now())
		pack.ActQty = pack.PlanQty
		err = pdao.UpdateOne(pack)
		if err != nil {
			packsession.Rollback()
			return "", grmi.NewBusinessError("更新包装单状态失败!")
		}

		Itemlst := new(model.PackOrderItemlst)
		Itemlst.PlantNr = user.Pid
		Itemlst.PackOrderId = packOrderId
		Itemlst.Status = bmodel.PACK_STATUS_CLOSED

		columns := []string{"Status"}
		err = dao.UpdateWhere([]grmi.Predicate{
			meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
			meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		}, Itemlst, columns...)
		if err != nil {
			packsession.Rollback()
			return "", grmi.NewBusinessError("更新包装项状态失败!")
		}
	}
	packsession.Commit()
	if isClose {
		return "close", nil
	}
	return "", nil
}

/******************************************************************************
 *
 * @Function Name            : ClosePackOrderItem
 *-----------------------------------------------------------------------------
 *
 * @Description              : 关闭包装
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : Article标识
 *
 * @Return Value             : 包装单模板,当只有一项返回时,根据返回的模板创建包装单,不会为空,如果未找到模板直接报错.
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : 娄文智
 *
 * @Date                     : 2021-06-03
 *
 ******************************************************************************/
func (self *PackOrderServiceImplement) ClosePackOrderItem(user *models.Usertab, packOrderId string) error {

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

	//开启事务
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewPackOrderItemlstDAO(session, user.Pid, user.Userid)
	//查询已经关闭的单数
	items, err := dao.Select([]grmi.Predicate{
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_Status.NewPredicate(grmi.Equal, bmodel.PACK_STATUS_RUNNING),
	}, nil)
	if err != nil {
		return err
	}
	//1.更新包装单
	pdao := dal.NewPackOrderDAO(session, user.Pid, user.Userid)

	pack, err := pdao.SelectOne(packOrderId)
	if err != nil {
		session.Rollback()
		return err
	}
	if pack == nil {
		session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	pack.PlantNr = user.Pid
	pack.PackOrderId = packOrderId
	pack.Status = bmodel.PACK_STATUS_CLOSED
	pack.CloseTime = grmi.DateTime(time.Now())
	pack.ActQty = float64(len(items))
	err = pdao.UpdateOne(pack)
	if err != nil {
		session.Rollback()
		return grmi.NewBusinessError("更新包装单状态失败!")
	}

	//2.更新对应的包装项信息
	PackOrderItemlstOne := new(model.PackOrderItemlst)
	PackOrderItemlstOne.PlantNr = user.Pid
	PackOrderItemlstOne.PackOrderId = packOrderId
	PackOrderItemlstOne.Status = bmodel.PACK_STATUS_CLOSED
	// 1) 更新处理中（40）的状态  ==>  (80)
	columns := []string{"Status"}
	err = dao.UpdateWhere([]grmi.Predicate{
		meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_Status.NewPredicate(grmi.Equal, bmodel.PACK_STATUS_RUNNING),
	}, PackOrderItemlstOne, columns...)

	if err != nil {
		session.Rollback()
		return grmi.NewBusinessError("更新包装项失败!")
	}
	//2） 更新等待（26）的状态  ==>   (98)
	PackOrderItemlstTwo := new(model.PackOrderItemlst)
	PackOrderItemlstTwo.PlantNr = user.Pid
	PackOrderItemlstTwo.PackOrderId = packOrderId
	PackOrderItemlstTwo.Status = bmodel.PACK_STATUS_CANCELED
	// 1) 更新处理中（40）的状态  ==>  (80)
	err = dao.UpdateWhere([]grmi.Predicate{
		meta.PackOrderItemlst_PlantNr.NewPredicate(grmi.Equal, user.Pid),
		meta.PackOrderItemlst_PackOrderId.NewPredicate(grmi.Equal, packOrderId),
		meta.PackOrderItemlst_Status.NewPredicate(grmi.Equal, bmodel.PACK_STATUS_RELEASED),
	}, PackOrderItemlstTwo, columns...)

	if err != nil {
		session.Rollback()
		return grmi.NewBusinessError("更新包装项失败!")
	}
	session.Commit()
	return nil
}
