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

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	meDal "LAPP_ACURA_MOM_BACKEND/dao/me"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	meMeta "LAPP_ACURA_MOM_BACKEND/meta/me"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : Plant的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
var DefaultConditionOfPlant = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Plant_PlantNr.UrlParameterName:        grmi.NewConditionItem(meta.Plant_PlantNr, grmi.Equal, true),
		meta.Plant_Status.UrlParameterName:         grmi.NewConditionItem(meta.Plant_Status, grmi.Equal, false),
		meta.Plant_Name1.UrlParameterName:          grmi.NewConditionItem(meta.Plant_Name1, grmi.Equal, false),
		meta.Plant_Name2.UrlParameterName:          grmi.NewConditionItem(meta.Plant_Name2, grmi.Equal, false),
		meta.Plant_Logo.UrlParameterName:           grmi.NewConditionItem(meta.Plant_Logo, grmi.Equal, false),
		meta.Plant_Abrevname.UrlParameterName:      grmi.NewConditionItem(meta.Plant_Abrevname, grmi.Equal, false),
		meta.Plant_Country.UrlParameterName:        grmi.NewConditionItem(meta.Plant_Country, grmi.Equal, false),
		meta.Plant_Street.UrlParameterName:         grmi.NewConditionItem(meta.Plant_Street, grmi.Equal, false),
		meta.Plant_Address.UrlParameterName:        grmi.NewConditionItem(meta.Plant_Address, grmi.Equal, false),
		meta.Plant_PostCode.UrlParameterName:       grmi.NewConditionItem(meta.Plant_PostCode, grmi.Equal, false),
		meta.Plant_Phone.UrlParameterName:          grmi.NewConditionItem(meta.Plant_Phone, grmi.Equal, false),
		meta.Plant_Fax.UrlParameterName:            grmi.NewConditionItem(meta.Plant_Fax, grmi.Equal, false),
		meta.Plant_StartYear.UrlParameterName:      grmi.NewConditionItem(meta.Plant_StartYear, grmi.Equal, false),
		meta.Plant_EndYear.UrlParameterName:        grmi.NewConditionItem(meta.Plant_EndYear, grmi.Equal, false),
		meta.Plant_CompanyTitle.UrlParameterName:   grmi.NewConditionItem(meta.Plant_CompanyTitle, grmi.Equal, false),
		meta.Plant_CompanyAddress.UrlParameterName: grmi.NewConditionItem(meta.Plant_CompanyAddress, grmi.Equal, false),
		meta.Plant_TaxId.UrlParameterName:          grmi.NewConditionItem(meta.Plant_TaxId, grmi.Equal, false),
		meta.Plant_AccountBank.UrlParameterName:    grmi.NewConditionItem(meta.Plant_AccountBank, grmi.Equal, false),
		meta.Plant_AccountNr.UrlParameterName:      grmi.NewConditionItem(meta.Plant_AccountNr, grmi.Equal, false),
		meta.Plant_Currency.UrlParameterName:       grmi.NewConditionItem(meta.Plant_Currency, grmi.Equal, false),
		meta.Plant_PlantProject.UrlParameterName:   grmi.NewConditionItem(meta.Plant_PlantProject, grmi.Equal, false),
		meta.Plant_LastModify.UrlParameterName:     grmi.NewConditionItem(meta.Plant_LastModify, grmi.Approximate, false),
		meta.Plant_LastUser.UrlParameterName:       grmi.NewConditionItem(meta.Plant_LastUser, grmi.Equal, false),
		meta.Plant_CreateTime.UrlParameterName:     grmi.NewConditionItem(meta.Plant_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Plant的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
var DefaultConditionOfPlantAndPaging = grmi.NewCondition(
	DefaultConditionOfPlant.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : PlantServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Plant的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
type PlantServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewPlantDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个PlantDAOImplement实例
 *
 * @Return Value             : PlantDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
func NewPlantServiceImplement() *PlantServiceImplement {
	return &PlantServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.InsertOne
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) InsertOne(user *global.User, entity *model.Plant) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPlantDAO(session, user.UserId)
	record, err := dao.SelectOne(entity.PlantNr)
	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/PlantService.DeleteOne
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) DeleteOne(user *global.User, plantNr int) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.SelectOne
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) SelectOne(user *global.User, plantNr int) (*model.Plant, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.UpdateOne
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) UpdateOne(user *global.User, entity *model.Plant) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.Insert
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) Insert(user *global.User, entities *[]model.Plant) error {

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

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

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

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

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

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

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

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

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

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

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.PlantNr)
		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/PlantService.GetPlants
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) GetPlants() ([]model.Plant, error) {

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPlantDAO(session, "sys")

	plants, err := dao.GetPlants()
	if err != nil {
		return plants, err
	}
	return plants, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.GetAllProjectsOfPlant
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) GetAllProjectsOfPlant(user *global.User) ([]model.PlantDataTree, error) {
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPlantDAO(session, user.UserId)
	projectDao := meDal.NewProjectDAO(session, user.PlantNr, user.UserId)
	productFamilyDao := meDal.NewProductFamilyDAO(session, user.PlantNr, user.UserId)
	productFamilyRelateDao := meDal.NewProductFamilyRelateDAO(session, user.PlantNr, user.UserId)
	plantLi, err := dao.Select(nil, []grmi.Field{meta.Plant_PlantNr})
	if err != nil {
		return nil, grmi.NewBusinessError("查询工厂数据失败, error:" + err.Error())
	}
	if len(plantLi) == 0 {
		return nil, grmi.NewBusinessError("不存在工厂数据")
	}
	result := make([]model.PlantDataTree, 0, 1)
	for _, plant := range plantLi {
		plantData := model.PlantDataTree{
			ItemId:   strconv.Itoa(plant.PlantNr),
			ItemDesc: plant.Name1,
		}
		projectLi, err := projectDao.Select([]grmi.Predicate{meMeta.Project_PlantNr.NewPredicate(grmi.Equal, plant.PlantNr)}, []grmi.Field{meMeta.Project_ProjectId})
		if err != nil {
			return nil, grmi.NewBusinessError("查询车型项目数据失败, error:" + err.Error() + " 工厂ID: " + strconv.Itoa(plant.PlantNr))
		}
		projectDataLi := make([]model.PlantDataTree, 0, len(projectLi))
		for _, project := range projectLi {
			projectData := model.PlantDataTree{
				ItemId:   project.ProjectId,
				ItemDesc: project.Descr,
			}
			productFamilyLi, err := productFamilyDao.Select([]grmi.Predicate{meMeta.ProductFamily_ProjectId.NewPredicate(grmi.Equal, project.ProjectId)}, []grmi.Field{meMeta.ProductFamily_ProductFamilyId})
			if err != nil {
				return nil, grmi.NewBusinessError("查询车型配置数据失败, error:" + err.Error() + " 工厂ID:" + strconv.Itoa(plant.PlantNr))
			}
			productFamilyDataLi := make([]model.PlantDataTree, 0, len(productFamilyLi))
			for _, productFamily := range productFamilyLi {
				productFamilyData := model.PlantDataTree{
					ItemId:   productFamily.ProductFamilyId,
					ItemDesc: productFamily.Descr,
				}
				productLi, err := productFamilyRelateDao.SelectProductByFamilyId(project.ProjectId, productFamily.ProductFamilyId)
				if err != nil {
					return nil, grmi.NewBusinessError("查询产品数据失败, error:" + err.Error() + " 工厂ID:" + strconv.Itoa(plant.PlantNr))
				}
				productDataLi := make([]model.PlantDataTree, 0, len(productLi))
				for _, product := range productLi {
					productData := model.PlantDataTree{
						ItemId:   product.ProductId,
						ItemDesc: product.Descr,
						IsEnd:    true,
					}
					productDataLi = append(productDataLi, productData)
				}
				productFamilyData.Children = productDataLi
				productFamilyDataLi = append(productFamilyDataLi, productFamilyData)
			}
			projectData.Children = productFamilyDataLi
			projectDataLi = append(projectDataLi, projectData)
		}
		plantData.Children = projectDataLi
		result = append(result, plantData)
	}
	return result, nil

}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PlantService.GetAllWorkLineOfPlant
 *
 ******************************************************************************/
