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

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/jit"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/jit"
	model "LAPP_ACURA_MOM_BACKEND/models/jit"
)

/******************************************************************************
 *
 * @Description              : ShipTemplate的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
var DefaultConditionOfShipTemplate = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ShipTemplate_ShipTemplateId.UrlParameterName:      grmi.NewConditionItem(meta.ShipTemplate_ShipTemplateId, grmi.Equal, true),
		meta.ShipTemplate_EnabledToggle.UrlParameterName:       grmi.NewConditionItem(meta.ShipTemplate_EnabledToggle, grmi.Equal, false),
		meta.ShipTemplate_DefaultCreateToggle.UrlParameterName: grmi.NewConditionItem(meta.ShipTemplate_DefaultCreateToggle, grmi.Equal, false),
		meta.ShipTemplate_Descr.UrlParameterName:               grmi.NewConditionItem(meta.ShipTemplate_Descr, grmi.Equal, false),
		meta.ShipTemplate_ProjectId.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_ProjectId, grmi.Equal, false),
		meta.ShipTemplate_ShipType.UrlParameterName:            grmi.NewConditionItem(meta.ShipTemplate_ShipType, grmi.Equal, false),
		meta.ShipTemplate_PrintQty.UrlParameterName:            grmi.NewConditionItem(meta.ShipTemplate_PrintQty, grmi.Equal, false),
		meta.ShipTemplate_PlanQty.UrlParameterName:             grmi.NewConditionItem(meta.ShipTemplate_PlanQty, grmi.Equal, false),
		meta.ShipTemplate_Orientation.UrlParameterName:         grmi.NewConditionItem(meta.ShipTemplate_Orientation, grmi.Equal, false),
		meta.ShipTemplate_PrinterId.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_PrinterId, grmi.Equal, false),
		meta.ShipTemplate_TemplateFile.UrlParameterName:        grmi.NewConditionItem(meta.ShipTemplate_TemplateFile, grmi.Equal, false),
		meta.ShipTemplate_CtrlPara1.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_CtrlPara1, grmi.Equal, false),
		meta.ShipTemplate_CtrlPara2.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_CtrlPara2, grmi.Equal, false),
		meta.ShipTemplate_CtrlStr1.UrlParameterName:            grmi.NewConditionItem(meta.ShipTemplate_CtrlStr1, grmi.Equal, false),
		meta.ShipTemplate_CtrlStr2.UrlParameterName:            grmi.NewConditionItem(meta.ShipTemplate_CtrlStr2, grmi.Equal, false),
		meta.ShipTemplate_CtrlTime1.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_CtrlTime1, grmi.Approximate, false),
		meta.ShipTemplate_CtrlTime2.UrlParameterName:           grmi.NewConditionItem(meta.ShipTemplate_CtrlTime2, grmi.Approximate, false),
		meta.ShipTemplate_LastModify.UrlParameterName:          grmi.NewConditionItem(meta.ShipTemplate_LastModify, grmi.Approximate, false),
		meta.ShipTemplate_LastUser.UrlParameterName:            grmi.NewConditionItem(meta.ShipTemplate_LastUser, grmi.Equal, false),
		meta.ShipTemplate_CreateTime.UrlParameterName:          grmi.NewConditionItem(meta.ShipTemplate_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ShipTemplate的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
var DefaultConditionOfShipTemplateAndPaging = grmi.NewCondition(
	DefaultConditionOfShipTemplate.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ShipTemplateServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ShipTemplate的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
type ShipTemplateServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewShipTemplateDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ShipTemplateDAOImplement实例
 *
 * @Return Value             : ShipTemplateDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
func NewShipTemplateServiceImplement() *ShipTemplateServiceImplement {
	return &ShipTemplateServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/jit/ShipTemplateService.InsertOne
 *
 ******************************************************************************/
