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

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	meDal "LAPP_ACURA_MOM_BACKEND/dao/me"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	meMeta "LAPP_ACURA_MOM_BACKEND/meta/me"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	meModel "LAPP_ACURA_MOM_BACKEND/models/me"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : Article的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-06 15:52:37
 *
 ******************************************************************************/
var DefaultConditionOfArticle = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Article_ArtId.UrlParameterName:                grmi.NewConditionItem(meta.Article_ArtId, grmi.Equal, true),
		meta.Article_Descr1.UrlParameterName:               grmi.NewConditionItem(meta.Article_Descr1, grmi.Equal, false),
		meta.Article_Descr2.UrlParameterName:               grmi.NewConditionItem(meta.Article_Descr2, grmi.Equal, false),
		meta.Article_ArtTypeId.UrlParameterName:            grmi.NewConditionItem(meta.Article_ArtTypeId, grmi.Equal, false),
		meta.Article_ProjectId.UrlParameterName:            grmi.NewConditionItem(meta.Article_ProjectId, grmi.Equal, true),
		meta.Article_CustArtId.UrlParameterName:            grmi.NewConditionItem(meta.Article_CustArtId, grmi.Equal, false),
		meta.Article_AlternativeArtId.UrlParameterName:     grmi.NewConditionItem(meta.Article_AlternativeArtId, grmi.Equal, false),
		meta.Article_PlanResourceGroupId.UrlParameterName:  grmi.NewConditionItem(meta.Article_PlanResourceGroupId, grmi.Equal, false),
		meta.Article_PlanResourceId.UrlParameterName:       grmi.NewConditionItem(meta.Article_PlanResourceId, grmi.Equal, false),
		meta.Article_UsedResourceId.UrlParameterName:       grmi.NewConditionItem(meta.Article_UsedResourceId, grmi.Equal, false),
		meta.Article_UomId.UrlParameterName:                grmi.NewConditionItem(meta.Article_UomId, grmi.Equal, false),
		meta.Article_PlanScrapRate.UrlParameterName:        grmi.NewConditionItem(meta.Article_PlanScrapRate, grmi.Equal, false),
		meta.Article_RatePerHourToggle.UrlParameterName:    grmi.NewConditionItem(meta.Article_RatePerHourToggle, grmi.Equal, false),
		meta.Article_TimePerItemToggle.UrlParameterName:    grmi.NewConditionItem(meta.Article_TimePerItemToggle, grmi.Equal, false),
		meta.Article_TimePerBatchToggle.UrlParameterName:   grmi.NewConditionItem(meta.Article_TimePerBatchToggle, grmi.Equal, false),
		meta.Article_BatchTimeFieldToggle.UrlParameterName: grmi.NewConditionItem(meta.Article_BatchTimeFieldToggle, grmi.Equal, false),
		meta.Article_OpTimePerItem.UrlParameterName:        grmi.NewConditionItem(meta.Article_OpTimePerItem, grmi.Equal, false),
		meta.Article_BatchTime.UrlParameterName:            grmi.NewConditionItem(meta.Article_BatchTime, grmi.Equal, false),
		meta.Article_QuantityPerHour.UrlParameterName:      grmi.NewConditionItem(meta.Article_QuantityPerHour, grmi.Equal, false),
		meta.Article_MidBatchQuantity.UrlParameterName:     grmi.NewConditionItem(meta.Article_MidBatchQuantity, grmi.Equal, false),
		meta.Article_MidBatchTime.UrlParameterName:         grmi.NewConditionItem(meta.Article_MidBatchTime, grmi.Approximate, false),
		meta.Article_EffectiveOpTime.UrlParameterName:      grmi.NewConditionItem(meta.Article_EffectiveOpTime, grmi.Equal, false),
		meta.Article_BatchingMethod.UrlParameterName:       grmi.NewConditionItem(meta.Article_BatchingMethod, grmi.Equal, false),
		meta.Article_DeliveryBuffer.UrlParameterName:       grmi.NewConditionItem(meta.Article_DeliveryBuffer, grmi.Equal, false),
		meta.Article_Icon.UrlParameterName:                 grmi.NewConditionItem(meta.Article_Icon, grmi.Equal, false),
		meta.Article_DisplayColor.UrlParameterName:         grmi.NewConditionItem(meta.Article_DisplayColor, grmi.Equal, false),
		meta.Article_Document.UrlParameterName:             grmi.NewConditionItem(meta.Article_Document, grmi.Equal, false),
		meta.Article_DefaultRoute.UrlParameterName:         grmi.NewConditionItem(meta.Article_DefaultRoute, grmi.Equal, false),
		meta.Article_DefaultInspectPlanId.UrlParameterName: grmi.NewConditionItem(meta.Article_DefaultInspectPlanId, grmi.Equal, false),
		meta.Article_LotSize.UrlParameterName:              grmi.NewConditionItem(meta.Article_LotSize, grmi.Equal, false),
		meta.Article_ABCClass.UrlParameterName:             grmi.NewConditionItem(meta.Article_ABCClass, grmi.Equal, false),
		meta.Article_PickingToggle.UrlParameterName:        grmi.NewConditionItem(meta.Article_PickingToggle, grmi.Equal, false),
		meta.Article_ArtSize1.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSize1, grmi.Equal, false),
		meta.Article_ArtSize2.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSize2, grmi.Equal, false),
		meta.Article_ArtSize3.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSize3, grmi.Equal, false),
		meta.Article_ArtSize4.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSize4, grmi.Equal, false),
		meta.Article_ArtSize5.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSize5, grmi.Equal, false),
		meta.Article_ArtSpec1.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSpec1, grmi.Equal, false),
		meta.Article_ArtSpec2.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSpec2, grmi.Equal, false),
		meta.Article_ArtSpec3.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSpec3, grmi.Equal, false),
		meta.Article_ArtSpec4.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSpec4, grmi.Equal, false),
		meta.Article_ArtSpec5.UrlParameterName:             grmi.NewConditionItem(meta.Article_ArtSpec5, grmi.Equal, false),
		meta.Article_PickingFlag.UrlParameterName:          grmi.NewConditionItem(meta.Article_ArtSpec5, grmi.Equal, false),
		meta.Article_Prefix.UrlParameterName:               grmi.NewConditionItem(meta.Article_Prefix, grmi.Equal, false),
		meta.Article_BackFlushItemToggle.UrlParameterName:  grmi.NewConditionItem(meta.Article_BackFlushItemToggle, grmi.Equal, false),
		meta.Article_CriticalItem.UrlParameterName:         grmi.NewConditionItem(meta.Article_CriticalItem, grmi.Equal, false),
		meta.Article_Version.UrlParameterName:              grmi.NewConditionItem(meta.Article_Version, grmi.Equal, false),
		meta.Article_LastModify.UrlParameterName:           grmi.NewConditionItem(meta.Article_LastModify, grmi.Approximate, false),
		meta.Article_LastUser.UrlParameterName:             grmi.NewConditionItem(meta.Article_LastUser, grmi.Equal, false),
		meta.Article_CreateTime.UrlParameterName:           grmi.NewConditionItem(meta.Article_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Article的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-06 15:52:37
 *
 ******************************************************************************/
var DefaultConditionOfArticleAndPaging = grmi.NewCondition(
	DefaultConditionOfArticle.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ArticleServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Article的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-06 15:52:37
 *
 ******************************************************************************/
type ArticleServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewArticleDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ArticleDAOImplement实例
 *
 * @Return Value             : ArticleDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-06 15:52:37
 *
 ******************************************************************************/
func NewArticleServiceImplement() *ArticleServiceImplement {
	return &ArticleServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.InsertOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) InsertOne(user *global.User, entity *model.Article) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "InsertOneArticle", "插入一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ArtId, entity.ProjectId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	if len(entity.Prefix) > 5 {
		return grmi.NewBusinessError("物料前缀不得超过5位")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		session.Rollback()
		return err
	}

	/**处理数据**/
	AtcodLst := make([]model.ArticleAtcodLst, 0)
	for _, v := range entity.Valst {
		onedata := model.ArticleAtcodLst{}
		onedata.ArtId = entity.ArtId
		onedata.ProjectId = entity.ProjectId
		onedata.Version = 1
		onedata.AttrCode = v.AttrCode
		onedata.AttrValue = v.AttrValue
		AtcodLst = append(AtcodLst, onedata)
	}
	lstdao := dal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.Insert(&AtcodLst)
	if err != nil {
		session.Rollback()
		return err
	}
	session.Commit()

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.DeleteOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) DeleteOne(user *global.User, artId string, projectId string) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "DeleteOneArticle", "删除一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	bomHeadDao := meDal.NewBomHeadDAO(session, user.PlantNr, user.UserId)
	bomLstDao := meDal.NewBomLstDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(artId, projectId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(artId, projectId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	lstdao := dal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.DeleteWhere([]grmi.Predicate{
		meta.ArticleAtcodLst_ArtId.NewPredicate(grmi.Equal, artId),
	})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = bomHeadDao.DeleteWhere([]grmi.Predicate{meMeta.BomHead_BomId.NewPredicate(grmi.Equal, artId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = bomLstDao.DeleteWhere([]grmi.Predicate{meMeta.BomLst_BomId.NewPredicate(grmi.Equal, artId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.SelectOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) SelectOne(user *global.User, artId string, projectId string) (*model.Article, error) {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "SelectOneArticle", "查询一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(artId, projectId)
	if err != nil {
		return nil, err
	}
	lstdao := dal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	list, err := lstdao.SelectAllot(artId, projectId)
	if err != nil {
		return nil, err
	}
	if utils.ValueIsEmpty(result) {
		return nil, err
	}
	//获取已分配的属性集合
	var attrCodes []int
	for _, v := range list {
		attrCodes = append(attrCodes, v.AttrCode)
	}
	unlist, err := lstdao.SelectUnAllot(attrCodes)
	if err != nil {
		return nil, err
	}
	//查询已分配
	result.Valst = list
	//查询未分配
	result.UnValst = unlist
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.UpdateOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) UpdateOne(user *global.User, entity *model.Article) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "UpdateOneArticle", "修改一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	productDao := meDal.NewProductDAO(session, user.PlantNr, user.UserId)
	dao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ArtId, entity.ProjectId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if len(entity.Prefix) > 5 {
		return grmi.NewBusinessError("物料前缀不得超过5位")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}

	/**处理数据**/
	AtcodLst := make([]model.ArticleAtcodLst, 0)
	for _, v := range entity.Valst {
		onedata := model.ArticleAtcodLst{}
		onedata.ArtId = entity.ArtId
		onedata.ProjectId = entity.ProjectId
		onedata.Version = 1
		onedata.AttrCode = v.AttrCode
		onedata.AttrValue = v.AttrValue
		AtcodLst = append(AtcodLst, onedata)
	}
	lstdao := dal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.DeleteWhere([]grmi.Predicate{
		meta.ArticleAtcodLst_ArtId.NewPredicate(grmi.Equal, entity.ArtId),
		meta.ArticleAtcodLst_ProjectId.NewPredicate(grmi.Equal, entity.ProjectId),
	})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = lstdao.Insert(&AtcodLst)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if entity.ArtSpec1 == model.ART_TYPE_FINISHED && (record.CustArtId != entity.CustArtId || record.Descr1 != entity.Descr1) {
		product, err := productDao.SelectOne(entity.ArtId, entity.ProjectId)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询总成数据失败, error:" + err.Error())
		}
		if product != nil {
			product.Descr = entity.Descr1
			product.CustPartId = entity.CustArtId
			err = productDao.UpdateOne(product)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("查询更新总成数据失败, error:" + err.Error())
			}
		}
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.Insert
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Insert(user *global.User, entities *[]model.Article) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "InsertArticle", "插入多个Article")

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

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

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "DeleteArticle", "删除多个Article")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ArtId, 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/base/ArticleService.Select
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Select(user *global.User, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "SelectArticle", "查询Article")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.Update
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Update(user *global.User, entities *[]model.Article) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "UpdateArticle", "修改多个Article")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ArtId, entity.ProjectId)
		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/base/ArticleService.SelectByWorkLine
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) SelectByWorkLine(user *global.User, workLineId string) (interface{}, error) {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "SelectByWorkLine", "通过产线查询总成")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtWorkLineLstDAO(session, user.PlantNr, user.UserId)
	articleLi, err := dao.SelectByFinishArtWorkLine(workLineId)
	return articleLi, err
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/ArticleService.SelectCols
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) SelectCols(user *global.User, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "SelectCols", "查询Article指定列")

	condition := DefaultConditionOfArticleAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectCols(predicates, condition.OrderByFields, []string{meta.Article_ArtId.ColumnName, meta.Article_Descr1.ColumnName})
	if err != nil {
		return nil, err
	}
	return result, nil
}

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	daoProject := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	daoArticle := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	daoProduct := meDal.NewProductDAO(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{})
	articleLi := make([]model.Article, 0)
	productLi := make([]meModel.Product, 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) != 23 {
			return grmi.NewBusinessError("excel数据列数不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		_, exist := projectMap[row[3]]
		if !exist {
			project, err := daoProject.SelectOne(row[3])
			if err != nil {
				return grmi.NewBusinessError("查询车型项目数据失败， error:" + err.Error())
			}
			if project == nil {
				return grmi.NewBusinessError("车型项目不存在, 车型项目ID:" + row[3])
			}
			projectMap[row[3]] = nil
		}
		var pickingToggle bool
		if row[8] == "1" {
			pickingToggle = true
		} else if row[8] == "0" {
			pickingToggle = false
		} else {
			return grmi.NewBusinessError("excel数据pickingToggle不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		var backFlushToggle bool
		if row[11] == "1" {
			backFlushToggle = true
		} else if row[11] != "0" {
			return grmi.NewBusinessError("excel数据backFlushToggle不合规, 行数:" + strconv.Itoa(rowIndex))
		}

		article := model.Article{
			ArtId: row[0],
			// 中文描述
			Descr1: row[1],
			// 产品号
			Descr2:              row[2],
			ProjectId:           row[3],
			CustArtId:           row[4],
			AlternativeArtId:    row[5],
			ArtSpec1:            row[6],
			ArtSpec2:            row[7],
			PickingToggle:       pickingToggle,
			Version:             row[9],
			PickingFlag:         row[10],
			BackFlushItemToggle: backFlushToggle,
			Prefix:              row[12],
		}
		articleLi = append(articleLi, article)
		if row[6] == model.ART_TYPE_FINISHED {
			PackOrderItemSize, err := strconv.Atoi(row[16])
			if err != nil {
				return grmi.NewBusinessError("excel数据PackOrderItemSize不合规, 行数:" + strconv.Itoa(rowIndex))
			}
			var CreateWorkOrderToggle bool
			if row[20] == "1" {
				CreateWorkOrderToggle = true
			} else if row[20] != "0" {
				return grmi.NewBusinessError("excel数据CreateWorkOrderToggle不合规, 行数:" + strconv.Itoa(rowIndex))
			}
			var CreatePackOrderToggle bool
			if row[21] == "1" {
				CreatePackOrderToggle = true
			} else if row[21] != "0" {
				return grmi.NewBusinessError("excel数据CreatePackOrderToggle不合规, 行数:" + strconv.Itoa(rowIndex))
			}
			product := meModel.Product{
				ProductId:             article.ArtId,
				Descr:                 article.Descr1,
				ProjectId:             article.ProjectId,
				DefaultWorkLineId:     row[13],
				PartId:                article.ArtId,
				CustPartId:            article.CustArtId,
				IntPartId:             article.ArtId,
				PickingFlag:           row[14],
				MachineCode:           row[15],
				PackOrderItemSize:     PackOrderItemSize,
				ColorValue:            row[17],
				ProductType:           row[18],
				PrintTemplateId:       row[19],
				CreateWorkOrderToggle: CreateWorkOrderToggle,
				CreatePackOrderToggle: CreatePackOrderToggle,
			}
			productLi = append(productLi, product)
		}
	}
	if err = session.Begin(); err != nil {
		return err
	}
	tempArticleLi := make([]model.Article, 0, 20)
	for index, article := range articleLi {
		if index != 0 && index%20 == 0 {
			err = daoArticle.Insert(&tempArticleLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("保存物料数据, error:" + err.Error())
			}
			tempArticleLi = make([]model.Article, 0, 20)
		}
		tempArticleLi = append(tempArticleLi, article)
	}
	if len(tempArticleLi) != 0 {
		err = daoArticle.Insert(&tempArticleLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("保存物料数据, error:" + err.Error())
		}
	}
	tempProductLi := make([]meModel.Product, 0, 20)
	for index, product := range productLi {
		if index != 0 && index%20 == 0 {
			err = daoProduct.Insert(&tempProductLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("保存产品数据, error:" + err.Error())
			}
			tempProductLi = make([]meModel.Product, 0, 20)
		}
		tempProductLi = append(tempProductLi, product)
	}
	if len(tempProductLi) != 0 {
		err = daoProduct.Insert(&tempProductLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("保存产品数据, error:" + err.Error())
		}
	}
	_ = session.Commit()
	return nil
}

// Copy 复制零件数据 修改项目ID
func (impl *ArticleServiceImplement) Copy(user *global.User, articleId, projectId string, targetProjectId string) error {

	grmi.Log(user, "/services/base/implments/Article.service.impl.go", "SelectCols", "查询Article指定列")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	articleDao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	articleAtcodLstDao := dal.NewArticleAtcodLstDAO(session, user.PlantNr, user.UserId)
	artQtyAllocateDao := dal.NewArtQtyAllocateDAO(session, user.PlantNr, user.UserId)
	artCheckRuleDao := dal.NewArtCheckRuleDAO(session, user.PlantNr, user.UserId)
	projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	article, err := articleDao.SelectOne(articleId, projectId)
	if err != nil {
		return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
	}
	if article == nil {
		return grmi.NewBusinessError("不存在该物料, 物料ID:" + articleId + ", 项目ID:" + projectId)
	}
	if article.ArtSpec1 == model.ART_TYPE_FINISHED {
		return grmi.NewBusinessError("总成复制请在派生管理页面进行操作")
	}
	project, err := projectDao.SelectOne(targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询车型项目数据失败, error:" + err.Error())
	}
	if project == nil {
		return grmi.NewBusinessError("车型项目ID不存在")
	}
	targetArticle, err := articleDao.SelectOne(articleId, targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
	}
	if targetArticle != nil {
		return grmi.NewBusinessError("已存在需要复制的物料")
	}
	attributeAllocateLi, err := articleAtcodLstDao.Select([]grmi.Predicate{meta.ArticleAtcodLst_ArtId.NewPredicate(grmi.Equal, articleId),
		meta.ArticleAtcodLst_ProjectId.NewPredicate(grmi.Equal, projectId)},
		nil)
	if err != nil {
		return grmi.NewBusinessError("查询物料关联属性失败, error:" + err.Error())
	}
	var checkRuleLi []model.ArtCheckRule
	var qtyAllocateLi []model.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(articleId, projectId, attrCodeLi)
		if err != nil {
			return grmi.NewBusinessError("查询物料校验规则失败, error:" + err.Error())
		}
		qtyAllocateLi, err = artQtyAllocateDao.SelectByArtId(articleId, projectId, attrCodeLi)
		if err != nil {
			return grmi.NewBusinessError("查询物料特殊工位分配规则失败, error:" + err.Error())
		}
	}
	if err = session.Begin(); err != nil {
		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
}
