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

package implments

import (
	baseDal "LAPP_ACURA_MOM_BACKEND/dao/base"
	dal "LAPP_ACURA_MOM_BACKEND/dao/me"
	"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/me"
	baseModel "LAPP_ACURA_MOM_BACKEND/models/base"
	model "LAPP_ACURA_MOM_BACKEND/models/me"
)

/******************************************************************************
 *
 * @Description              : Product的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 15:22:21
 *
 ******************************************************************************/
var DefaultConditionOfProduct = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Product_ProductId.UrlParameterName:             grmi.NewConditionItem(meta.Product_ProductId, grmi.Equal, true),
		meta.Product_ProjectId.UrlParameterName:             grmi.NewConditionItem(meta.Product_ProjectId, grmi.Equal, true),
		meta.Product_Descr.UrlParameterName:                 grmi.NewConditionItem(meta.Product_Descr, grmi.Equal, false),
		meta.Product_Descr1.UrlParameterName:                grmi.NewConditionItem(meta.Product_Descr1, grmi.Equal, false),
		meta.Product_Descr2.UrlParameterName:                grmi.NewConditionItem(meta.Product_Descr2, grmi.Equal, false),
		meta.Product_PartId.UrlParameterName:                grmi.NewConditionItem(meta.Product_PartId, grmi.Equal, false),
		meta.Product_DefaultWorkLineId.UrlParameterName:     grmi.NewConditionItem(meta.Product_DefaultWorkLineId, grmi.Equal, false),
		meta.Product_MultiWorkLineToggle.UrlParameterName:   grmi.NewConditionItem(meta.Product_MultiWorkLineToggle, grmi.Equal, false),
		meta.Product_CustPartId.UrlParameterName:            grmi.NewConditionItem(meta.Product_CustPartId, grmi.Equal, false),
		meta.Product_IntPartId.UrlParameterName:             grmi.NewConditionItem(meta.Product_IntPartId, grmi.Equal, false),
		meta.Product_PlanType.UrlParameterName:              grmi.NewConditionItem(meta.Product_PlanType, grmi.Equal, false),
		meta.Product_PlanMode.UrlParameterName:              grmi.NewConditionItem(meta.Product_PlanMode, grmi.Equal, false),
		meta.Product_ProductType.UrlParameterName:           grmi.NewConditionItem(meta.Product_ProductType, grmi.Equal, false),
		meta.Product_ProductType1.UrlParameterName:          grmi.NewConditionItem(meta.Product_ProductType1, grmi.Equal, false),
		meta.Product_ProductType2.UrlParameterName:          grmi.NewConditionItem(meta.Product_ProductType2, grmi.Equal, false),
		meta.Product_ProductSpec.UrlParameterName:           grmi.NewConditionItem(meta.Product_ProductSpec, grmi.Equal, false),
		meta.Product_ProductSpec1.UrlParameterName:          grmi.NewConditionItem(meta.Product_ProductSpec1, grmi.Equal, false),
		meta.Product_ProductSpec2.UrlParameterName:          grmi.NewConditionItem(meta.Product_ProductSpec2, grmi.Equal, false),
		meta.Product_AllowPackToggle.UrlParameterName:       grmi.NewConditionItem(meta.Product_AllowPackToggle, grmi.Equal, false),
		meta.Product_CreateWorkOrderToggle.UrlParameterName: grmi.NewConditionItem(meta.Product_CreateWorkOrderToggle, grmi.Equal, false),
		meta.Product_CreatePackOrderToggle.UrlParameterName: grmi.NewConditionItem(meta.Product_CreatePackOrderToggle, grmi.Equal, false),
		meta.Product_PackSize.UrlParameterName:              grmi.NewConditionItem(meta.Product_PackSize, grmi.Equal, false),
		meta.PackOrderItemSize.UrlParameterName:             grmi.NewConditionItem(meta.PackOrderItemSize, grmi.Equal, false),
		meta.Product_Jph.UrlParameterName:                   grmi.NewConditionItem(meta.Product_Jph, grmi.Equal, false),
		meta.Product_PlanPriority.UrlParameterName:          grmi.NewConditionItem(meta.Product_PlanPriority, grmi.Equal, false),
		meta.Product_BatchSize.UrlParameterName:             grmi.NewConditionItem(meta.Product_BatchSize, grmi.Equal, false),
		meta.Product_LeadTimeInSecond.UrlParameterName:      grmi.NewConditionItem(meta.Product_LeadTimeInSecond, grmi.Equal, false),
		meta.Product_PickingFlag.UrlParameterName:           grmi.NewConditionItem(meta.Product_PickingFlag, grmi.Equal, false),
		meta.Product_MachineCode.UrlParameterName:           grmi.NewConditionItem(meta.Product_MachineCode, grmi.Equal, false),
		meta.Product_ColorValue.UrlParameterName:            grmi.NewConditionItem(meta.Product_ColorValue, grmi.Equal, false),
		meta.Product_PrintTemplateId.UrlParameterName:       grmi.NewConditionItem(meta.Product_PrintTemplateId, grmi.Equal, false),
		meta.Product_CtrlPara1.UrlParameterName:             grmi.NewConditionItem(meta.Product_CtrlPara1, grmi.Equal, false),
		meta.Product_CtrlPara2.UrlParameterName:             grmi.NewConditionItem(meta.Product_CtrlPara2, grmi.Equal, false),
		meta.Product_CtrlStr1.UrlParameterName:              grmi.NewConditionItem(meta.Product_CtrlStr1, grmi.Equal, false),
		meta.Product_CtrlStr2.UrlParameterName:              grmi.NewConditionItem(meta.Product_CtrlStr2, grmi.Equal, false),
		meta.Product_CtrlTime1.UrlParameterName:             grmi.NewConditionItem(meta.Product_CtrlTime1, grmi.Approximate, false),
		meta.Product_CtrlTime2.UrlParameterName:             grmi.NewConditionItem(meta.Product_CtrlTime2, grmi.Approximate, false),
		meta.Product_LastModify.UrlParameterName:            grmi.NewConditionItem(meta.Product_LastModify, grmi.Approximate, false),
		meta.Product_LastUser.UrlParameterName:              grmi.NewConditionItem(meta.Product_LastUser, grmi.Equal, false),
		meta.Product_CreateTime.UrlParameterName:            grmi.NewConditionItem(meta.Product_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Product的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 15:22:21
 *
 ******************************************************************************/
var DefaultConditionOfProductAndPaging = grmi.NewCondition(
	DefaultConditionOfProduct.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ProductServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Product的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 15:22:21
 *
 ******************************************************************************/
type ProductServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewProductDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ProductDAOImplement实例
 *
 * @Return Value             : ProductDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 15:22:21
 *
 ******************************************************************************/
func NewProductServiceImplement() *ProductServiceImplement {
	return &ProductServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.InsertOne
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) InsertOne(user *global.User, entity *model.Product) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "InsertOneProduct", "插入一个Product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	//绑定配置
	relateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)

	record, err := dao.SelectOne(entity.ProductId, entity.ProjectId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	if !(entity.Count > 0) {
		return grmi.NewBusinessError("请填写数量!")
	}
	//查询配置
	relateL, err := relateDao.SelectOne(entity.ProductFamilyId, entity.ProjectId, entity.ProductId)
	if err != nil {
		return err
	}
	if relateL != nil {
		return grmi.NewBusinessError("配置已存在")
	}
	maxPos, err := relateDao.GetMaxPos(entity.ProductFamilyId)
	if err != nil {
		return grmi.NewBusinessError("查询派生和总成关联数据失败, error:" + err.Error())
	}
	if err = session.Begin(); err != nil {
		return err
	}

	//添加配置
	relateData := model.ProductFamilyRelate{
		ProductFamilyId: entity.ProductFamilyId,
		ProductDescr:    entity.Descr,
		ProjectId:       entity.ProjectId,
		ProductId:       entity.ProductId,
		Count:           entity.Count,
		Pos:             maxPos + 1,
	}
	err = relateDao.InsertOne(&relateData)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.Cancel
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) Cancel(user *global.User, productId string, projectId string, productFamilyId string) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "DeleteOneProduct", "删除一个Product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	//dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	//record, err := dao.SelectOne(productId, projectId)
	//if err != nil {
	//	return err
	//}
	//if record == nil {
	//	return grmi.NewBusinessError("不存在指定记录!")
	//}
	//判断是否有关联配置
	//relate := model.ProductFamily{}
	//_lodLen := 0
	//for _, v := range record.Project {
	//	for _, val := range v.ProductFamily {
	//		if val.ProductFamilyId == productFamilyId {
	//			_lodLen += 1
	//			relate = val
	//			break
	//		}
	//	}
	//}
	//if _lodLen == 0 {
	//	return grmi.NewBusinessError("该产品未关联此配置!")
	//}
	relateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
	relate, err := relateDao.SelectOne(productFamilyId, projectId, productId)
	if err != nil {
		return grmi.NewBusinessError("查询关联关系失败, error:" + err.Error())
	}
	if relate == nil {
		return grmi.NewBusinessError("不存在该关联关系")
	}
	err = relateDao.DeleteOne(productFamilyId, projectId, productId)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.DeleteOne
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) DeleteOne(user *global.User, productId string, projectId string, productFamilyId string) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "DeleteOneProduct", "删除一个Product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(productId, projectId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	//判断是否有关联配置
	//_lodLen := 0
	//relate := model.ProductFamily{}
	//for _, v := range record.Project {
	//	for _, val := range v.ProductFamily {
	//		if val.ProductFamilyId != productFamilyId {
	//			_lodLen += 1
	//		}
	//		if val.ProductFamilyId == productFamilyId {
	//			relate = val
	//		}
	//	}
	//}
	//if _lodLen > 0 {
	//	return grmi.NewBusinessError("请解除配置关联后删除!")
	//}
	if err = session.Begin(); err != nil {
		return err
	}
	err = dao.DeleteOne(productId, projectId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除产品数据失败, error:" + err.Error())
	}
	relateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
	err = relateDao.DeleteOne(productFamilyId, projectId, productId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除关联关系失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.SelectOne
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) SelectOne(user *global.User, productId string, projectId string) (*model.Product, error) {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "SelectOneProduct", "查询一个Product")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.UpdateOne
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) UpdateOne(user *global.User, entity *model.Product) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "UpdateOneProduct", "修改一个Product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ProductId, entity.ProjectId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	//如过count大于0修改对应配置数量
	if entity.Count > 0 {
		rateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
		//修改数量
		rate := model.ProductFamilyRelate{
			Count:           entity.Count,
			ProjectId:       entity.ProjectId,
			ProductFamilyId: entity.ProductFamilyId,
			ProductId:       entity.ProductId,
		}
		rateDao.UpdateOne(&rate)
	}
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.Insert
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) Insert(user *global.User, entities *[]model.Product) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "InsertProduct", "插入多个Product")

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.Delete
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) Delete(user *global.User, entities *[]model.Product) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "DeleteProduct", "删除多个Product")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ProductId, entity.ProjectId)
		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/me/ProductService.Select
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.Product, error) {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "SelectProduct", "查询Product")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.SelectAndPaging
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) SelectAndPaging(user *global.User, urlParameters map[string]string) (grmi.PagingResult, error) {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "SelectProduct", "查询Product")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductService.Update
 *
 ******************************************************************************/