func (impl *ShipTemplateServiceImplement) InsertOne(user *global.User, entity *model.ShipTemplate) error {

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "InsertOneShipTemplate", "插入一个ShipTemplate")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	itemLstLi := entity.ShipTemplateItemLstLi
	if len(itemLstLi) == 0 {
		return grmi.NewBusinessError("未创建发运模板子项")
	}
	packTemplateDao := dal.NewPackTemplateDAO(session, user.PlantNr, user.UserId)
	packTemplateMap := make(map[string]interface{})
	for index, itemLst := range itemLstLi {
		itemLst.Pos = index + 1
		itemLst.ShipTemplateId = entity.ShipTemplateId
		_, exist := packTemplateMap[itemLst.PackTemplateId]
		if !exist {
			packTemplate, err := packTemplateDao.SelectOne(itemLst.PackTemplateId)
			if err != nil {
				return grmi.NewBusinessError("查询包装模板数据失败, error:" + err.Error())
			}
			if packTemplate == nil {
				return grmi.NewBusinessError("创建发运模板子项绑定的包装模板ID不存在, 包装模板ID:" + itemLst.PackTemplateId)
			}
			if itemLst.PackTypeId != packTemplate.PackTypeId {
				return grmi.NewBusinessError("包装模板ID和包装类型ID不匹配")
			}
			packTemplateMap[itemLst.PackTemplateId] = nil
			itemLstLi[index] = itemLst
		}

	}
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewShipTemplateDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ShipTemplateId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询已存在发运模板失败, error:" + err.Error())
	}
	if record != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存发运模板数据失败, error:" + err.Error())
	}
	shipTemplateItemDao := dal.NewShipTemplateItemLstDAO(session, user.PlantNr, user.UserId)
	tempLi := make([]model.ShipTemplateItemLst, 0, 20)
	for index, itemLst := range itemLstLi {
		if len(tempLi)%20 == 0 && index != 0 {
			err = shipTemplateItemDao.Insert(&tempLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("保存发运模板子项失败, error:" + err.Error())
			}
			tempLi = make([]model.ShipTemplateItemLst, 0, 20)
		}
		tempLi = append(tempLi, itemLst)
	}
	if len(tempLi) != 0 {
		err = shipTemplateItemDao.Insert(&tempLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("保存发运模板子项失败, error:" + err.Error())
		}
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/jit/ShipTemplateService.DeleteOne
 *
 ******************************************************************************/
func (impl *ShipTemplateServiceImplement) DeleteOne(user *global.User, shipTemplateId string) error {

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "DeleteOneShipTemplate", "删除一个ShipTemplate")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewShipTemplateDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(shipTemplateId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询发运模板数据失败, error:" + err.Error())
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(shipTemplateId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除发运模板失败, error:" + err.Error())
	}
	lstDao := dal.NewShipTemplateItemLstDAO(session, user.PlantNr, user.UserId)
	err = lstDao.DeleteWhere([]grmi.Predicate{meta.ShipTemplateItemLst_ShipTemplateId.NewPredicate(grmi.Equal, shipTemplateId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除发运模板子项失败, error:" + err.Error())
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/jit/ShipTemplateService.SelectOne
 *
 ******************************************************************************/
func (impl *ShipTemplateServiceImplement) SelectOne(user *global.User, shipTemplateId string) (*model.ShipTemplate, error) {

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "SelectOneShipTemplate", "查询一个ShipTemplate")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewShipTemplateDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(shipTemplateId)
	if err != nil {
		return nil, err
	}
	lstDao := dal.NewShipTemplateItemLstDAO(session, user.PlantNr, user.UserId)
	lstLi, err := lstDao.Select([]grmi.Predicate{meta.ShipTemplateItemLst_ShipTemplateId.NewPredicate(grmi.Equal, shipTemplateId)}, []grmi.Field{meta.ShipTemplateItemLst_Pos})
	if err != nil {
		return nil, grmi.NewBusinessError("查询发运模板子项失败， error:" + err.Error())
	}
	result.ShipTemplateItemLstLi = lstLi
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/jit/ShipTemplateService.UpdateOne
 *
 ******************************************************************************/
func (impl *ShipTemplateServiceImplement) UpdateOne(user *global.User, entity *model.ShipTemplate) error {

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "UpdateOneShipTemplate", "修改一个ShipTemplate")

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

	itemLstLi := entity.ShipTemplateItemLstLi
	if len(itemLstLi) == 0 {
		return grmi.NewBusinessError("未创建发运模板子项")
	}
	packTemplateDao := dal.NewPackTemplateDAO(session, user.PlantNr, user.UserId)
	packTemplateMap := make(map[string]interface{})
	for index, itemLst := range itemLstLi {
		itemLst.Pos = index + 1
		itemLst.ShipTemplateId = entity.ShipTemplateId
		_, exist := packTemplateMap[itemLst.PackTemplateId]
		if !exist {
			packTemplate, err := packTemplateDao.SelectOne(itemLst.PackTemplateId)
			if err != nil {
				return grmi.NewBusinessError("查询包装模板数据失败, error:" + err.Error())
			}
			if packTemplate == nil {
				return grmi.NewBusinessError("创建发运模板子项绑定的包装模板ID不存在, 包装模板ID:" + itemLst.PackTemplateId)
			}
			if itemLst.PackTypeId != packTemplate.PackTypeId {
				return grmi.NewBusinessError("包装模板ID和包装类型ID不匹配")
			}
			packTemplateMap[itemLst.PackTemplateId] = nil
			itemLstLi[index] = itemLst

		}

	}
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewShipTemplateDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.ShipTemplateId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询已存在发运模板失败, error:" + err.Error())
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("保存发运模板数据失败, error:" + err.Error())
	}
	shipTemplateItemDao := dal.NewShipTemplateItemLstDAO(session, user.PlantNr, user.UserId)
	err = shipTemplateItemDao.DeleteWhere([]grmi.Predicate{meta.ShipTemplateItemLst_ShipTemplateId.NewPredicate(grmi.Equal, entity.ShipTemplateId)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除发运模板子项失败, error:" + err.Error())
	}
	tempLi := make([]model.ShipTemplateItemLst, 0, 20)
	for index, itemLst := range itemLstLi {
		if len(tempLi)%20 == 0 && index != 0 {
			err = shipTemplateItemDao.Insert(&tempLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("保存发运模板子项失败, error:" + err.Error())
			}
			tempLi = make([]model.ShipTemplateItemLst, 0, 20)
		}
		tempLi = append(tempLi, itemLst)
	}
	if len(tempLi) != 0 {
		err = shipTemplateItemDao.Insert(&tempLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("保存发运模板子项失败, error:" + err.Error())
		}
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/jit/ShipTemplateService.Insert
 *
 ******************************************************************************/
func (impl *ShipTemplateServiceImplement) Insert(user *global.User, entities *[]model.ShipTemplate) error {

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "InsertShipTemplate", "插入多个ShipTemplate")

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

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

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "DeleteShipTemplate", "删除多个ShipTemplate")

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

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

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "SelectShipTemplate", "查询ShipTemplate")

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

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "SelectShipTemplate", "查询ShipTemplate")

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

	grmi.Log(user, "/services/jit/implments/ShipTemplate.service.impl.go", "UpdateShipTemplate", "修改多个ShipTemplate")

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

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

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