// 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"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	meModel "LAPP_ACURA_MOM_BACKEND/models/me"
)

/******************************************************************************
 *
 * @Description              : Operation的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-22 18:49:53
 *
 ******************************************************************************/
var DefaultConditionOfOperation = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Operation_OperationId.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OperationId, grmi.Equal, true),
		meta.Operation_PO.UrlParameterName:                      grmi.NewConditionItem(meta.Operation_PO, grmi.Equal, false),
		meta.Operation_ProjectId.UrlParameterName:               grmi.NewConditionItem(meta.Operation_ProjectId, grmi.Equal, false),
		meta.Operation_StepNo.UrlParameterName:                  grmi.NewConditionItem(meta.Operation_StepNo, grmi.Equal, false),
		meta.Operation_StepDesc.UrlParameterName:                grmi.NewConditionItem(meta.Operation_StepDesc, grmi.Equal, false),
		meta.Operation_ActivateInNormalStation.UrlParameterName: grmi.NewConditionItem(meta.Operation_ActivateInNormalStation, grmi.Equal, false),
		meta.Operation_ActivateInBKStation.UrlParameterName:     grmi.NewConditionItem(meta.Operation_ActivateInBKStation, grmi.Equal, false),
		meta.Operation_ActivateInRepStation.UrlParameterName:    grmi.NewConditionItem(meta.Operation_ActivateInRepStation, grmi.Equal, false),
		meta.Operation_AttrCode.UrlParameterName:                grmi.NewConditionItem(meta.Operation_AttrCode, grmi.Equal, false),
		meta.Operation_AttrValue.UrlParameterName:               grmi.NewConditionItem(meta.Operation_AttrValue, grmi.Equal, false),
		meta.Operation_StepType.UrlParameterName:                grmi.NewConditionItem(meta.Operation_StepType, grmi.Equal, false),
		meta.Operation_OPCtrlPara1.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara1, grmi.Equal, false),
		meta.Operation_OPCtrlPara2.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara2, grmi.Equal, false),
		meta.Operation_OPCtrlPara3.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara3, grmi.Equal, false),
		meta.Operation_OPCtrlPara4.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara4, grmi.Equal, false),
		meta.Operation_OPCtrlPara5.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara5, grmi.Equal, false),
		meta.Operation_OPCtrlPara6.UrlParameterName:             grmi.NewConditionItem(meta.Operation_OPCtrlPara6, grmi.Equal, false),
		meta.Operation_LastModify.UrlParameterName:              grmi.NewConditionItem(meta.Operation_LastModify, grmi.Approximate, false),
		meta.Operation_LastUser.UrlParameterName:                grmi.NewConditionItem(meta.Operation_LastUser, grmi.Equal, false),
		meta.Operation_CreateTime.UrlParameterName:              grmi.NewConditionItem(meta.Operation_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Operation的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-22 18:49:53
 *
 ******************************************************************************/
var DefaultConditionOfOperationAndPaging = grmi.NewCondition(
	DefaultConditionOfOperation.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : OperationServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Operation的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-22 18:49:53
 *
 ******************************************************************************/
type OperationServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewOperationDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个OperationDAOImplement实例
 *
 * @Return Value             : OperationDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-22 18:49:53
 *
 ******************************************************************************/
func NewOperationServiceImplement() *OperationServiceImplement {
	return &OperationServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/OperationService.InsertOne
 *
 ******************************************************************************/
func (impl *OperationServiceImplement) InsertOne(user *global.User, entity *model.Operation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	attributeDao := dal.NewAttributeValstDAO(session, user.PlantNr, user.UserId)
	processDao := dal.NewProcessDAO(session, user.PlantNr, user.UserId)
	stepDao := dal.NewStepTypeDAO(session, user.PlantNr, user.UserId)
	recordLi, err := dao.Select([]grmi.Predicate{meta.Operation_PO.NewPredicate(grmi.Equal, entity.PO),
		meta.Operation_ProjectId.NewPredicate(grmi.Equal, entity.ProjectId),
		meta.Operation_ActivateInBKStation.NewPredicate(grmi.Equal, entity.ActivateInBKStation),
		meta.Operation_StepNo.NewPredicate(grmi.Equal, entity.StepNo)}, nil)
	if err != nil {
		return grmi.NewBusinessError("查询已经原有数据失败, error:" + err.Error())
	}
	if len(recordLi) != 0 {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	process, err := processDao.SelectOne(entity.PO)
	if err != nil {
		return grmi.NewBusinessError("查询工序数据失败, error:" + err.Error())
	}
	if process == nil {
		return grmi.NewBusinessError("不存在指定的工序")
	}
	project, err := projectDao.SelectOne(entity.ProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询车型项目数据失败, error:" + err.Error())
	}
	if project == nil {
		return grmi.NewBusinessError("车型项目不存在, 车型项目ID:" + entity.ProjectId)
	}
	attributeLi, err := attributeDao.Select([]grmi.Predicate{meta.AttributeValst_AttrCode.NewPredicate(grmi.Equal, entity.AttrCode), meta.AttributeValst_AttrValue.NewPredicate(grmi.Equal, entity.AttrValue)}, nil)
	if err != nil {
		return grmi.NewBusinessError("查询属性数据失败, error:" + err.Error())
	}
	if len(attributeLi) == 0 {
		return grmi.NewBusinessError("不存在对应的零件属性数据")
	}
	step, err := stepDao.SelectOne(entity.StepType)
	if err != nil {
		return grmi.NewBusinessError("查询操作类型数据失败, error:" + err.Error())
	}
	if step == nil {
		return grmi.NewBusinessError("不存在对应的操作类型")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return grmi.NewBusinessError("保存数据失败, error:" + err.Error())
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/OperationService.DeleteOne
 *
 ******************************************************************************/
func (impl *OperationServiceImplement) DeleteOne(user *global.User, operationId int) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	opcBasicDao := dal.NewOPCBasicComInfoDAO(session, user.PlantNr, user.UserId)
	opcComDao := dal.NewOPCComRuleDAO(session, user.PlantNr, user.UserId)
	opcDetailDao := dal.NewOPCComDetailRuleDAO(session, user.PlantNr, user.UserId)
	opcCheckDao := dal.NewOPCComValueCheckRuleDAO(session, user.PlantNr, user.UserId)
	opcCheckDetailDao := dal.NewOPCComValueCheckRuleDetailDAO(session, user.PlantNr, user.UserId)
	twDao := dal.NewTightenWrenchInfoDAO(session, user.PlantNr, user.UserId)
	twrDao := dal.NewTightenWrenchRuleInfoDAO(session, user.PlantNr, user.UserId)
	scanDao := dal.NewScanRuleInfoDAO(session, user.PlantNr, user.UserId)
	printDao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	guideDao := dal.NewGuideRuleInfoDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(operationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(operationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = opcBasicDao.DeleteWhere([]grmi.Predicate{meta.OPCBasicComInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = opcComDao.DeleteWhere([]grmi.Predicate{meta.OPCComRule_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = opcDetailDao.DeleteWhere([]grmi.Predicate{meta.OPCComDetailRule_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = opcCheckDao.DeleteWhere([]grmi.Predicate{meta.OPCComValueCheckRule_CheckOperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除OPC问题项规则数据失败, error:" + err.Error())
	}

	err = opcCheckDetailDao.DeleteWhere([]grmi.Predicate{meta.OPCComValueCheckRuleDetail_CheckOperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除OPC问题项规则细则数据失败, error:" + err.Error())
	}
	err = twDao.DeleteWhere([]grmi.Predicate{meta.TightenWrenchInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = twrDao.DeleteWhere([]grmi.Predicate{meta.TightenWrenchRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = scanDao.DeleteWhere([]grmi.Predicate{meta.ScanRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = printDao.DeleteWhere([]grmi.Predicate{meta.PrintBasicRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除单据打印规则数据失败, error:" + err.Error())
	}
	err = guideDao.DeleteWhere([]grmi.Predicate{meta.GuideRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除指导操作数据失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/OperationService.SelectOne
 *
 ******************************************************************************/
func (impl *OperationServiceImplement) SelectOne(user *global.User, operationId int) (*model.Operation, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/OperationService.UpdateOne
 *
 ******************************************************************************/
func (impl *OperationServiceImplement) UpdateOne(user *global.User, entity *model.Operation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	attributeDao := dal.NewAttributeValstDAO(session, user.PlantNr, user.UserId)
	processDao := dal.NewProcessDAO(session, user.PlantNr, user.UserId)
	stepDao := dal.NewStepTypeDAO(session, user.PlantNr, user.UserId)
	opcBasicDao := dal.NewOPCBasicComInfoDAO(session, user.PlantNr, user.UserId)
	opcComDao := dal.NewOPCComRuleDAO(session, user.PlantNr, user.UserId)
	opcDetailDao := dal.NewOPCComDetailRuleDAO(session, user.PlantNr, user.UserId)
	opcCheckDao := dal.NewOPCComValueCheckRuleDAO(session, user.PlantNr, user.UserId)
	opcCheckDetailDao := dal.NewOPCComValueCheckRuleDetailDAO(session, user.PlantNr, user.UserId)
	twDao := dal.NewTightenWrenchInfoDAO(session, user.PlantNr, user.UserId)
	twrDao := dal.NewTightenWrenchRuleInfoDAO(session, user.PlantNr, user.UserId)
	scanDao := dal.NewScanRuleInfoDAO(session, user.PlantNr, user.UserId)
	guideRuleDao := dal.NewGuideRuleInfoDAO(session, user.PlantNr, user.UserId)
	printDao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.OperationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.PO != entity.PO {
		processLi, err := processDao.Select([]grmi.Predicate{meta.Process_PO.NewPredicate(grmi.Equal, entity.PO)}, nil)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if len(processLi) == 0 {
			_ = session.Rollback()
			return grmi.NewBusinessError("不存在对应的工序")
		}
	}
	if record.AttrCode != entity.AttrCode || record.AttrValue != record.AttrValue {
		attributeLi, err := attributeDao.Select([]grmi.Predicate{meta.AttributeValst_AttrCode.NewPredicate(grmi.Equal, entity.AttrCode), meta.AttributeValst_AttrValue.NewPredicate(grmi.Equal, entity.AttrValue)}, nil)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if len(attributeLi) == 0 {
			_ = session.Rollback()
			return grmi.NewBusinessError("不存在对应的零件属性数据")
		}
	}
	if record.StepType != entity.StepType {
		step, err := stepDao.SelectOne(entity.StepType)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if step == nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("不存在对应的操作类型")
		}
	}
	if record.StepDesc != entity.StepDesc || record.StepNo != entity.StepNo {
		basic := model.OPCBasicComInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		com := model.OPCComRule{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		detail := model.OPCComDetailRule{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		check := model.OPCComValueCheckRule{CheckStepDesc: entity.StepDesc, CheckStepNo: entity.StepNo}
		checkDetail := model.OPCComValueCheckRuleDetail{CheckStepDesc: entity.StepDesc, CheckStepNo: entity.StepNo}
		tw := model.TightenWrenchInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		twr := model.TightenWrenchRuleInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		scan := model.ScanRuleInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		gr := model.GuideRuleInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		pr := model.PrintBasicRuleInfo{StepDesc: entity.StepDesc, StepNo: entity.StepNo}
		err = opcBasicDao.UpdateWhere([]grmi.Predicate{meta.OPCBasicComInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &basic, meta.OPCBasicComInfo_StepDesc.Name, meta.OPCBasicComInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = opcComDao.UpdateWhere([]grmi.Predicate{meta.OPCComRule_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &com, meta.OPCComRule_StepDesc.Name, meta.OPCComRule_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = opcDetailDao.UpdateWhere([]grmi.Predicate{meta.OPCComDetailRule_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &detail, meta.OPCComDetailRule_StepDesc.Name, meta.OPCComDetailRule_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}

		err = opcCheckDao.UpdateWhere([]grmi.Predicate{meta.OPCComValueCheckRule_CheckOperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &check, meta.OPCComValueCheckRule_CheckStepDesc.Name, meta.OPCComValueCheckRule_CheckStepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = opcCheckDetailDao.UpdateWhere([]grmi.Predicate{meta.OPCComValueCheckRuleDetail_CheckOperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &checkDetail, meta.OPCComValueCheckRuleDetail_CheckStepDesc.Name, meta.OPCComValueCheckRuleDetail_CheckStepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = twDao.UpdateWhere([]grmi.Predicate{meta.TightenWrenchInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &tw, meta.TightenWrenchInfo_StepDesc.Name, meta.TightenWrenchInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = twrDao.UpdateWhere([]grmi.Predicate{meta.TightenWrenchRuleInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &twr, meta.TightenWrenchRuleInfo_StepDesc.Name, meta.TightenWrenchRuleInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = scanDao.UpdateWhere([]grmi.Predicate{meta.ScanRuleInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &scan, meta.ScanRuleInfo_StepDesc.Name, meta.ScanRuleInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = guideRuleDao.UpdateWhere([]grmi.Predicate{meta.GuideRuleInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &gr, meta.GuideRuleInfo_StepDesc.Name, meta.GuideRuleInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		err = printDao.UpdateWhere([]grmi.Predicate{meta.PrintBasicRuleInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &pr, meta.PrintBasicRuleInfo_StepDesc.Name, meta.PrintBasicRuleInfo_StepNo.Name)
		if err != nil {
			_ = session.Rollback()
			return err
		}
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/OperationService.Insert
 *
 ******************************************************************************/
func (impl *OperationServiceImplement) Insert(user *global.User, entities *[]model.Operation) error {

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

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

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

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

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

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

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

	condition := DefaultConditionOfOperationAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	orderBy := make([]grmi.Field, 0, 3)
	orderBy = append(orderBy, meta.Operation_ProjectId, meta.Operation_ActivateInBKStation, meta.Operation_StepNo)
	result, err := dao.Select(predicates, orderBy)
	if err != nil {
		return nil, err
	}
	return result, nil
}

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

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

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

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

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

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

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

// SelectOperationByArtId 查询工艺总览
func (impl *OperationServiceImplement) SelectOperationByArtId(user *global.User, productId string, projectId string, workLineId string) (interface{}, error) {
	grmi.Log(user, "/services/base/implments/Operation.service.impl.go", "SelectOperationByArtId", "通过总成id查询工艺路径")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	productDao := meDal.NewProductDAO(session, user.PlantNr, user.UserId)
	workLineProcessDao := dal.NewWorkLineProcessLstDAO(session, user.PlantNr, user.UserId)
	operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	printRuleDao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	scanRuleDao := dal.NewScanRuleInfoDAO(session, user.PlantNr, user.UserId)
	twDao := dal.NewTightenWrenchInfoDAO(session, user.PlantNr, user.UserId)
	twrDao := dal.NewTightenWrenchRuleInfoDAO(session, user.PlantNr, user.UserId)
	artCheckRuleDao := dal.NewArtCheckRuleDAO(session, user.PlantNr, user.UserId)
	attributeDao := dal.NewAttributeDAO(session, user.PlantNr, user.UserId)
	attrValueDao := dal.NewAttributeValstDAO(session, user.PlantNr, user.UserId)
	printerDao := dal.NewPrinterDAO(session, user.PlantNr, user.UserId)
	bomHeadDao := meDal.NewBomHeadDAO(session, user.PlantNr, user.UserId)
	articleDao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
	// 每道工序展示内容
	type POOperation struct {
		PO          string            `json:"POOperation-PO"`
		OperationLi []model.Operation `json:"POOperation-OperationLi"`
	}
	// 总成展示内容
	type ProductOperation struct {
		WorkLineId    string        `json:"ProductOperation-WorkLineId"`
		POOperationLi []POOperation `json:"ProductOperation-POOperationLi"`
	}
	// 单据打印 展示内容
	type OperationPrintRule struct {
		PrinterId string `json:"OperationPrintRule-PrinterId"`
		IP        string `json:"OperationPrintRule-IP"`
	}
	// 扫码校验 展示内容
	// 当OperationScanRule-DisplayType == "CheckAttribute"展示：
		//AttrCode      int    `json:"OperationScanRule-AttrCode"`
		//AttrCodeDesc  string `json:"OperationScanRule-AttrCodeDesc"`
		//AttrValue     string    `json:"OperationScanRule-AttrValue"`
		//AttrValueDesc string `json:"OperationScanRule-AttrValueDesc"`
	// 当OperationScanRule-DisplayType == "CheckRule" 展示:
		//ArtId         string `json:"OperationScanRule-ArtId"`
		//ArtDesc       string `json:"OperationScanRule-ArtDesc"`
		//CheckLength   int    `json:"OperationScanRule-CheckLength"`
		//CheckObject   string `json:"OperationScanRule-CheckObject"`
	type OperationScanRule struct {
		AttrCode      int    `json:"OperationScanRule-AttrCode"`
		AttrCodeDesc  string `json:"OperationScanRule-AttrCodeDesc"`
		AttrValue     string    `json:"OperationScanRule-AttrValue"`
		AttrValueDesc string `json:"OperationScanRule-AttrValueDesc"`
		ArtId         string `json:"OperationScanRule-ArtId"`
		ArtDesc       string `json:"OperationScanRule-ArtDesc"`
		CheckLength   int    `json:"OperationScanRule-CheckLength"`
		CheckObject   string `json:"OperationScanRule-CheckObject"`
		DisplayType string `json:"OperationScanRule-DisplayType"`
	}
	// 开放协议 展示内容
	type OperationTightenWrenchRule struct {
		IpAddress         string `json:"OperationTightenWrenchRule-IpAddress"`
		MainControlAction string `json:"OperationTightenWrenchRule-MainControlAction"`
		ControlId         string `json:"OperationTightenWrenchRule-ControlId"`
		ControlTime       int    `json:"OperationTightenWrenchRule-ControlTime"`
	}
	var result ProductOperation

	product, err := productDao.SelectOne(productId, projectId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询总成数据失败, error:" + err.Error())
	}
	if product == nil {
		return nil, grmi.NewBusinessError("总成不存在")
	}
	result.WorkLineId = workLineId
	poLi, err := workLineProcessDao.SelectProcessByWorkLine(workLineId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询工序数据失败, error:" + err.Error())
	}
	if len(poLi) == 0 {
		return nil, grmi.NewBusinessError("该产线未关联工序")
	}
	poIdLi := make([]string, 0, len(poLi))
	for _, po := range poLi {
		poIdLi = append(poIdLi, po.PO)
	}
	bomHead, err := bomHeadDao.SelectOne(productId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询物料BOM失败, error:" + err.Error())
	}
	if bomHead == nil {
		return nil, grmi.NewBusinessError("不存在对应的物料BOM, 物料ID:" + productId)
	}
	var Me meModel.BomLst
	Me.PlantNr = user.PlantNr
	Me.BomId = bomHead.BomId
	bomList, err := Me.SetMenu(bomHead.MatNr)
	if err != nil {
		return nil, grmi.NewBusinessError("获取BOM细则失败, error:" + err.Error())
	}
	if len(bomList) == 0 {
		return nil, grmi.NewBusinessError("未获取到BOM细则, 物料ID:" + bomHead.BomId)
	}
	bomHead.BomLstLi = bomList
	// 获取关联的所有零件ID
	artMap := impl.ExtractArtId(bomHead)
	artIdLi := make([]string, 0, len(artMap))
	for innerArtId := range artMap {
		artIdLi = append(artIdLi, innerArtId)
	}
	artIdLi = append(artIdLi, productId)
	meOperationLi, err := operationDao.GetMeOperation(artIdLi, projectId, poIdLi, workLineId)
	if err != nil {
		return nil, grmi.NewBusinessError("查询工艺数据失败, error:" + err.Error())
	}
	var currentPoId string
	var poOperationData POOperation
	nullData := make(map[string]string)
	nullLiData := []interface{}{nullData}
	for index, meOperation := range meOperationLi {
		operationId := meOperation.Operation.OperationId
		switch meOperation.StepType {
		case model.STEP_PRINT_RULE:
			printRuleLi, err := printRuleDao.Select([]grmi.Predicate{meta.PrintBasicRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)}, nil)
			if err != nil {
				return nil, grmi.NewBusinessError("查询打印规则失败, error:" + err.Error())
			}
			if len(printRuleLi) == 0 {
				meOperation.Operation.Rule = nullData
			} else {
				printerId := printRuleLi[0].PrinterId
				printer, err := printerDao.SelectOne(printerId)
				if err != nil {
					return nil, grmi.NewBusinessError("查询打印机数据失败, error:" + err.Error())
				}
				var ip string
				if printer != nil {
					ip = printer.IP
				}
				meOperation.Operation.Rule = OperationPrintRule{
					PrinterId: printerId,
					IP: ip,
				}
			}
		case model.STEP_CHECK_RULE:
			scanRule, err := scanRuleDao.SelectOne(operationId)
			if err != nil {
				return nil, grmi.NewBusinessError("查询单据打印规则失败, error:" + err.Error())
			}
			if scanRule == nil {
				meOperation.Operation.Rule = nullLiData
			} else {
				attrCode := meOperation.ArticleAtcodLst.AttrCode
				attrValue := meOperation.ArticleAtcodLst.AttrValue
				if scanRule.RuleType == model.SCAN_RULE_TYPE_OTHER ||
					(scanRule.RuleType == model.SCAN_RULE_TYPE_ARTICLE && scanRule.SRCtrlPara1 == model.SCAN_RULE_CRWAL){
					attribute, err := attributeDao.SelectOne(attrCode)
					if err != nil {
						return nil, grmi.NewBusinessError("查询属性数据失败, error:" + err.Error())
					}
					var attrCodeDesc string
					if attribute != nil {
						attrCodeDesc = attribute.Descr
					}
					attrValueLi, err := attrValueDao.Select([]grmi.Predicate{meta.AttributeValst_AttrCode.NewPredicate(grmi.Equal, attrCode),
						meta.AttributeValst_AttrValue.NewPredicate(grmi.Equal, attrValue)}, nil)
					if err != nil {
						return nil, grmi.NewBusinessError("查询属性值数据失败, error:" + err.Error())
					}
					var attrValueDesc string
					if len(attrValueLi) != 0 {
						attrValueDesc = attrValueLi[0].Descr
					}
					rule := OperationScanRule{
						DisplayType: "CheckAttribute",
						AttrCode: attrCode,
						AttrCodeDesc: attrCodeDesc,
						AttrValue: attrValue,
						AttrValueDesc: attrValueDesc,
					}
					meOperation.Operation.Rule = []interface{}{rule}
				} else {
					artId := meOperation.ArticleAtcodLst.ArtId
					article, err := articleDao.SelectOne(artId, projectId)
					if err != nil {
						return nil, grmi.NewBusinessError("查询物料失败, error:" + err.Error())
					}
					var artDesc string
					if article != nil {
						artDesc = article.Descr1
					}
					// TODO 删除了产线作为条件
					checkRuleLi, err := artCheckRuleDao.SelectOperationCheckRule(artId, attrCode, projectId)
					if err != nil {
						return nil, grmi.NewBusinessError("查询零件校验规则失败, error:" + err.Error())
					}
					if len(checkRuleLi) == 0 {
						meOperation.Operation.Rule = nullLiData
					} else {
						ruleLi := make([]interface{}, 0, len(checkRuleLi))
						for _, checkRule := range checkRuleLi {
							rule := OperationScanRule{
								DisplayType: "CheckRule",
								ArtId: artId,
								ArtDesc: artDesc,
								CheckLength: checkRule.CheckLength,
								CheckObject: checkRule.CheckObject,
							}
							ruleLi = append(ruleLi, rule)
						}
						meOperation.Operation.Rule = ruleLi
					}
				}
			}
		case model.STEP_TW_RULE:
			twLi, err := twDao.Select([]grmi.Predicate{meta.TightenWrenchInfo_OperationId.NewPredicate(grmi.Equal, operationId)}, []grmi.Field{meta.TightenWrenchInfo_WorkPlaceNr})
			if err != nil {
				return nil, grmi.NewBusinessError("查询开放协议失败, error:" + err.Error())
			}
			if len(twLi) == 0 {
				meOperation.Operation.Rule = nullLiData
			} else {
				ruleLi := make([]interface{}, 0, len(twLi))
				for _, tw := range twLi {
					ipAddress := tw.IpAddress
					twrLi, err := twrDao.Select([]grmi.Predicate{meta.TightenWrenchRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId),
						meta.TightenWrenchRuleInfo_WorkPlaceNr.NewPredicate(grmi.Equal, tw.WorkPlaceNr)}, []grmi.Field{meta.TightenWrenchRuleInfo_RuleId})
					if err != nil {
						return nil, grmi.NewBusinessError("查询开放协议细则失败, error:" + err.Error())
					}
					if len(twrLi) == 0 {
						rule := OperationTightenWrenchRule{
							IpAddress: ipAddress,
						}
						ruleLi = append(ruleLi, rule)
					} else {
						twr := twrLi[0]
						rule := OperationTightenWrenchRule{
							IpAddress: ipAddress,
							MainControlAction: twr.MainControlAction,
							ControlId: twr.ControlId,
							ControlTime: twr.ControlTime,
						}
						ruleLi = append(ruleLi, rule)
					}
				}
				meOperation.Operation.Rule = ruleLi
			}
		}
		if index == 0 {
			currentPoId = meOperation.Process.PO
			poOperationData.PO = currentPoId
		}
		if currentPoId != meOperation.Process.PO {
			result.POOperationLi = append(result.POOperationLi, poOperationData)
			poOperationData = POOperation{
				PO: meOperation.Process.PO,
			}
			currentPoId = meOperation.Process.PO
		}
		poOperationData.OperationLi = append(poOperationData.OperationLi, meOperation.Operation)
	}
	result.POOperationLi = append(result.POOperationLi, poOperationData)
	return &result, nil
}

// ExtractArtId 从Bom数据结构中提取需要的每种物料数量
func (impl *OperationServiceImplement) ExtractArtId(bomHead *meModel.BomHead) map[string]int {
	artMap := make(map[string]int)
	bomLstLi := bomHead.BomLstLi
	for _, bomLst := range bomLstLi {
		_, exist := artMap[bomLst.CmatNr]
		if exist {
			artMap[bomLst.CmatNr] += int(bomLst.CmatQty / bomLst.FmatQty)
		} else {
			artMap[bomLst.CmatNr] = int(bomLst.CmatQty / bomLst.FmatQty)
		}
	}
	return artMap
}

// Copy 通过项目复制工艺
func (impl *OperationServiceImplement) Copy(user *global.User, po string, sourceProjectId string, targetProjectId string, source string) (err error) {
	grmi.Log(user, "/services/base/implments/Operation.service.impl.go", "Copy", "通过项目复制工艺")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	project, err := projectDao.SelectOne(targetProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询目标项目数据失败, error:" + err.Error())
	}
	if project == nil {
		return grmi.NewBusinessError("目标项目不存在")
	}
	if source == "produce" {
		operationLi, err := operationDao.Select([]grmi.Predicate{meta.Operation_PO.NewPredicate(grmi.Equal, po), meta.Operation_ProjectId.NewPredicate(grmi.Equal, sourceProjectId)}, []grmi.Field{meta.Operation_StepNo})
		if err != nil {
			return grmi.NewBusinessError("查询工艺数据失败, error:" + err.Error())
		}
		if len(operationLi) == 0 {
			return grmi.NewBusinessError("来源项目在该工序不存在工艺数据")
		}
		if err = session.Begin(); err != nil {
			return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
		}
		for _, operation := range operationLi {
			var copyOperation model.Operation
			copyOperation = operation
			copyOperation.OperationId = 0
			copyOperation.ProjectId = targetProjectId
			err = operationDao.InsertOne(&copyOperation)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入复制的工艺数据失败, error:" + err.Error())
			}
			switch operation.StepType {
			case model.STEP_CHECK_RULE:
				scanRuleDao := dal.NewScanRuleInfoDAO(session, user.PlantNr, user.UserId)
				ruleLi, err := scanRuleDao.Select([]grmi.Predicate{meta.ScanRuleInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询扫码校验规则失败, error:" + err.Error())
				}
				for _, rule := range ruleLi {
					rule.OperationId = copyOperation.OperationId
					rule.ProjectId = copyOperation.ProjectId
					err = scanRuleDao.InsertOne(&rule)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入扫码校验规则失败, error:" + err.Error())
					}
				}
			case model.STEP_GUIDE_RULE:
				guideDao := dal.NewGuideRuleInfoDAO(session, user.PlantNr, user.UserId)
				ruleLi, err := guideDao.Select([]grmi.Predicate{meta.GuideRuleInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询指导操作规则失败, error:" + err.Error())
				}
				for _, rule := range ruleLi {
					rule.OperationId = copyOperation.OperationId
					rule.ProjectId = copyOperation.ProjectId
					err = guideDao.InsertOne(&rule)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入指导操作规则失败, error:" + err.Error())
					}
				}
			case model.STEP_PRINT_RULE:
				printRuleDao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
				ruleLi, err := printRuleDao.Select([]grmi.Predicate{meta.PrintBasicRuleInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询单据打印规则失败, error:" + err.Error())
				}
				for _, rule := range ruleLi {
					rule.OperationId = copyOperation.OperationId
					rule.ProjectId = copyOperation.ProjectId
					err = printRuleDao.InsertOne(&rule)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入单据打印规则失败, error:" + err.Error())
					}
				}
			case model.STEP_TW_RULE:
				twDao := dal.NewTightenWrenchInfoDAO(session, user.PlantNr, user.UserId)
				twDetailDao := dal.NewTightenWrenchRuleInfoDAO(session, user.PlantNr, user.UserId)
				twLi, err := twDao.Select([]grmi.Predicate{meta.TightenWrenchInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					return grmi.NewBusinessError("查询开放协议失败, error:" + err.Error())
				}
				twDetailLi, err := twDetailDao.Select([]grmi.Predicate{meta.TightenWrenchRuleInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					return grmi.NewBusinessError("查询开放协议详细规则失败, error:" + err.Error())
				}
				for _, tw := range twLi {
					tw.OperationId = copyOperation.OperationId
					tw.ProjectId = copyOperation.ProjectId
					err = twDao.InsertOne(&tw)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入开放协议规则失败, error:" + err.Error())
					}
				}
				for _, twDetail := range twDetailLi {
					twDetail.OperationId = copyOperation.OperationId
					twDetail.ProjectId = copyOperation.ProjectId
					err = twDetailDao.InsertOne(&twDetail)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入开放协议详细规则失败, error:" + err.Error())
					}
				}
			case model.STEP_OPC_RULE:
				opcBasicDao := dal.NewOPCBasicComInfoDAO(session, user.PlantNr, user.UserId)
				opcComDao := dal.NewOPCComRuleDAO(session, user.PlantNr, user.UserId)
				opcDetailDao := dal.NewOPCComDetailRuleDAO(session, user.PlantNr, user.UserId)
				basicLi, err := opcBasicDao.Select([]grmi.Predicate{meta.OPCBasicComInfo_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询opc基础通讯规则失败, error:" + err.Error())
				}
				comLi, err := opcComDao.Select([]grmi.Predicate{meta.OPCComRule_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询opc通讯规则失败, error:" + err.Error())
				}
				detailLi, err := opcDetailDao.Select([]grmi.Predicate{meta.OPCComDetailRule_OperationId.NewPredicate(grmi.Equal, operation.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询opc通讯详细规则失败, error:" + err.Error())
				}
				for _, basic := range basicLi {
					basic.OperationId = copyOperation.OperationId
					basic.ProjectId = copyOperation.ProjectId
					err = opcBasicDao.InsertOne(&basic)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入opc基础通讯规则失败, error:" + err.Error())
					}
				}
				for _, com := range comLi {
					com.OperationId = copyOperation.OperationId
					com.ProjectId = copyOperation.ProjectId
					err = opcComDao.InsertOne(&com)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入opc通讯规则失败, error:" + err.Error())
					}
				}
				for _, detail := range detailLi {
					detail.OperationId = copyOperation.OperationId
					detail.ProjectId = copyOperation.ProjectId
					err = opcDetailDao.InsertOne(&detail)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入opc通讯详细规则失败, error:" + err.Error())
					}
				}
			}
		}
		_ = session.Commit()
	} else {
		monitorOperationDao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
		opLi, err := monitorOperationDao.Select([]grmi.Predicate{meta.MonitorOperation_PO.NewPredicate(grmi.Equal, po), meta.MonitorOperation_ProjectId.NewPredicate(grmi.Equal, sourceProjectId)}, []grmi.Field{meta.MonitorOperation_StepNo})
		if err != nil {
			return grmi.NewBusinessError("查询监控工步数据失败, error:" + err.Error())
		}
		if len(opLi) == 0 {
			return grmi.NewBusinessError("未查询到需要复制的工艺数据")
		}
		if err = session.Begin(); err != nil {
			return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
		}
		for _, op := range opLi {
			var copyOperation model.MonitorOperation
			copyOperation = op
			copyOperation.OperationId = 0
			copyOperation.ProjectId = targetProjectId
			err = monitorOperationDao.InsertOne(&copyOperation)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入复制的监控工步数据失败, error:" + err.Error())
			}
			if op.StepType == model.STEP_OPC_RULE {
				monitorOPCBasicDao := dal.NewOPCMonitorBasicComInfoDAO(session, user.PlantNr, user.UserId)
				monitorOPCComDao := dal.NewOPCMonitorComRuleDAO(session, user.PlantNr, user.UserId)
				monitorOPCDetailDao := dal.NewOPCMonitorComDetailRuleDAO(session, user.PlantNr, user.UserId)
				basicLi, err := monitorOPCBasicDao.Select([]grmi.Predicate{meta.OPCMonitorBasicComInfo_OperationId.NewPredicate(grmi.Equal, op.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询监控工步的opc基础通讯规则失败, error:" + err.Error())
				}
				comLi, err := monitorOPCComDao.Select([]grmi.Predicate{meta.OPCMonitorComRule_OperationId.NewPredicate(grmi.Equal, op.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询监控工步的opc通讯规则失败, error:" + err.Error())
				}
				detailLi, err := monitorOPCDetailDao.Select([]grmi.Predicate{meta.OPCMonitorComDetailRule_OperationId.NewPredicate(grmi.Equal, op.OperationId)}, nil)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询监控工步的opc通讯详细规则失败, error:" + err.Error())
				}
				for _, basic := range basicLi {
					basic.OperationId = copyOperation.OperationId
					basic.ProjectId = copyOperation.ProjectId
					err = monitorOPCBasicDao.InsertOne(&basic)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入监控工步的opc基础通讯规则失败, error:" + err.Error())
					}
				}
				for _, com := range comLi {
					com.OperationId = copyOperation.OperationId
					com.ProjectId = copyOperation.ProjectId
					err = monitorOPCComDao.InsertOne(&com)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入监控工步的opc通讯规则失败, error:" + err.Error())
					}
				}
				for _, detail := range detailLi {
					detail.OperationId = copyOperation.OperationId
					detail.ProjectId = copyOperation.ProjectId
					err = monitorOPCDetailDao.InsertOne(&detail)
					if err != nil {
						_ = session.Rollback()
						return grmi.NewBusinessError("写入监控工步的opc通讯详细规则失败, error:" + err.Error())
					}
				}
			}
		}
		_ = session.Commit()
	}

	return nil

}
