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

package implments

import (
	baseDal "LAPP_ACURA_MOM_BACKEND/dao/base"
	dal "LAPP_ACURA_MOM_BACKEND/dao/pm"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/pm"
	model "LAPP_ACURA_MOM_BACKEND/models/pm"
	"LAPP_ACURA_MOM_BACKEND/utils"
)

/******************************************************************************
 *
 * @Description              : Location的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
var DefaultConditionOfLocation = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Location_LocaNr.UrlParameterName:     grmi.NewConditionItem(meta.Location_LocaNr, grmi.Equal, true),
		meta.Location_LocaName.UrlParameterName:   grmi.NewConditionItem(meta.Location_LocaName, grmi.Equal, false),
		meta.Location_LocaPara1.UrlParameterName:  grmi.NewConditionItem(meta.Location_LocaPara1, grmi.Equal, false),
		meta.Location_LocaPara2.UrlParameterName:  grmi.NewConditionItem(meta.Location_LocaPara2, grmi.Equal, false),
		meta.Location_LocaPara3.UrlParameterName:  grmi.NewConditionItem(meta.Location_LocaPara3, grmi.Equal, false),
		meta.Location_LocaPara4.UrlParameterName:  grmi.NewConditionItem(meta.Location_LocaPara4, grmi.Equal, false),
		meta.Location_LastModify.UrlParameterName: grmi.NewConditionItem(meta.Location_LastModify, grmi.Approximate, false),
		meta.Location_LastUser.UrlParameterName:   grmi.NewConditionItem(meta.Location_LastUser, grmi.Equal, false),
		meta.Location_CreateTime.UrlParameterName: grmi.NewConditionItem(meta.Location_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Location的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
var DefaultConditionOfLocationAndPaging = grmi.NewCondition(
	DefaultConditionOfLocation.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : LocationServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Location的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
type LocationServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewLocationDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个LocationDAOImplement实例
 *
 * @Return Value             : LocationDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
func NewLocationServiceImplement() *LocationServiceImplement {
	return &LocationServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/LocationService.InsertOne
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) InsertOne(user *global.User, entity *model.Location) error {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "InsertOneLocation", "插入一个Location")

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

	snrDao := baseDal.NewSnrDAO(session, user.PlantNr, user.UserId)
	Locationid, err := snrDao.GetNextSnr("Locationid")
	if err != nil {
		return err
	}
	entity.LocaNr = utils.ValueToInt(Locationid,0)

	record, err := dao.SelectOne(entity.LocaNr)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	var Assetids []int
	for _, v := range entity.Valst {
		Assetids = append(Assetids, v.AssetNr)
	}
	if !utils.ValueIsEmpty(Assetids) {
		//批量更新
		_, err = session.Table("PM_ASSET").In("AssetNr", Assetids).Where("PlantNr = ?", entity.PlantNr).Update(map[string]interface{}{"LocaNr": entity.LocaNr})
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/LocationService.DeleteOne
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) DeleteOne(user *global.User, locaNr int) error {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "DeleteOneLocation", "删除一个Location")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewLocationDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(locaNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(locaNr)
	if err != nil {
		return err
	}
	//批量更新
	_, err = session.Table("PM_ASSET").Where("PlantNr = ? and LocaNr = ? ", user.PlantNr,locaNr).Update(map[string]interface{}{"LocaNr": 0})
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/LocationService.SelectOne
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) SelectOne(user *global.User, locaNr int) (*model.Location, error) {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "SelectOneLocation", "查询一个Location")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewLocationDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(locaNr)
	if err != nil {
		return nil, err
	}
	var valst []model.Asset
	err = session.Table("Pm_Asset").Where("PlantNr = ? and LocaNr = ?", user.PlantNr, locaNr).Find(&valst)
	if err != nil {
		return result, err
	}
	var uvalst []model.Asset
	err = session.Table("Pm_Asset").Where("PlantNr = ? and (LocaNr =0 or LocaNr = null)", user.PlantNr).Find(&uvalst)
	if err != nil {
		return result, err
	}
	if result!=nil{
		result.Valst = valst
		result.UnValst = uvalst
	}

	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/LocationService.UpdateOne
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) UpdateOne(user *global.User, entity *model.Location) error {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "UpdateOneLocation", "修改一个Location")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewLocationDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.LocaNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	var Assetids []int
	for _, v := range entity.Valst {
		Assetids = append(Assetids, v.AssetNr)
	}
	if !utils.ValueIsEmpty(Assetids) {
		//批量更新
		_, err = session.Table("PM_ASSET").In("AssetNr", Assetids).Where("PlantNr = ?", entity.PlantNr).Update(map[string]interface{}{"LocaNr": entity.LocaNr})
		if err != nil {
			return err
		}
	}
	var NAssetids []int
	for _, v := range entity.UnValst {
		NAssetids = append(NAssetids, v.AssetNr)
	}
	if !utils.ValueIsEmpty(NAssetids) {
		//批量更新
		_, err = session.Table("PM_ASSET").In("AssetNr", NAssetids).Where("PlantNr = ?", entity.PlantNr).Update(map[string]interface{}{"LocaNr": 0})
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/LocationService.Insert
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) Insert(user *global.User, entities *[]model.Location) error {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "InsertLocation", "插入多个Location")

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

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

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "DeleteLocation", "删除多个Location")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.LocaNr)
		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/pm/LocationService.Select
 *
 ******************************************************************************/
func (impl *LocationServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.Location, error) {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "SelectLocation", "查询Location")

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

func (impl *LocationServiceImplement) SelectAll(user *global.User, urlParameters map[string]string) ([]model.Asset, error) {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "SelectAll", "SelectAll")
	e := db.Eloquent.Master()
	var data []model.Asset
	err := e.Table("Pm_Asset").Where("PlantNr = ? and (LocaNr =0 or LocaNr = null)", user.PlantNr).Find(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

func (impl *LocationServiceImplement) SelectArr(user *global.User, urlParameters map[string]string) ([]model.Location, error) {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "SelectArr", "SelectArr")

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

func (impl *LocationServiceImplement) GetMenuLocation(user *global.User, urlParameters map[string]string) ([]model.TreePmLocation, error) {

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "GetMenuLocation", "GetMenuLocation")

	m := make([]model.TreePmLocation, 0)
	data := make([]model.LocationAsset, 0)
	e := db.Eloquent.Master()
	err := e.Table("Pm_Location").Join("left", "Pm_Asset", "Pm_Asset.PlantNr=Pm_Location.PlantNr and Pm_Asset.LocaNr=Pm_Location.LocaNr").Where("Pm_Location.PlantNr = ? ", user.PlantNr).Find(&data)
	if err != nil {
		return m, err
	}
	tem := make(map[int]interface{})
	for i := 0; i < len(data); i++ {
		key := data[i].Location.LocaNr
		if utils.ValueIsEmpty(key) {
			continue
		}
		_, ok := tem[key]
		if ok {
			continue
		} else {
			tem[key] = data[i].Location
		}
		val := model.TreePmLocation{}
		val.Locaid = data[i].Location.LocaNr
		val.Locaname = data[i].Location.LocaName
		menusInfo :=  data[i].DiguiLocation(&data, val)

		m = append(m, menusInfo)
	}
	return m, nil
}

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

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "SelectLocation", "查询Location")

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

	grmi.Log(user, "/services/pm/implments/Location.service.impl.go", "UpdateLocation", "修改多个Location")

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

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

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