// 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              : MaterialFrameInfo的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-19 16:19:33
 *
 ******************************************************************************/
var DefaultConditionOfMaterialFrameInfo = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.MaterialFrameInfo_WorkPlaceNr.UrlParameterName:        grmi.NewConditionItem(meta.MaterialFrameInfo_WorkPlaceNr, grmi.Equal, true),
		meta.MaterialFrameInfo_WorkPlaceDesc.UrlParameterName:      grmi.NewConditionItem(meta.MaterialFrameInfo_WorkPlaceDesc, grmi.Equal, true),
		meta.MaterialFrameInfo_GatewayIP.UrlParameterName:          grmi.NewConditionItem(meta.MaterialFrameInfo_GatewayIP, grmi.Equal, true),
		meta.MaterialFrameInfo_LampAddress.UrlParameterName:        grmi.NewConditionItem(meta.MaterialFrameInfo_LampAddress, grmi.Equal, true),
		meta.MaterialFrameInfo_FrameID.UrlParameterName:            grmi.NewConditionItem(meta.MaterialFrameInfo_FrameID, grmi.Equal, true),
		meta.MaterialFrameInfo_LevelID.UrlParameterName:            grmi.NewConditionItem(meta.MaterialFrameInfo_LevelID, grmi.Equal, true),
		meta.MaterialFrameInfo_BoxID.UrlParameterName:              grmi.NewConditionItem(meta.MaterialFrameInfo_BoxID, grmi.Equal, true),
		meta.MaterialFrameInfo_TagAddr.UrlParameterName:            grmi.NewConditionItem(meta.MaterialFrameInfo_TagAddr, grmi.Equal, true),
		meta.MaterialFrameInfo_ArtID.UrlParameterName:              grmi.NewConditionItem(meta.MaterialFrameInfo_ArtID, grmi.Equal, true),
		meta.MaterialFrameInfo_CustArtID.UrlParameterName:          grmi.NewConditionItem(meta.MaterialFrameInfo_CustArtID, grmi.Equal, true),
		meta.MaterialFrameInfo_DescCN.UrlParameterName:             grmi.NewConditionItem(meta.MaterialFrameInfo_DescCN, grmi.Equal, true),
		meta.MaterialFrameInfo_StandardPack.UrlParameterName:       grmi.NewConditionItem(meta.MaterialFrameInfo_StandardPack, grmi.Equal, true),
		meta.MaterialFrameInfo_FullLoadNum.UrlParameterName:        grmi.NewConditionItem(meta.MaterialFrameInfo_FullLoadNum, grmi.Equal, false),
		meta.MaterialFrameInfo_InitialNum.UrlParameterName:         grmi.NewConditionItem(meta.MaterialFrameInfo_InitialNum, grmi.Equal, false),
		meta.MaterialFrameInfo_AlreadyPicked.UrlParameterName:      grmi.NewConditionItem(meta.MaterialFrameInfo_AlreadyPicked, grmi.Equal, false),
		meta.MaterialFrameInfo_LastCallSystime.UrlParameterName:    grmi.NewConditionItem(meta.MaterialFrameInfo_LastCallSystime, grmi.Approximate, false),
		meta.MaterialFrameInfo_LastRespondSystime.UrlParameterName: grmi.NewConditionItem(meta.MaterialFrameInfo_LastRespondSystime, grmi.Approximate, false),
		meta.MaterialFrameInfo_AGVStatusFlag.UrlParameterName:      grmi.NewConditionItem(meta.MaterialFrameInfo_AGVStatusFlag, grmi.Equal, false),
		meta.MaterialFrameInfo_LastModify.UrlParameterName:         grmi.NewConditionItem(meta.MaterialFrameInfo_LastModify, grmi.Approximate, false),
		meta.MaterialFrameInfo_LastUser.UrlParameterName:           grmi.NewConditionItem(meta.MaterialFrameInfo_LastUser, grmi.Equal, false),
		meta.MaterialFrameInfo_CreateTime.UrlParameterName:         grmi.NewConditionItem(meta.MaterialFrameInfo_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : MaterialFrameInfo的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-19 16:19:33
 *
 ******************************************************************************/
var DefaultConditionOfMaterialFrameInfoAndPaging = grmi.NewCondition(
	DefaultConditionOfMaterialFrameInfo.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : MaterialFrameInfoServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : MaterialFrameInfo的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-19 16:19:33
 *
 ******************************************************************************/
type MaterialFrameInfoServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewMaterialFrameInfoDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个MaterialFrameInfoDAOImplement实例
 *
 * @Return Value             : MaterialFrameInfoDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-11-19 16:19:33
 *
 ******************************************************************************/
func NewMaterialFrameInfoServiceImplement() *MaterialFrameInfoServiceImplement {
	return &MaterialFrameInfoServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.InsertOne
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) InsertOne(user *global.User, entity *model.MaterialFrameInfo) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.WorkPlaceNr, entity.WorkPlaceDesc, entity.GatewayIP, entity.LampAddress, entity.FrameID, entity.LevelID, entity.BoxID, entity.TagAddr, entity.ArtID, entity.CustArtID, entity.DescCN, entity.StandardPack)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.DeleteOne
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) DeleteOne(user *global.User, workPlaceNr int, workPlaceDesc string, gatewayIP string, lampAddress string, frameID int, levelID int, boxID int, tagAddr string, artID string, custArtID string, descCN string, standardPack int) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(workPlaceNr, workPlaceDesc, gatewayIP, lampAddress, frameID, levelID, boxID, tagAddr, artID, custArtID, descCN, standardPack)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(workPlaceNr, workPlaceDesc, gatewayIP, lampAddress, frameID, levelID, boxID, tagAddr, artID, custArtID, descCN, standardPack)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.SelectOne
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) SelectOne(user *global.User, workPlaceNr int, workPlaceDesc string, gatewayIP string, lampAddress string, frameID int, levelID int, boxID int, tagAddr string, artID string, custArtID string, descCN string, standardPack int) (*model.MaterialFrameInfo, error) {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(workPlaceNr, workPlaceDesc, gatewayIP, lampAddress, frameID, levelID, boxID, tagAddr, artID, custArtID, descCN, standardPack)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.UpdateOne
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) UpdateOne(user *global.User, entity *model.MaterialFrameInfo) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	recordLi, err := dao.Select([]grmi.Predicate{meta.MaterialFrameInfo_WorkPlaceNr.NewPredicate(grmi.Equal, entity.WorkPlaceNr),
		meta.MaterialFrameInfo_FrameID.NewPredicate(grmi.Equal, entity.FrameID),
		meta.MaterialFrameInfo_LevelID.NewPredicate(grmi.Equal, entity.LevelID),
		meta.MaterialFrameInfo_BoxID.NewPredicate(grmi.Equal, entity.BoxID)}, nil)
	if err != nil {
		return grmi.NewBusinessError("查询原数据失败, error:" + err.Error())
	}
	if len(recordLi) == 0 {
		return grmi.NewBusinessError("不存在该位置的数据")
	}
	if len(recordLi) > 1 {
		return grmi.NewBusinessError("该位置存在多条数据")
	}
	record := recordLi[0]
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	err = dao.DeleteOne(record.WorkPlaceNr, record.WorkPlaceDesc, record.GatewayIP, record.LampAddress, record.FrameID, record.LevelID, record.BoxID, record.TagAddr, record.ArtID, record.CustArtID, record.DescCN, record.StandardPack)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除原有数据失败, error:" + err.Error())
	}
	if entity.ArtID != "" {
		articleDao := dal.NewArticleDAO(session, user.PlantNr, user.UserId)
		articleLi, err := articleDao.Select([]grmi.Predicate{meta.Article_ArtId.NewPredicate(grmi.Equal, entity.ArtID)}, nil)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
		}
		if len(articleLi) == 0 {
			_ = session.Rollback()
			return grmi.NewBusinessError("绑定的物料不存在, 物料ID:" + entity.ArtID)
		}
		article := articleLi[0]
		if !article.PickingToggle {
			_ = session.Rollback()
			return grmi.NewBusinessError("绑定的物料不是拣选物料, 物料ID:" + entity.ArtID)
		}

	}
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.Insert
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) Insert(user *global.User, entities *[]model.MaterialFrameInfo) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkPlaceNr, entity.WorkPlaceDesc, entity.GatewayIP, entity.LampAddress, entity.FrameID, entity.LevelID, entity.BoxID, entity.TagAddr, entity.ArtID, entity.CustArtID, entity.DescCN, entity.StandardPack)
		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/MaterialFrameInfoService.Delete
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) Delete(user *global.User, entities *[]model.MaterialFrameInfo) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkPlaceNr, entity.WorkPlaceDesc, entity.GatewayIP, entity.LampAddress, entity.FrameID, entity.LevelID, entity.BoxID, entity.TagAddr, entity.ArtID, entity.CustArtID, entity.DescCN, entity.StandardPack)
		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/MaterialFrameInfoService.Select
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.MaterialFrameInfo, error) {

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

	condition := DefaultConditionOfMaterialFrameInfoAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	orderBy := []grmi.Field{meta.MaterialFrameInfo_FrameID, meta.MaterialFrameInfo_LevelID, meta.MaterialFrameInfo_BoxID}
	result, err := dao.Select(predicates, orderBy)
	if err != nil {
		return nil, err
	}
	return result, nil
}

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

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

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

	grmi.Log(user, "/services/base/implments/MaterialFrameInfo.service.impl.go", "UpdateMaterialFrameInfo", "修改多个MaterialFrameInfo")
	if len(*entities) != 6*4*4 {
		return grmi.NewBusinessError("数据条数错误")
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	workPlaceDao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	var workPlaceNr int
	var lampAddress string
	var gatewayIp string
	for _, entity := range *entities {
		if workPlaceNr == 0 {
			workPlaceNr = entity.WorkPlaceNr
			workPlace, err := workPlaceDao.SelectOne(workPlaceNr)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("查询工位数据失败, error:" + err.Error())
			}
			if workPlace == nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("工位不存在")
			}
			if workPlace.FunctionType != model.FUNTION_TYPE_PICKING {
				_ = session.Rollback()
				return grmi.NewBusinessError("工位不是拣选工位")
			}
		}
		if workPlaceNr != entity.WorkPlaceNr {
			_ = session.Rollback()
			return grmi.NewBusinessError("工位ID不一致")
		}
		if lampAddress == "" {
			lampAddress = entity.LampAddress
		}
		if lampAddress != entity.LampAddress {
			_ = session.Rollback()
			return grmi.NewBusinessError("巷道灯地址不一致")
		}
		if gatewayIp == "" {
			gatewayIp = entity.GatewayIP
		}
		if gatewayIp != entity.GatewayIP {
			_ = session.Rollback()
			return grmi.NewBusinessError("控制器IP")
		}
	}
	err := dao.DeleteWhere([]grmi.Predicate{meta.MaterialFrameInfo_WorkPlaceNr.NewPredicate(grmi.Equal, workPlaceNr)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除原有数据失败, error:" + err.Error())
	}
	tempLi := make([]model.MaterialFrameInfo, 0, 20)
	for index, data := range *entities {
		if index != 0 && index%20 == 0 {
			err := dao.Insert(&tempLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入工位拣选配置数据失败, error:" + err.Error())
			}
			tempLi = make([]model.MaterialFrameInfo, 0, 20)
		}
		tempLi = append(tempLi, data)
	}
	if len(tempLi) != 0 {
		err := dao.Insert(&tempLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("插入工位拣选配置数据失败, error:" + err.Error())
		}
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/MaterialFrameInfoService.UpdateInfo
 *
 ******************************************************************************/
func (impl *MaterialFrameInfoServiceImplement) UpdateInfo(user *global.User, entity *model.MaterialFrameInfo) error {
	grmi.Log(user, "/services/base/implments/MaterialFrameInfo.service.impl.go", "UpdateInfo", "修改头部信息")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
	updateData := model.MaterialFrameInfo{
		GatewayIP:   entity.GatewayIP,
		LampAddress: entity.LampAddress,
	}
	err := dao.UpdateInfo(entity.WorkPlaceNr, &updateData)
	return err
}