func (impl *ProductServiceImplement) Update(user *global.User, entities *[]model.Product) error {

	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "UpdateProduct", "修改多个Product")

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

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

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

// SelectByWorkLine 通过产线查询产品列表
func (impl *ProductServiceImplement) SelectByWorkLine(user *global.User, workLineId string) ([]model.Product, error) {
	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "SelectByWorkLine", "通过产线查询product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	productLi, err := dao.Select([]grmi.Predicate{meta.Product_DefaultWorkLineId.NewPredicate(grmi.Equal, workLineId), meta.Product_MultiWorkLineToggle.NewPredicate(grmi.Equal, false)}, []grmi.Field{meta.Product_ProductId})
	if err != nil {
		return nil, grmi.NewBusinessError("查询失败, error:" + err.Error())
	}
	productWorkLineDao := dal.NewProductWorkLineLstDAO(session, user.PlantNr, user.UserId)
	relateProductLi, err := productWorkLineDao.SelectByRelate(workLineId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询关联多产线的产品数据失败, error:" + err.Error())
	}
	productLi = append(productLi, relateProductLi...)
	return productLi, nil
}

// Copy 总成产品数据 修改项目ID
func (impl *ProductServiceImplement) Copy(user *global.User, productId, projectId string, targetProjectId string) error {
	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "Copy", "复制")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	productDao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	articleDao := baseDal.NewArticleDAO(session, user.PlantNr, user.UserId)
	articleAtcodLstDao := baseDal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	artQtyAllocateDao := baseDal.NewArtQtyAllocateDAO(session, user.PlantNr, user.UserId)
	artCheckRuleDao := baseDal.NewArtCheckRuleDAO(session, user.PlantNr, user.UserId)
	projectDao := dal.NewProjectDAO(session, user.PlantNr, user.UserId)
	product, err := productDao.SelectOne(productId, projectId)
	if err != nil {
		return grmi.NewBusinessError("查询总成产品数据失败, error:" + err.Error())
	}
	if product == nil {
		return grmi.NewBusinessError("来源总成数据不存在")
	}
	targetProduct, err := productDao.SelectOne(productId, targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询总成产品数据失败, error:" + err.Error())
	}
	if targetProduct != nil {
		return grmi.NewBusinessError("要复制的总成产品已存在")
	}
	project, err := projectDao.SelectOne(targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询车型项目数据失败, error:" + err.Error())
	}
	if project == nil {
		return grmi.NewBusinessError("车型项目ID不存在")
	}
	article, err := articleDao.SelectOne(productId, projectId)
	if err != nil {
		return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
	}
	if article == nil {
		return grmi.NewBusinessError("不存在该物料, 物料ID:" + productId + ", 项目ID:" + projectId)
	}
	targetArticle, err := articleDao.SelectOne(productId, targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
	}
	if targetArticle != nil {
		return grmi.NewBusinessError("已存在需要复制的物料")
	}
	attributeAllocateLi, err := articleAtcodLstDao.Select([]grmi.Predicate{baseMeta.ArticleAtcodLst_ArtId.NewPredicate(grmi.Equal, productId),
		baseMeta.ArticleAtcodLst_ProjectId.NewPredicate(grmi.Equal, projectId)},
		nil)
	if err != nil {
		return grmi.NewBusinessError("查询物料关联属性失败, error:" + err.Error())
	}
	var checkRuleLi []baseModel.ArtCheckRule
	var qtyAllocateLi []baseModel.ArtQtyAllocate
	if len(attributeAllocateLi) != 0 {
		attrCodeMap := make(map[int]interface{})
		attrCodeLi := make([]int, 0)
		for _, articleAtcod := range attributeAllocateLi {
			_, exist := attrCodeMap[articleAtcod.AttrCode]
			if !exist {
				attrCodeLi = append(attrCodeLi, articleAtcod.AttrCode)
				attrCodeMap[articleAtcod.AttrCode] = nil
			}
		}
		checkRuleLi, err = artCheckRuleDao.SelectByArtId(productId, projectId, attrCodeLi)
		if err != nil {
			return grmi.NewBusinessError("查询物料校验规则失败, error:" + err.Error())
		}
		qtyAllocateLi, err = artQtyAllocateDao.SelectByArtId(productId, projectId, attrCodeLi)
		if err != nil {
			return grmi.NewBusinessError("查询物料特殊工位分配规则失败, error:" + err.Error())
		}
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	targetProduct = product
	targetProduct.ProjectId = targetProjectId
	err = productDao.InsertOne(targetProduct)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("插入总成数据失败, error:" + err.Error())
	}
	targetArticle = article
	targetArticle.ProjectId = targetProjectId
	err = articleDao.InsertOne(targetArticle)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("写入物料数据失败, error:" + err.Error())
	}
	if len(attributeAllocateLi) != 0 {
		for _, attribute := range attributeAllocateLi {
			attribute.ProjectId = targetProjectId
			err = articleAtcodLstDao.InsertOne(&attribute)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入物料属性数据失败, error:" + err.Error())
			}
		}
	}
	if checkRuleLi != nil && len(checkRuleLi) != 0 {
		for _, checkRule := range checkRuleLi {
			checkRule.ProjectId = targetProjectId
			err = artCheckRuleDao.InsertOne(&checkRule)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入零件校验规则失败, error:" + err.Error())
			}
		}
	}
	if qtyAllocateLi != nil && len(qtyAllocateLi) != 0 {
		for _, qtyAllocate := range qtyAllocateLi {
			qtyAllocate.ProjectId = targetProjectId
			err = artQtyAllocateDao.InsertOne(&qtyAllocate)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入零件分配规则失败, error:" + err.Error())
			}
		}
	}
	_ = session.Commit()
	return nil
}

