// 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"
)

/******************************************************************************
 *
 * @Description              : MonitorOperation的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-25 09:48:01
 *
 ******************************************************************************/
var DefaultConditionOfMonitorOperation = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.MonitorOperation_OperationId.UrlParameterName:   grmi.NewConditionItem(meta.MonitorOperation_OperationId, grmi.Equal, true),
		meta.MonitorOperation_PO.UrlParameterName:            grmi.NewConditionItem(meta.MonitorOperation_PO, grmi.Equal, false),
		meta.MonitorOperation_StepNo.UrlParameterName:        grmi.NewConditionItem(meta.MonitorOperation_StepNo, grmi.Equal, false),
		meta.MonitorOperation_StepDesc.UrlParameterName:      grmi.NewConditionItem(meta.MonitorOperation_StepDesc, grmi.Equal, false),
		meta.MonitorOperation_StepType.UrlParameterName:      grmi.NewConditionItem(meta.MonitorOperation_StepType, grmi.Equal, false),
		meta.MonitorOperation_ProjectId.UrlParameterName:     grmi.NewConditionItem(meta.MonitorOperation_ProjectId, grmi.Equal, false),
		meta.MonitorOperation_TriggerPoint.UrlParameterName:  grmi.NewConditionItem(meta.MonitorOperation_TriggerPoint, grmi.Equal, false),
		meta.MonitorOperation_RunForeground.UrlParameterName: grmi.NewConditionItem(meta.MonitorOperation_RunForeground, grmi.Equal, false),
		meta.MonitorOperation_LastModify.UrlParameterName:    grmi.NewConditionItem(meta.MonitorOperation_LastModify, grmi.Approximate, false),
		meta.MonitorOperation_LastUser.UrlParameterName:      grmi.NewConditionItem(meta.MonitorOperation_LastUser, grmi.Equal, false),
		meta.MonitorOperation_CreateTime.UrlParameterName:    grmi.NewConditionItem(meta.MonitorOperation_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : MonitorOperation的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-25 09:48:01
 *
 ******************************************************************************/
var DefaultConditionOfMonitorOperationAndPaging = grmi.NewCondition(
	DefaultConditionOfMonitorOperation.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : MonitorOperationServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : MonitorOperation的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-25 09:48:01
 *
 ******************************************************************************/
type MonitorOperationServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewMonitorOperationDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个MonitorOperationDAOImplement实例
 *
 * @Return Value             : MonitorOperationDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-25 09:48:01
 *
 ******************************************************************************/
func NewMonitorOperationServiceImplement() *MonitorOperationServiceImplement {
	return &MonitorOperationServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MonitorOperationService.InsertOne
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) InsertOne(user *global.User, entity *model.MonitorOperation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.OperationId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	poDao := dal.NewProcessDAO(session, user.PlantNr, user.UserId)
	process, err := poDao.SelectOne(entity.PO)
	if err != nil {
		return grmi.NewBusinessError("查询工步绑定工序失败, error:" + err.Error())
	}
	if process == nil {
		return grmi.NewBusinessError("工序不存在, PO:" + entity.PO)
	}
	projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	project, err := projectDao.SelectOne(entity.ProjectId)
	if err != nil {
		return grmi.NewBusinessError("查询车型项目ID失败, error:" + err.Error())
	}
	if project == nil {
		return grmi.NewBusinessError("车型项目不存在, 车型项目ID:" + entity.ProjectId)
	}
	stepTypeDao := dal.NewStepTypeDAO(session, user.PlantNr, user.UserId)
	stepType, err := stepTypeDao.SelectOne(entity.StepType)
	if err != nil {
		return grmi.NewBusinessError("查询操作类型失败, error:" + err.Error())
	}
	if stepType == nil {
		return grmi.NewBusinessError("操作类型不存在, 操作类型:" + entity.StepType)
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(operationId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if err := session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	opcMonitorBasicDao := dal.NewOPCMonitorBasicComInfoDAO(session, user.PlantNr, user.UserId)
	opcMonitorComDao := dal.NewOPCMonitorComRuleDAO(session, user.PlantNr, user.UserId)
	opcMonitorDetailDao := dal.NewOPCMonitorComDetailRuleDAO(session, user.PlantNr, user.UserId)
	err = opcMonitorBasicDao.DeleteWhere([]grmi.Predicate{meta.OPCMonitorBasicComInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除工步监控动作OPC通讯基础规则失败, error:" + err.Error())
	}
	err = opcMonitorComDao.DeleteWhere([]grmi.Predicate{meta.OPCMonitorComRule_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除工步监控动作OPC通讯规则失败, error:" + err.Error())
	}
	err = opcMonitorDetailDao.DeleteWhere([]grmi.Predicate{meta.OPCMonitorComDetailRule_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除工步监控动作OPC通讯详细规则失败, error:" + err.Error())
	}
	err = dao.DeleteOne(operationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MonitorOperationService.SelectOne
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) SelectOne(user *global.User, operationId int) (*model.MonitorOperation, error) {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(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/MonitorOperationService.UpdateOne
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) UpdateOne(user *global.User, entity *model.MonitorOperation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.OperationId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if entity.PO != record.PO {
		poDao := dal.NewProcessDAO(session, user.PlantNr, user.UserId)
		process, err := poDao.SelectOne(entity.PO)
		if err != nil {
			return grmi.NewBusinessError("查询工步绑定工序失败, error:" + err.Error())
		}
		if process == nil {
			return grmi.NewBusinessError("工序不存在, PO:" + entity.PO)
		}
	}
	if entity.ProjectId != record.ProjectId {
		projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
		project, err := projectDao.SelectOne(entity.ProjectId)
		if err != nil {
			return grmi.NewBusinessError("查询车型项目ID失败, error:" + err.Error())
		}
		if project == nil {
			return grmi.NewBusinessError("车型项目不存在, 车型项目ID:" + entity.ProjectId)
		}
	}
	if entity.StepType != record.StepType {
		stepTypeDao := dal.NewStepTypeDAO(session, user.PlantNr, user.UserId)
		stepType, err := stepTypeDao.SelectOne(entity.StepType)
		if err != nil {
			return grmi.NewBusinessError("查询操作类型失败, error:" + err.Error())
		}
		if stepType == nil {
			return grmi.NewBusinessError("操作类型不存在, 操作类型:" + entity.StepType)
		}
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if entity.PO != record.PO || entity.StepNo != record.StepNo || entity.StepDesc != record.StepDesc || entity.ProjectId != record.ProjectId {
		basicDao := dal.NewOPCMonitorBasicComInfoDAO(session, user.PlantNr, user.UserId)
		comDao := dal.NewOPCMonitorComRuleDAO(session, user.PlantNr, user.UserId)
		detailDao := dal.NewOPCMonitorComDetailRuleDAO(session, user.PlantNr, user.UserId)
		basic := model.OPCMonitorBasicComInfo{
			PO: entity.PO,
			StepNo: entity.StepNo,
			StepDesc: entity.StepDesc,
			ProjectId: entity.ProjectId,
		}
		com := model.OPCMonitorComRule{
			PO: entity.PO,
			StepNo: entity.StepNo,
			StepDesc: entity.StepDesc,
			ProjectId: entity.ProjectId,
		}
		detail := model.OPCMonitorComDetailRule{
			PO: entity.PO,
			StepNo: entity.StepNo,
			StepDesc: entity.StepDesc,
			ProjectId: entity.ProjectId,
		}
		err = basicDao.UpdateWhere([]grmi.Predicate{meta.OPCMonitorBasicComInfo_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &basic, meta.OPCMonitorBasicComInfo_PO.ColumnName, meta.OPCMonitorBasicComInfo_StepDesc.ColumnName, meta.OPCMonitorBasicComInfo_StepNo.ColumnName, meta.OPCMonitorBasicComInfo_ProjectId.ColumnName)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("更新监控工步的OPC通讯基础规则失败, error:" + err.Error())
		}
		err = comDao.UpdateWhere([]grmi.Predicate{meta.OPCMonitorComRule_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &com, meta.OPCMonitorComRule_PO.ColumnName, meta.OPCMonitorComRule_StepDesc.ColumnName, meta.OPCMonitorComRule_StepNo.ColumnName, meta.OPCMonitorComRule_ProjectId.ColumnName)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("更新监控工步的OPC通讯规则失败, error:" + err.Error())
		}
		err = detailDao.UpdateWhere([]grmi.Predicate{meta.OPCMonitorComDetailRule_OperationId.NewPredicate(grmi.Equal, entity.OperationId)}, &detail, meta.OPCMonitorComDetailRule_PO.ColumnName, meta.OPCMonitorComDetailRule_StepDesc.ColumnName, meta.OPCMonitorComDetailRule_StepNo.ColumnName, meta.OPCMonitorComDetailRule_ProjectId.ColumnName)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("更新监控工步的OPC通讯详细规则失败, error:" + err.Error())
		}

	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MonitorOperationService.Insert
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) Insert(user *global.User, entities *[]model.MonitorOperation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(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/MonitorOperationService.Delete
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) Delete(user *global.User, entities *[]model.MonitorOperation) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(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/MonitorOperationService.Select
 *
 ******************************************************************************/
func (impl *MonitorOperationServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.MonitorOperation, error) {

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

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

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

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMonitorOperationDAO(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
}
