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

package implments

import (
	baseDal "LAPP_ACURA_MOM_BACKEND/dao/base"
	jitDal "LAPP_ACURA_MOM_BACKEND/dao/jit"
	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"
	jitMeta "LAPP_ACURA_MOM_BACKEND/meta/jit"
	meta "LAPP_ACURA_MOM_BACKEND/meta/me"
	baseModel "LAPP_ACURA_MOM_BACKEND/models/base"
	jitModel "LAPP_ACURA_MOM_BACKEND/models/jit"
	model "LAPP_ACURA_MOM_BACKEND/models/me"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : ProductFamily的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 14:04:53
 *
 ******************************************************************************/
var DefaultConditionOfProductFamily = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ProductFamily_ProductFamilyId.UrlParameterName:     grmi.NewConditionItem(meta.ProductFamily_ProductFamilyId, grmi.Equal, true),
		meta.ProductFamily_Descr.UrlParameterName:               grmi.NewConditionItem(meta.ProductFamily_Descr, grmi.Equal, false),
		meta.ProductFamily_ProjectId.UrlParameterName:           grmi.NewConditionItem(meta.ProductFamily_ProjectId, grmi.Equal, false),
		meta.ProductFamily_ConfigValue.UrlParameterName:         grmi.NewConditionItem(meta.ProductFamily_ConfigValue, grmi.Equal, false),
		meta.ProductFamily_ModelValue.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_ModelValue, grmi.Equal, false),
		meta.ProductFamily_ColorValue.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_ColorValue, grmi.Equal, false),
		meta.ProductFamily_BroadcastPoint.UrlParameterName:      grmi.NewConditionItem(meta.ProductFamily_BroadcastPoint, grmi.Equal, false),
		meta.ProductFamily_AutoGenPackToggle.UrlParameterName:   grmi.NewConditionItem(meta.ProductFamily_AutoGenPackToggle, grmi.Equal, false),
		meta.ProductFamily_MultiWorkLineToggle.UrlParameterName: grmi.NewConditionItem(meta.ProductFamily_MultiWorkLineToggle, grmi.Equal, false),
		meta.ProductFamily_Jph.UrlParameterName:                 grmi.NewConditionItem(meta.ProductFamily_Jph, grmi.Equal, false),
		meta.ProductFamily_WorkLineId.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_WorkLineId, grmi.Equal, false),
		meta.ProductFamily_PackTypeId.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_PackTypeId, grmi.Equal, false),
		meta.ProductFamily_CheckSyncKey.UrlParameterName:        grmi.NewConditionItem(meta.ProductFamily_CheckSyncKey, grmi.Equal, false),
		meta.ProductFamily_Enable.UrlParameterName:              grmi.NewConditionItem(meta.ProductFamily_Enable, grmi.Equal, false),
		meta.ProductFamily_CtrlPara1.UrlParameterName:           grmi.NewConditionItem(meta.ProductFamily_CtrlPara1, grmi.Equal, false),
		meta.ProductFamily_CtrlPara2.UrlParameterName:           grmi.NewConditionItem(meta.ProductFamily_CtrlPara2, grmi.Equal, false),
		meta.ProductFamily_CtrlStr1.UrlParameterName:            grmi.NewConditionItem(meta.ProductFamily_CtrlStr1, grmi.Equal, false),
		meta.ProductFamily_CtrlStr2.UrlParameterName:            grmi.NewConditionItem(meta.ProductFamily_CtrlStr2, grmi.Equal, false),
		meta.ProductFamily_CtrlTime1.UrlParameterName:           grmi.NewConditionItem(meta.ProductFamily_CtrlTime1, grmi.Approximate, false),
		meta.ProductFamily_CtrlTime2.UrlParameterName:           grmi.NewConditionItem(meta.ProductFamily_CtrlTime2, grmi.Approximate, false),
		meta.ProductFamily_LastModify.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_LastModify, grmi.Approximate, false),
		meta.ProductFamily_LastUser.UrlParameterName:            grmi.NewConditionItem(meta.ProductFamily_LastUser, grmi.Equal, false),
		meta.ProductFamily_CreateTime.UrlParameterName:          grmi.NewConditionItem(meta.ProductFamily_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ProductFamily的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 14:04:53
 *
 ******************************************************************************/
var DefaultConditionOfProductFamilyAndPaging = grmi.NewCondition(
	DefaultConditionOfProductFamily.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ProductFamilyServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ProductFamily的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 14:04:53
 *
 ******************************************************************************/
type ProductFamilyServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewProductFamilyDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ProductFamilyDAOImplement实例
 *
 * @Return Value             : ProductFamilyDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 14:04:53
 *
 ******************************************************************************/
func NewProductFamilyServiceImplement() *ProductFamilyServiceImplement {
	return &ProductFamilyServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductFamilyService.InsertOne
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) InsertOne(user *global.User, entity *model.ProductFamily) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ProductFamilyId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}
func (impl *ProductFamilyServiceImplement) Association(user *global.User, entity *model.ProductFamily) error {
	grmi.Log(user, "/services/me/implments/ProductFamily.service.impl.go", "Association", "配置ProductFamily")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ProductFamilyId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	//删除配置
	relateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
	relateCondition := DefaultConditionOfProductFamilyRelateAndPaging
	urlParameters := make(map[string]string)
	urlParameters[meta.ProductFamilyRelate_ProductFamilyId.Name] = entity.ProductFamilyId
	predicates, err := relateCondition.BuildPredicates(urlParameters)
	if err != nil {
		return err
	}
	session.Begin()
	err = relateDao.DeleteWhere(predicates)
	if err != nil {
		session.Rollback()
		return err
	}
	//添加配置
	var relateData []model.ProductFamilyRelate
	for k, v := range entity.Product {
		if !(v.Count > 0) {
			return fmt.Errorf("请配置零件数量")
		}
		relateData = append(relateData, model.ProductFamilyRelate{
			ProductId:       v.ProductId,
			ProductFamilyId: record.ProductFamilyId,
			ProjectId:       record.ProjectId,
			ProductDescr:    v.Descr,
			Count:           v.Count,
			Pos:             k + 1,
		})
	}
	if len(relateData) == 0 {
		session.Commit()
		return nil
	}
	//添加
	if len(relateData) > 20 {
		var _infoList []model.ProductFamilyRelate
		for k, v := range relateData {
			_infoList = append(_infoList, v)
			if (k > 0 && k%20 == 0) || k+1 == len(relateData) {
				err = relateDao.Insert(&_infoList)
				if err != nil {
					session.Rollback()
					return err
				}
				_infoList = []model.ProductFamilyRelate{}
			}
		}
	} else {
		err = relateDao.Insert(&relateData)
		if err != nil {
			session.Rollback()
			return err
		}
	}
	session.Commit()
	return nil
}

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(productFamilyId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.ProjectId != projectId {
		return grmi.NewBusinessError("项目号与配置不匹配!")
	}
	err = dao.DeleteOne(productFamilyId)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductFamilyService.SelectOne
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) SelectOne(user *global.User, productFamilyId string) (*model.ProductFamily, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/ProductFamilyService.UpdateOne
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) UpdateOne(user *global.User, entity *model.ProductFamily) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ProductFamilyId)
	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/me/ProductFamilyService.Insert
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) Insert(user *global.User, entities *[]model.ProductFamily) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ProductFamilyId)
		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/ProductFamilyService.Delete
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) Delete(user *global.User, entities *[]model.ProductFamily) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ProductFamilyId)
		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/ProductFamilyService.Select
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.ProductFamily, error) {

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

	condition := DefaultConditionOfProductFamilyAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewProductFamilyDAO(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/ProductFamilyService.SelectAndPaging
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) SelectAndPaging(user *global.User, urlParameters map[string]string) (grmi.PagingResult, error) {

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

	condition := DefaultConditionOfProductFamilyAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	dao := dal.NewProductFamilyDAO(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/ProductFamilyService.Update
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) Update(user *global.User, entities *[]model.ProductFamily) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ProductFamilyId)
		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/me/ProductFamilyService.GeneratePackTemplate
 *
 ******************************************************************************/
func (impl *ProductFamilyServiceImplement) GeneratePackTemplate(user *global.User, productFamilyId string) error {
	grmi.Log(user, "/services/me/implments/ProductFamily.service.impl.go", "GeneratePackTemplate", "生成包装模板")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	familyRelateDao := dal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
	// 校验车型配置数据和座椅产品数据
	productFamily, err := dao.SelectOne(productFamilyId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询车型配置失败, error:" + err.Error())
	}
	if productFamily == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("该车型配置不存在, error:" + err.Error())
	}
	productLi, err := familyRelateDao.SelectProductByFamilyId(productFamily.ProjectId, productFamilyId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询产品数据失败, error:" + err.Error())
	}
	if len(productLi) == 0 {
		_ = session.Rollback()
		return grmi.NewBusinessError("当前车型配置下还没有维护座椅产品数据")
	}
	// 将车型配置下的产品数据插入到包装模板表中
	templateDao := jitDal.NewPackTemplateDAO(session, user.PlantNr, user.UserId)
	templateLstDao := jitDal.NewPackTemplateItemLstDAO(session, user.PlantNr, user.UserId)
	oldPackTemplate, err := templateDao.SelectOne(productFamilyId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询车型配置下的模板失败, error:" + err.Error())
	}
	if oldPackTemplate != nil {
		err = templateDao.DeleteOne(productFamilyId)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("删除已存在包装模板数据失败, error:" + err.Error())
		}
		err = templateLstDao.DeleteWhere([]grmi.Predicate{jitMeta.PackTemplateItemLst_PackTemplateId.NewPredicate(grmi.Equal, productFamilyId)})
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("删除已存在包装模板数据失败, error:" + err.Error())
		}
	}
	packTotalQty := 0
	templateLstLi := make([]jitModel.PackTemplateItemLst, 0, len(productLi))
	for index, product := range productLi {
		packTotalQty += product.PackOrderItemSize
		packTemplateLst := jitModel.PackTemplateItemLst{
			PackTemplateId: productFamilyId,
			Pos:            index + 1,
			PartId:         product.PartId,
			PlanQty:        product.PackOrderItemSize,
		}
		templateLstLi = append(templateLstLi, packTemplateLst)
	}
	err = templateLstDao.Insert(&templateLstLi)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存包装模板包装项数据失败, error:" + err.Error())
	}
	packTemplate := jitModel.PackTemplate{
		PackTemplateId: productFamilyId,
		EnabledToggle:  true,
		Descr:          productFamily.Descr,
		ProjectId:      productFamily.ProjectId,
		PackTypeId:     productFamily.PackTypeId,
		PlanQty:        packTotalQty,
		CheckSyncKey:   productFamily.CheckSyncKey,
	}
	err = templateDao.InsertOne(&packTemplate)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("插入模板数据失败, error:" + err.Error())
	}
	// 将生成包装模板的标志置位
	productFamily.AutoGenPackToggle = true
	err = dao.UpdateOne(productFamily)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("更新车型配置数据失败, error:" + err.Error())
	}
	// 更新全局包装模板数据
	err = templateLstDao.InitGlobalPackTemplate()
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("初始化全局模板数据失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

// ImportFromExcel 从excel导入数据
func (impl *ProductFamilyServiceImplement) ImportFromExcel(user *global.User, filepath string) error {
	grmi.Log(user, "/services/me/implments/ProductFamily.service.impl.go", "ImportFromExcel", "Copy复制Bom")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	daoProject := dal.NewProjectDAO(session, user.PlantNr, user.UserId)
	daoProductFamily := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	file, err := excelize.OpenFile(filepath)
	if err != nil {
		return grmi.NewBusinessError("读取文件失败, error:" + err.Error())
	}
	rowsIterator, err := file.Rows("Sheet1")
	if err != nil {
		return grmi.NewBusinessError("读取Sheet1页失败, error:" + err.Error())
	}
	rowIndex := 0
	projectMap := make(map[string]interface{})
	productFamilyLi := make([]model.ProductFamily, 0)
	for rowsIterator.Next() {
		rowIndex++
		if rowIndex == 1 {
			_, err = rowsIterator.Columns()
			if err != nil {
				return grmi.NewBusinessError("去读excel行数据失败, error:" + err.Error())
			}
			continue
		}
		row, err := rowsIterator.Columns()
		if err != nil {
			return grmi.NewBusinessError("去读excel行数据失败, error:" + err.Error())
		}
		if len(row) != 12 {
			return grmi.NewBusinessError("excel数据不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		_, exist := projectMap[row[2]]
		if !exist {
			project, err := daoProject.SelectOne(row[2])
			if err != nil {
				return grmi.NewBusinessError("查询车型项目数据失败， error:" + err.Error())
			}
			if project == nil {
				return grmi.NewBusinessError("车型项目不存在, 车型项目ID:" + row[2])
			}
			projectMap[row[2]] = nil
		}
		var autoGenPackToggle bool
		if row[6] == "0" {
			autoGenPackToggle = false
		} else if row[6] == "1" {
			autoGenPackToggle = true
		} else {
			return grmi.NewBusinessError("excel数据不合规, 行数:" + strconv.Itoa(rowIndex))
		}

		jph, err := strconv.Atoi(row[7])
		if err != nil {
			return grmi.NewBusinessError("excel数据不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		var checkSynKey bool
		if row[10] == "0" {
			checkSynKey = false
		} else if row[10] == "1" {
			checkSynKey = true
		} else {
			return grmi.NewBusinessError("excel数据不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		productFamily := model.ProductFamily{
			ProductFamilyId:   row[0],
			Descr:             row[1],
			ProjectId:         row[2],
			ConfigValue:       row[3],
			ModelValue:        row[4],
			ColorValue:        row[5],
			AutoGenPackToggle: autoGenPackToggle,
			Jph:               float64(jph),
			WorkLineId:        row[8],
			PackTypeId:        row[9],
			CheckSyncKey:      checkSynKey,
		}
		productFamilyLi = append(productFamilyLi, productFamily)
	}
	if err = session.Begin(); err != nil {
		return err
	}
	tempProductFamilyLi := make([]model.ProductFamily, 0, 20)
	for index, productFamily := range productFamilyLi {
		if index != 0 && index%20 == 0 {
			err = daoProductFamily.Insert(&tempProductFamilyLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入派生数据失败, error:" + err.Error())
			}
			tempProductFamilyLi = make([]model.ProductFamily, 0, 20)
		}
		tempProductFamilyLi = append(tempProductFamilyLi, productFamily)
	}
	if len(tempProductFamilyLi) != 0 {
		err = daoProductFamily.Insert(&tempProductFamilyLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("写入派生数据失败, error:" + err.Error())
		}
	}
	_ = session.Commit()
	return nil
}

// SelectCanProductWorkLine 查询该派生可生产的产线
func (impl *ProductFamilyServiceImplement) SelectCanProductWorkLine(user *global.User, productFamilyId string) ([]baseModel.WorkLine, error) {
	grmi.Log(user, "/services/me/implments/ProductFamily.service.impl.go", "SelectCanProductWorkLine", "查询该派生可生产的产线")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	productFamilyDao := dal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	productFamilyWorkLineDao := dal.NewProductFamilyWorkLineLstDAO(session, user.PlantNr, user.UserId)
	workLineDao := baseDal.NewWorkLineDAO(session, user.PlantNr, user.UserId)
	result := make([]baseModel.WorkLine, 0, 2)
	productFamily, err := productFamilyDao.SelectOne(productFamilyId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询派生数据失败, 错误:" + err.Error())
	}
	if productFamily == nil {
		return nil, grmi.NewBusinessError("派生不存在")
	}
	if !productFamily.MultiWorkLineToggle {
		if productFamily.WorkLineId == "" {
			return nil, grmi.NewBusinessError("该派生未配置产线")
		}
		workLine, err := workLineDao.SelectOne(productFamily.WorkLineId)
		if err != nil {
			return nil, grmi.NewBusinessError("查询产线失败, 错误:" + err.Error())
		}
		if workLine == nil {
			return result, nil
		}
		result = append(result, *workLine)
		return result, nil
	} else {
		relateWorkLineLi, err := productFamilyWorkLineDao.Select([]grmi.Predicate{
			meta.ProductFamilyWorkLineLst_ProductFamilyId.NewPredicate(grmi.Equal, productFamilyId),
		}, nil)
		if err != nil {
			return nil, grmi.NewBusinessError("查询派生可生产产线失败, 错误:" + err.Error())
		}
		if len(relateWorkLineLi) == 0 {
			return result, nil
		}
		workLineIdLi := make([]interface{}, 0, len(relateWorkLineLi))
		for _, relateWorkLine := range relateWorkLineLi {
			workLineIdLi = append(workLineIdLi, relateWorkLine.WorkLineId)
		}
		workLineLi, err := workLineDao.Select([]grmi.Predicate{
			baseMeta.WorkLine_WorkLineid.NewPredicate(grmi.Include, workLineIdLi...),
		}, []grmi.Field{baseMeta.WorkLine_WorkLineid})
		return workLineLi, err
	}
}