// 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              : WorkPlace的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
var DefaultConditionOfWorkPlace = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.WorkPlace_WorkPlaceNr.UrlParameterName:       grmi.NewConditionItem(meta.WorkPlace_WorkPlaceNr, grmi.Equal, true),
		meta.WorkPlace_WorkPlaceId.UrlParameterName:       grmi.NewConditionItem(meta.WorkPlace_WorkPlaceId, grmi.Equal, false),
		meta.WorkPlace_Descr.UrlParameterName:             grmi.NewConditionItem(meta.WorkPlace_Descr, grmi.Equal, false),
		meta.WorkPlace_WorkPlaceGrpNr.UrlParameterName:    grmi.NewConditionItem(meta.WorkPlace_WorkPlaceGrpNr, grmi.Equal, false),
		meta.WorkPlace_WorkPlaceType.UrlParameterName:     grmi.NewConditionItem(meta.WorkPlace_WorkPlaceType, grmi.Equal, false),
		meta.WorkPlace_CapacityType.UrlParameterName:      grmi.NewConditionItem(meta.WorkPlace_CapacityType, grmi.Equal, false),
		meta.WorkPlace_CapacityFactor.UrlParameterName:    grmi.NewConditionItem(meta.WorkPlace_CapacityFactor, grmi.Equal, false),
		meta.WorkPlace_PlanEfficiency.UrlParameterName:    grmi.NewConditionItem(meta.WorkPlace_PlanEfficiency, grmi.Equal, false),
		meta.WorkPlace_CostRate.UrlParameterName:          grmi.NewConditionItem(meta.WorkPlace_CostRate, grmi.Equal, false),
		meta.WorkPlace_WeekModelNr.UrlParameterName:       grmi.NewConditionItem(meta.WorkPlace_WeekModelNr, grmi.Equal, false),
		meta.WorkPlace_WorkCalendarNr.UrlParameterName:    grmi.NewConditionItem(meta.WorkPlace_WorkCalendarNr, grmi.Equal, false),
		meta.WorkPlace_CostCenterId.UrlParameterName:      grmi.NewConditionItem(meta.WorkPlace_CostCenterId, grmi.Equal, false),
		meta.WorkPlace_LocationId.UrlParameterName:        grmi.NewConditionItem(meta.WorkPlace_LocationId, grmi.Equal, false),
		meta.WorkPlace_RequireSkillRank1.UrlParameterName: grmi.NewConditionItem(meta.WorkPlace_RequireSkillRank1, grmi.Equal, false),
		meta.WorkPlace_RequireSkillRank2.UrlParameterName: grmi.NewConditionItem(meta.WorkPlace_RequireSkillRank2, grmi.Equal, false),
		meta.WorkPlace_RequireSkillRank3.UrlParameterName: grmi.NewConditionItem(meta.WorkPlace_RequireSkillRank3, grmi.Equal, false),
		meta.WorkPlace_RequireSkillRank4.UrlParameterName: grmi.NewConditionItem(meta.WorkPlace_RequireSkillRank4, grmi.Equal, false),
		meta.WorkPlace_TriggerFrom.UrlParameterName:       grmi.NewConditionItem(meta.WorkPlace_TriggerFrom, grmi.Equal, false),
		meta.WorkPlace_TriggerDependOn.UrlParameterName:   grmi.NewConditionItem(meta.WorkPlace_TriggerDependOn, grmi.Equal, false),
		meta.WorkPlace_FunctionType.UrlParameterName:      grmi.NewConditionItem(meta.WorkPlace_FunctionType, grmi.Equal, false),
		meta.WorkPlace_BKFlag.UrlParameterName:            grmi.NewConditionItem(meta.WorkPlace_BKFlag, grmi.Equal, false),
		meta.WorkPlace_PrinterId.UrlParameterName:         grmi.NewConditionItem(meta.WorkPlace_PrinterId, grmi.Equal, false),
		meta.WorkPlace_LastModify.UrlParameterName:        grmi.NewConditionItem(meta.WorkPlace_LastModify, grmi.Approximate, false),
		meta.WorkPlace_LastUser.UrlParameterName:          grmi.NewConditionItem(meta.WorkPlace_LastUser, grmi.Equal, false),
		meta.WorkPlace_CreateTime.UrlParameterName:        grmi.NewConditionItem(meta.WorkPlace_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : WorkPlace的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
var DefaultConditionOfWorkPlaceAndPaging = grmi.NewCondition(
	DefaultConditionOfWorkPlace.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : WorkPlaceServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : WorkPlace的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
type WorkPlaceServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewWorkPlaceDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个WorkPlaceDAOImplement实例
 *
 * @Return Value             : WorkPlaceDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
func NewWorkPlaceServiceImplement() *WorkPlaceServiceImplement {
	return &WorkPlaceServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.InsertOne
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) InsertOne(user *global.User, entity *model.WorkPlace) error {

	grmi.Log(user, "/services/base/implments/WorkPlace.service.impl.go", "InsertOneWorkPlace", "插入一个WorkPlace")
	if entity.TriggerFrom == model.TRIGGER_FROM_BARCODE {
		entity.TriggerDependOn = model.TRIGGER_DEPEND_ON_UNITSN
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	dao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	err := dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if entity.FunctionType == model.FUNTION_TYPE_PICKING {
		materialFrameInfoDao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
		materialFrameInfoLi := make([]model.MaterialFrameInfo, 0, 6*4*4)
		for i := 1; i <= 6; i++ {
			for j := 1; j <= 4; j++ {
				for z := 1; z <= 4; z++ {
					data := model.MaterialFrameInfo{
						WorkPlaceNr:   entity.WorkPlaceNr,
						WorkPlaceDesc: entity.Descr,
						FrameID:       i,
						LevelID:       j,
						BoxID:         z,
					}
					materialFrameInfoLi = append(materialFrameInfoLi, data)
				}
			}
		}
		tempLi := make([]model.MaterialFrameInfo, 0, 20)
		for index, data := range materialFrameInfoLi {
			if index != 0 && index%20 == 0 {
				err = materialFrameInfoDao.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 = materialFrameInfoDao.Insert(&tempLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入工位拣选配置数据失败, error:" + err.Error())
			}
		}
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.DeleteOne
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) DeleteOne(user *global.User, workPlaceNr int) error {

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

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

	dao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	processWorkPlaceDao := dal.NewProcessWorkPlaceLstDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(workPlaceNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if err = session.Begin(); err != nil {
		return err
	}
	if record.FunctionType == model.FUNTION_TYPE_PICKING {
		materialFrameInfoDao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
		err = materialFrameInfoDao.DeleteWhere([]grmi.Predicate{meta.MaterialFrameInfo_WorkPlaceNr.NewPredicate(grmi.Equal, workPlaceNr)})
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("删除工位拣选配置失败, error:" + err.Error())
		}
	}
	err = processWorkPlaceDao.DeleteWhere([]grmi.Predicate{meta.ProcessWorkPlaceLst_WorkPlaceNr.NewPredicate(grmi.Equal, workPlaceNr)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除工序工位关联关系失败, error:" + err.Error())
	}
	configDao := dal.NewWorkPlaceConfigDAO(session, user.PlantNr, user.UserId)
	err = configDao.DeleteWhere([]grmi.Predicate{meta.WorkPlaceConfig_WorkPlaceNr.NewPredicate(grmi.Equal, workPlaceNr)})
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("删除工位配置失败, error:" + err.Error())
	}
	err = dao.DeleteOne(workPlaceNr)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.SelectOne
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) SelectOne(user *global.User, workPlaceNr int) (*model.WorkPlace, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.UpdateOne
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) UpdateOne(user *global.User, entity *model.WorkPlace) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.WorkPlaceNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if entity.TriggerFrom == model.TRIGGER_FROM_BARCODE {
		entity.TriggerDependOn = model.TRIGGER_DEPEND_ON_UNITSN
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败, error:" + err.Error())
	}
	if record.FunctionType == model.FUNTION_TYPE_PICKING && entity.FunctionType != model.FUNTION_TYPE_PICKING {
		materialFrameInfoDao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
		err = materialFrameInfoDao.DeleteWhere([]grmi.Predicate{meta.MaterialFrameInfo_WorkPlaceNr.NewPredicate(grmi.Equal, entity.WorkPlaceNr)})
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("删除工位拣选配置失败, error:" + err.Error())
		}
	} else if record.FunctionType != model.FUNTION_TYPE_PICKING && entity.FunctionType == model.FUNTION_TYPE_PICKING {
		materialFrameInfoDao := dal.NewMaterialFrameInfoDAO(session, user.PlantNr, user.UserId)
		materialFrameInfoLi := make([]model.MaterialFrameInfo, 0, 6*6*4)
		for i := 1; i <= 6; i++ {
			for j := 1; j <= 4; j++ {
				for z := 1; z <= 4; z++ {
					data := model.MaterialFrameInfo{
						WorkPlaceNr:   entity.WorkPlaceNr,
						WorkPlaceDesc: entity.Descr,
						FrameID:       i,
						LevelID:       j,
						BoxID:         z,
					}
					materialFrameInfoLi = append(materialFrameInfoLi, data)
				}
			}
		}
		tempLi := make([]model.MaterialFrameInfo, 0, 20)
		for index, data := range materialFrameInfoLi {
			if index != 0 && index%20 == 0 {
				err = materialFrameInfoDao.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 = materialFrameInfoDao.Insert(&tempLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("插入工位拣选配置数据失败, error:" + err.Error())
			}
		}
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.Insert
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) Insert(user *global.User, entities *[]model.WorkPlace) error {

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

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

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

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkPlaceNr)
		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/WorkPlaceService.Select
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) Select(user *global.User, urlParameters map[string]string) (interface{}, error) {

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

	condition := DefaultConditionOfWorkPlaceAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/WorkPlaceService.Update
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) Update(user *global.User, entities *[]model.WorkPlace) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkPlaceNr)
		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/WorkPlaceService.SelectByWorkLineId
 *
 ******************************************************************************/
func (impl *WorkPlaceServiceImplement) SelectByWorkLineId(user *global.User, workLineId string) ([]model.WorkPlace, error) {

	grmi.Log(user, "/services/base/implments/WorkPlace.service.impl.go", "SelectByWorkLineId", "通过workLineId查询WorkPlace")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	workPlaceLi, err := dao.SelectByWorkLineId(workLineId)
	if err != nil {
		return nil, err
	}
	return *workPlaceLi, nil
}