// SelectWorkLineByProduct 通过总成查询可生产产线
func (impl *ProductServiceImplement) SelectWorkLineByProduct(user *global.User, productId, projectId string) ([]baseModel.WorkLine, error) {
	grmi.Log(user, "/services/me/implments/Product.service.impl.go", "SelectByWorkLine", "通过产线查询product")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductDAO(session, user.PlantNr, user.UserId)
	product, err := dao.SelectOne(productId, projectId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询总成失败， 错误:" + err.Error())
	}
	if product == nil {
		return nil, grmi.NewBusinessError("总成不存在")
	}
	var workLineIdLi []interface{}
	if product.MultiWorkLineToggle {
		productWorkLineDao := dal.NewProductWorkLineLstDAO(session, user.PlantNr, user.UserId)
		relateLi, err := productWorkLineDao.Select([]grmi.Predicate{
			meta.ProductWorkLineLst_ProductId.NewPredicate(grmi.Equal, productId),
			meta.ProductWorkLineLst_ProjectId.NewPredicate(grmi.Equal, projectId),
		}, nil)
		if err != nil {
			return nil, grmi.NewBusinessError("查询总成关联产线失败, 错误:" + err.Error())
		}
		for _, relateData := range relateLi {
			workLineIdLi = append(workLineIdLi, relateData.WorkLineId)
		}
	} else {
		workLineIdLi = append(workLineIdLi, product.DefaultWorkLineId)
	}
	workLineDao := baseDal.NewWorkLineDAO(session, user.PlantNr, user.UserId)
	workLineLi, err := workLineDao.Select([]grmi.Predicate{
		baseMeta.WorkLine_WorkLineid.NewPredicate(grmi.Include, workLineIdLi...),
	}, []grmi.Field{baseMeta.WorkLine_WorkLineid})
	if err != nil {
		return nil, grmi.NewBusinessError("查询产线数据失败, 错误:" + err.Error())
	}
	return workLineLi, nil
}