func (impl *PlantServiceImplement) GetAllWorkLineOfPlant(user *global.User) ([]model.WorkLineOfPlant, error) {
	grmi.Log(user, "/services/base/implments/Plant.service.impl.go", "GetAllWorkLineOfPlant", "获取所有工厂及工厂下的产线")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPlantDAO(session, user.UserId)
	plantLi, err := dao.Select(nil, []grmi.Field{meta.Plant_PlantNr})
	if err != nil {
		return nil, grmi.NewBusinessError("查询工厂数据失败, error:" + err.Error())
	}
	result := make([]model.WorkLineOfPlant, 0, 1)
	for _, plant := range plantLi {
		plantData := model.WorkLineOfPlant{
			ItemId:   plant.PlantNr,
			ItemDesc: plant.Name1,
			Children: make([]model.WorkLineOfPlant, 0),
		}
		workLineDao := dal.NewWorkLineDAO(session, plant.PlantNr, user.UserId)
		workLineLi, err := workLineDao.Select(nil, []grmi.Field{meta.WorkLine_WorkLineid})
		if err != nil {
			return nil, grmi.NewBusinessError("查询产线数据失败, error:" + err.Error())
		}
		for _, workLine := range workLineLi {
			data := model.WorkLineOfPlant{
				ItemId:   workLine.WorkLineid,
				ItemDesc: workLine.Descr,
				IsEnd:    true,
			}
			plantData.Children = append(plantData.Children, data)
		}
		result = append(result, plantData)
	}
	return result, nil
}
