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

/******************************************************************************
 *
 * @Description              : PrintBasicRuleInfo的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-12-01 11:23:29
 *
 ******************************************************************************/
var DefaultConditionOfPrintBasicRuleInfo = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.PrintBasicRuleInfo_OperationId.UrlParameterName:         grmi.NewConditionItem(meta.PrintBasicRuleInfo_OperationId, grmi.Equal, true),
		meta.PrintBasicRuleInfo_WorkPlaceNr.UrlParameterName:         grmi.NewConditionItem(meta.PrintBasicRuleInfo_WorkPlaceNr, grmi.Equal, true),
		meta.PrintBasicRuleInfo_MainCodeName.UrlParameterName:        grmi.NewConditionItem(meta.PrintBasicRuleInfo_MainCodeName, grmi.Equal, true),
		meta.PrintBasicRuleInfo_TemplateFile.UrlParameterName:        grmi.NewConditionItem(meta.PrintBasicRuleInfo_TemplateFile, grmi.Equal, true),
		meta.PrintBasicRuleInfo_PO.UrlParameterName:                  grmi.NewConditionItem(meta.PrintBasicRuleInfo_PO, grmi.Equal, false),
		meta.PrintBasicRuleInfo_StepNo.UrlParameterName:              grmi.NewConditionItem(meta.PrintBasicRuleInfo_StepNo, grmi.Equal, false),
		meta.PrintBasicRuleInfo_StepDesc.UrlParameterName:            grmi.NewConditionItem(meta.PrintBasicRuleInfo_StepDesc, grmi.Equal, false),
		meta.PrintBasicRuleInfo_ProjectId.UrlParameterName:           grmi.NewConditionItem(meta.PrintBasicRuleInfo_ProjectId, grmi.Equal, false),
		meta.PrintBasicRuleInfo_TemplateChooseModel.UrlParameterName: grmi.NewConditionItem(meta.PrintBasicRuleInfo_TemplateChooseModel, grmi.Equal, false),
		meta.PrintBasicRuleInfo_DependPO.UrlParameterName:            grmi.NewConditionItem(meta.PrintBasicRuleInfo_DependPO, grmi.Equal, false),
		meta.PrintBasicRuleInfo_DependStepNo.UrlParameterName:        grmi.NewConditionItem(meta.PrintBasicRuleInfo_DependStepNo, grmi.Equal, false),
		meta.PrintBasicRuleInfo_DependRuleId.UrlParameterName:        grmi.NewConditionItem(meta.PrintBasicRuleInfo_DependRuleId, grmi.Equal, false),
		meta.PrintBasicRuleInfo_DependValue.UrlParameterName:         grmi.NewConditionItem(meta.PrintBasicRuleInfo_DependValue, grmi.Equal, false),
		meta.PrintBasicRuleInfo_Action.UrlParameterName:              grmi.NewConditionItem(meta.PrintBasicRuleInfo_Action, grmi.Equal, false),
		meta.PrintBasicRuleInfo_WhetherCheckContent.UrlParameterName: grmi.NewConditionItem(meta.PrintBasicRuleInfo_WhetherCheckContent, grmi.Equal, false),
		meta.PrintBasicRuleInfo_PrinterId.UrlParameterName:           grmi.NewConditionItem(meta.PrintBasicRuleInfo_PrinterId, grmi.Equal, false),
		meta.PrintBasicRuleInfo_TemplateType.UrlParameterName:        grmi.NewConditionItem(meta.PrintBasicRuleInfo_TemplateType, grmi.Equal, false),
		meta.PrintBasicRuleInfo_TemplateId.UrlParameterName:          grmi.NewConditionItem(meta.PrintBasicRuleInfo_TemplateId, grmi.Equal, false),
		meta.PrintBasicRuleInfo_Qty.UrlParameterName:                 grmi.NewConditionItem(meta.PrintBasicRuleInfo_Qty, grmi.Equal, false),
		meta.PrintBasicRuleInfo_CollectScanBarcode.UrlParameterName:  grmi.NewConditionItem(meta.PrintBasicRuleInfo_CollectScanBarcode, grmi.Equal, false),
		meta.PrintBasicRuleInfo_ScanOperationId.UrlParameterName:     grmi.NewConditionItem(meta.PrintBasicRuleInfo_ScanOperationId, grmi.Equal, false),
		meta.PrintBasicRuleInfo_LabelDetailPos.UrlParameterName:      grmi.NewConditionItem(meta.PrintBasicRuleInfo_LabelDetailPos, grmi.Equal, false),
		meta.PrintBasicRuleInfo_ScanPo.UrlParameterName:              grmi.NewConditionItem(meta.PrintBasicRuleInfo_ScanPo, grmi.Equal, false),
		meta.PrintBasicRuleInfo_LastModify.UrlParameterName:          grmi.NewConditionItem(meta.PrintBasicRuleInfo_LastModify, grmi.Approximate, false),
		meta.PrintBasicRuleInfo_LastUser.UrlParameterName:            grmi.NewConditionItem(meta.PrintBasicRuleInfo_LastUser, grmi.Equal, false),
		meta.PrintBasicRuleInfo_CreateTime.UrlParameterName:          grmi.NewConditionItem(meta.PrintBasicRuleInfo_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : PrintBasicRuleInfo的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-12-01 11:23:29
 *
 ******************************************************************************/
var DefaultConditionOfPrintBasicRuleInfoAndPaging = grmi.NewCondition(
	DefaultConditionOfPrintBasicRuleInfo.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : PrintBasicRuleInfoServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : PrintBasicRuleInfo的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-12-01 11:23:29
 *
 ******************************************************************************/
type PrintBasicRuleInfoServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewPrintBasicRuleInfoDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个PrintBasicRuleInfoDAOImplement实例
 *
 * @Return Value             : PrintBasicRuleInfoDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-12-01 11:23:29
 *
 ******************************************************************************/
func NewPrintBasicRuleInfoServiceImplement() *PrintBasicRuleInfoServiceImplement {
	return &PrintBasicRuleInfoServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PrintBasicRuleInfoService.InsertOne
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) InsertOne(user *global.User, entity *model.PrintBasicRuleInfo) error {

	grmi.Log(user, "/services/base/implments/PrintBasicRuleInfo.service.impl.go", "InsertOnePrintBasicRuleInfo", "插入一个PrintBasicRuleInfo")
	if entity.Qty <= 0 {
		return grmi.NewBusinessError("打印数量小于或等于0")
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	workPlaceDao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	printerDao := dal.NewPrinterDAO(session, user.PlantNr, user.UserId)
	templateDao := dal.NewLabelTemplateHeadDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.OperationId, entity.WorkPlaceNr, entity.MainCodeName, entity.TemplateFile)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	operation, err := operationDao.SelectOne(entity.OperationId)
	if err != nil {
		return err
	}
	if operation == nil {
		return grmi.NewBusinessError("不存在对应的工步数据")
	}
	if operation.StepType != model.STEP_PRINT_RULE {
		return grmi.NewBusinessError("绑定的工步数据操作类型不是单据打印")
	}
	workPlace, err := workPlaceDao.SelectOne(entity.WorkPlaceNr)
	if err != nil {
		return grmi.NewBusinessError("查询工位数据失败, error:" + err.Error())
	}
	if workPlace == nil {
		return grmi.NewBusinessError("绑定的工位不存在, 工位ID:" + strconv.Itoa(entity.WorkPlaceNr))
	}
	printer, err := printerDao.SelectOne(entity.PrinterId)
	if err != nil {
		return grmi.NewBusinessError("查询打印机失败, error:" + err.Error())
	}
	if printer == nil {
		return grmi.NewBusinessError("绑定的打印机不存在, 打印机ID:" + entity.PrinterId)
	}
	if entity.TemplateType != model.PRINT_RULE_TEMPLATE_TYPE_LABEL {
		return grmi.NewBusinessError("暂不支持模板类型")
	} else {
		template, err := templateDao.SelectOne(entity.TemplateId)
		if err != nil {
			return grmi.NewBusinessError("查询模板失败, error:" + err.Error())
		}
		if template == nil {
			return grmi.NewBusinessError("绑定模板不存在, 模板ID:" + entity.TemplateId)
		}
	}
	//if entity.TemplateFile == "" {
	//	_ = session.Rollback()
	//	return grmi.NewBusinessError("数据不合规")
	//}
	//if entity.MainCodeName == "" {
	//	_ = session.Rollback()
	//	return grmi.NewBusinessError("数据不合规")
	//}
	entity.ProjectId = operation.ProjectId
	entity.PO = operation.PO
	entity.StepDesc = operation.StepDesc
	entity.StepNo = operation.StepNo
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PrintBasicRuleInfoService.DeleteOne
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) DeleteOne(user *global.User, operationId int, workPlaceNr int, mainCodeName string, templateFile string) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(operationId, workPlaceNr, mainCodeName, templateFile)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(operationId, workPlaceNr, mainCodeName, templateFile)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PrintBasicRuleInfoService.SelectOne
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) SelectOne(user *global.User, operationId int, workPlaceNr int, mainCodeName string, templateFile string) (*model.PrintBasicRuleInfo, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PrintBasicRuleInfoService.UpdateOne
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) UpdateOne(user *global.User, entity *model.PrintBasicRuleInfo) error {

	grmi.Log(user, "/services/base/implments/PrintBasicRuleInfo.service.impl.go", "UpdateOnePrintBasicRuleInfo", "修改一个PrintBasicRuleInfo")
	if entity.Qty <= 0 {
		return grmi.NewBusinessError("打印数量小于或等于0")
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	printerDao := dal.NewPrinterDAO(session, user.PlantNr, user.UserId)
	templateDao := dal.NewLabelTemplateHeadDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.OperationId, entity.WorkPlaceNr, entity.MainCodeName, entity.TemplateFile)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	operation, err := operationDao.SelectOne(entity.OperationId)
	if err != nil {
		return err
	}
	if operation == nil {
		return grmi.NewBusinessError("不存在对应的工步数据")
	}
	if operation.StepType != model.STEP_PRINT_RULE {
		return grmi.NewBusinessError("绑定的工步数据操作类型不是单据打印")
	}
	if entity.PrinterId != record.PrinterId {
		printer, err := printerDao.SelectOne(entity.PrinterId)
		if err != nil {
			return grmi.NewBusinessError("查询打印机失败, error:" + err.Error())
		}
		if printer == nil {
			return grmi.NewBusinessError("绑定的打印机不存在, 打印机ID:" + entity.PrinterId)
		}
	}
	if entity.TemplateId != record.TemplateId || entity.TemplateType != record.TemplateType {
		if entity.TemplateType != model.PRINT_RULE_TEMPLATE_TYPE_LABEL {
			return grmi.NewBusinessError("暂不支持模板类型")
		} else {
			template, err := templateDao.SelectOne(entity.TemplateId)
			if err != nil {
				return grmi.NewBusinessError("查询模板失败, error:" + err.Error())
			}
			if template == nil {
				return grmi.NewBusinessError("绑定模板不存在, 模板ID:" + entity.TemplateId)
			}
		}
	}
	entity.ProjectId = operation.ProjectId
	entity.PO = operation.PO
	entity.StepDesc = operation.StepDesc
	entity.StepNo = operation.StepNo
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PrintBasicRuleInfoService.Insert
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) Insert(user *global.User, entities *[]model.PrintBasicRuleInfo) error {

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

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

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

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

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

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

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

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

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

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

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.OperationId, entity.WorkPlaceNr, entity.MainCodeName, entity.TemplateFile)
		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/PrintBasicRuleInfoService.Save
 *
 ******************************************************************************/
func (impl *PrintBasicRuleInfoServiceImplement) Save(user *global.User, entity *model.PrintBasicRuleInfoData) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	operationId := entity.OperationId
	li := entity.PrintBasicRuleInfoLi
	dao := dal.NewPrintBasicRuleInfoDAO(session, user.PlantNr, user.UserId)
	operationDao := dal.NewOperationDAO(session, user.PlantNr, user.UserId)
	operation, err := operationDao.SelectOne(operationId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if operation == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在对应的工艺")
	}
	if operation.StepType != model.STEP_PRINT_RULE {
		_ = session.Rollback()
		return grmi.NewBusinessError("操作类型不符")
	}
	for index, rule := range li {
		if rule.TemplateFile == "" {
			_ = session.Rollback()
			return grmi.NewBusinessError("数据不合规")
		}
		if rule.MainCodeName == "" {
			_ = session.Rollback()
			return grmi.NewBusinessError("数据不合规")
		}
		rule.ProjectId = operation.ProjectId
		rule.PO = operation.PO
		rule.StepDesc = operation.StepDesc
		rule.StepNo = operation.StepNo
		rule.OperationId = operationId
		li[index] = rule
	}

	err = dao.DeleteWhere([]grmi.Predicate{meta.PrintBasicRuleInfo_OperationId.NewPredicate(grmi.Equal, operationId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = dao.Insert(&li)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}
