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

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	"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              : WorkOrderIdentifyRule的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-30 14:27:09
 *
 ******************************************************************************/
var DefaultConditionOfWorkOrderIdentifyRule = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.WorkOrderIdentifyRule_CollerationBasis.UrlParameterName:       grmi.NewConditionItem(meta.WorkOrderIdentifyRule_CollerationBasis, grmi.Equal, true),
		meta.WorkOrderIdentifyRule_CollerationOperationId.UrlParameterName: grmi.NewConditionItem(meta.WorkOrderIdentifyRule_CollerationOperationId, grmi.Equal, true),
		meta.WorkOrderIdentifyRule_PO.UrlParameterName:                     grmi.NewConditionItem(meta.WorkOrderIdentifyRule_PO, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_OpenPlan.UrlParameterName:               grmi.NewConditionItem(meta.WorkOrderIdentifyRule_OpenPlan, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_IdentifyPlan.UrlParameterName:           grmi.NewConditionItem(meta.WorkOrderIdentifyRule_IdentifyPlan, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_CombinePlan.UrlParameterName:            grmi.NewConditionItem(meta.WorkOrderIdentifyRule_CombinePlan, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_CollerationStepDesc.UrlParameterName:    grmi.NewConditionItem(meta.WorkOrderIdentifyRule_CollerationStepDesc, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_LastModify.UrlParameterName:             grmi.NewConditionItem(meta.WorkOrderIdentifyRule_LastModify, grmi.Approximate, false),
		meta.WorkOrderIdentifyRule_LastUser.UrlParameterName:               grmi.NewConditionItem(meta.WorkOrderIdentifyRule_LastUser, grmi.Equal, false),
		meta.WorkOrderIdentifyRule_CreateTime.UrlParameterName:             grmi.NewConditionItem(meta.WorkOrderIdentifyRule_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : WorkOrderIdentifyRule的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-30 14:27:09
 *
 ******************************************************************************/
var DefaultConditionOfWorkOrderIdentifyRuleAndPaging = grmi.NewCondition(
	DefaultConditionOfWorkOrderIdentifyRule.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : WorkOrderIdentifyRuleServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : WorkOrderIdentifyRule的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-30 14:27:09
 *
 ******************************************************************************/
type WorkOrderIdentifyRuleServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewWorkOrderIdentifyRuleDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个WorkOrderIdentifyRuleDAOImplement实例
 *
 * @Return Value             : WorkOrderIdentifyRuleDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-30 14:27:09
 *
 ******************************************************************************/
func NewWorkOrderIdentifyRuleServiceImplement() *WorkOrderIdentifyRuleServiceImplement {
	return &WorkOrderIdentifyRuleServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkOrderIdentifyRuleService.InsertOne
 *
 ******************************************************************************/
func (impl *WorkOrderIdentifyRuleServiceImplement) InsertOne(user *global.User, entity *model.WorkOrderIdentifyRule) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkOrderIdentifyRuleDAO(session, user.PlantNr, user.UserId)
	detailDao := dal.NewWorkOrderIdentifyRuleDetailDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.CollerationBasis, entity.CollerationOperationId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	if entity.CollerationBasis == model.ORDER_IDENTIFY_SOURCE_MONITOR {
		operationDao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
		operation, err := operationDao.SelectOne(entity.CollerationOperationId)
		if err != nil {
			return grmi.NewBusinessError("查询监控工步失败, error:" + err.Error())
		}
		if operation == nil {
			return grmi.NewBusinessError("监控工步不存在")
		}
		entity.PO = operation.PO
		entity.CollerationStepDesc = operation.StepDesc
	} else {
		operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
		operation, err := operationDao.SelectOne(entity.CollerationOperationId)
		if err != nil {
			return grmi.NewBusinessError("查询生产工步失败, error:" + err.Error())
		}
		if operation == nil {
			return grmi.NewBusinessError("不存在该生产工步")
		}
		entity.PO = operation.PO
		entity.CollerationStepDesc = operation.StepDesc
	}
	li := entity.WorkOrderIdentifyRuleDetailLi
	for index, detail := range li {
		detail.PO = entity.PO
		detail.CollerationBasis = entity.CollerationBasis
		detail.CollerationOperationId = entity.CollerationOperationId
		li[index] = detail
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	err = detailDao.Insert(&li)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存详细规则失败, error:" + err.Error())
	}
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存规则失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkOrderIdentifyRuleService.DeleteOne
 *
 ******************************************************************************/
func (impl *WorkOrderIdentifyRuleServiceImplement) DeleteOne(user *global.User, collerationBasis string, collerationOperationId int) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkOrderIdentifyRuleDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(collerationBasis, collerationOperationId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	err = dao.DeleteOne(collerationBasis, collerationOperationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	detailDao := dal.NewWorkOrderIdentifyRuleDetailDAO(session, user.PlantNr, user.UserId)
	err = detailDao.DeleteWhere([]grmi.Predicate{meta.WorkOrderIdentifyRuleDetail_CollerationBasis.NewPredicate(grmi.Equal, collerationBasis),
		meta.WorkOrderIdentifyRuleDetail_CollerationOperationId.NewPredicate(grmi.Equal, collerationOperationId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除详细规则失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkOrderIdentifyRuleService.SelectOne
 *
 ******************************************************************************/
func (impl *WorkOrderIdentifyRuleServiceImplement) SelectOne(user *global.User, collerationBasis string, collerationOperationId int) (*model.WorkOrderIdentifyRule, error) {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkOrderIdentifyRuleDAO(session, user.PlantNr, user.UserId)
	detailDao := dal.NewWorkOrderIdentifyRuleDetailDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(collerationBasis, collerationOperationId)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return nil, nil
	}
	detailLi, err := detailDao.Select([]grmi.Predicate{meta.WorkOrderIdentifyRuleDetail_CollerationBasis.NewPredicate(grmi.Equal, collerationBasis),
	meta.WorkOrderIdentifyRuleDetail_CollerationOperationId.NewPredicate(grmi.Equal, collerationOperationId)}, []grmi.Field{meta.WorkOrderIdentifyRuleDetail_IdentifyRuleId})
	if err != nil {
		return nil, grmi.NewBusinessError("查询详细规则失败, error:" + err.Error())
	}
	result.WorkOrderIdentifyRuleDetailLi = detailLi
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkOrderIdentifyRuleService.UpdateOne
 *
 ******************************************************************************/
func (impl *WorkOrderIdentifyRuleServiceImplement) UpdateOne(user *global.User, entity *model.WorkOrderIdentifyRule) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()

	dao := dal.NewWorkOrderIdentifyRuleDAO(session, user.PlantNr, user.UserId)
	detailDao := dal.NewWorkOrderIdentifyRuleDetailDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.CollerationBasis, entity.CollerationOperationId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在的记录!")
	}
	if entity.CollerationBasis == model.ORDER_IDENTIFY_SOURCE_MONITOR {
		operationDao := dal.NewMonitorOperationDAO(session, user.PlantNr, user.UserId)
		operation, err := operationDao.SelectOne(entity.CollerationOperationId)
		if err != nil {
			return grmi.NewBusinessError("查询监控工步失败, error:" + err.Error())
		}
		if operation == nil {
			return grmi.NewBusinessError("监控工步不存在")
		}
		entity.PO = operation.PO
		entity.CollerationStepDesc = operation.StepDesc
	} else {
		operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
		operation, err := operationDao.SelectOne(entity.CollerationOperationId)
		if err != nil {
			return grmi.NewBusinessError("查询生产工步失败, error:" + err.Error())
		}
		if operation == nil {
			return grmi.NewBusinessError("不存在该生产工步")
		}
		entity.PO = operation.PO
		entity.CollerationStepDesc = operation.StepDesc
	}
	li := entity.WorkOrderIdentifyRuleDetailLi
	for index, detail := range li {
		detail.PO = entity.PO
		detail.CollerationBasis = entity.CollerationBasis
		detail.CollerationOperationId = entity.CollerationOperationId
		li[index] = detail
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	err = detailDao.DeleteWhere([]grmi.Predicate{meta.WorkOrderIdentifyRuleDetail_CollerationBasis.NewPredicate(grmi.Equal, entity.CollerationBasis),
		meta.WorkOrderIdentifyRuleDetail_CollerationOperationId.NewPredicate(grmi.Equal, entity.CollerationOperationId)})
	if err != nil {
		return grmi.NewBusinessError("删除详细规则失败, error:" + err.Error())
	}
	err = detailDao.Insert(&li)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存详细规则失败, error:" + err.Error())
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存规则失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkOrderIdentifyRuleService.Insert
 *
 ******************************************************************************/
func (impl *WorkOrderIdentifyRuleServiceImplement) Insert(user *global.User, entities *[]model.WorkOrderIdentifyRule) error {

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

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

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

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

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

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

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

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

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

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

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

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

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

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