// 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              : Service的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
var DefaultConditionOfService = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Service_MainServiceNr.UrlParameterName:        grmi.NewConditionItem(meta.Service_MainServiceNr, grmi.Equal, true),
		meta.Service_Descr.UrlParameterName:                grmi.NewConditionItem(meta.Service_Descr, grmi.Equal, false),
		meta.Service_MaintType.UrlParameterName:            grmi.NewConditionItem(meta.Service_MaintType, grmi.Equal, false),
		meta.Service_Priority.UrlParameterName:             grmi.NewConditionItem(meta.Service_Priority, grmi.Equal, false),
		meta.Service_EnabledToggle.UrlParameterName:        grmi.NewConditionItem(meta.Service_EnabledToggle, grmi.Equal, false),
		meta.Service_MaintByDateToggle.UrlParameterName:    grmi.NewConditionItem(meta.Service_MaintByDateToggle, grmi.Equal, false),
		meta.Service_DueDateInterval.UrlParameterName:      grmi.NewConditionItem(meta.Service_DueDateInterval, grmi.Equal, false),
		meta.Service_NodifyDays.UrlParameterName:           grmi.NewConditionItem(meta.Service_NodifyDays, grmi.Equal, false),
		meta.Service_DueDateOn.UrlParameterName:            grmi.NewConditionItem(meta.Service_DueDateOn, grmi.Approximate, false),
		meta.Service_MaintByHourToggle.UrlParameterName:    grmi.NewConditionItem(meta.Service_MaintByHourToggle, grmi.Equal, false),
		meta.Service_DueHourInterval.UrlParameterName:      grmi.NewConditionItem(meta.Service_DueHourInterval, grmi.Equal, false),
		meta.Service_NodifyHours.UrlParameterName:          grmi.NewConditionItem(meta.Service_NodifyHours, grmi.Equal, false),
		meta.Service_DueHourOn.UrlParameterName:            grmi.NewConditionItem(meta.Service_DueHourOn, grmi.Approximate, false),
		meta.Service_MaintByMileageToggle.UrlParameterName: grmi.NewConditionItem(meta.Service_MaintByMileageToggle, grmi.Equal, false),
		meta.Service_DueMileageInterval.UrlParameterName:   grmi.NewConditionItem(meta.Service_DueMileageInterval, grmi.Equal, false),
		meta.Service_NodifyMileages.UrlParameterName:       grmi.NewConditionItem(meta.Service_NodifyMileages, grmi.Equal, false),
		meta.Service_DueMileageAt.UrlParameterName:         grmi.NewConditionItem(meta.Service_DueMileageAt, grmi.Equal, false),
		meta.Service_NeedSchedule.UrlParameterName:         grmi.NewConditionItem(meta.Service_NeedSchedule, grmi.Equal, false),
		meta.Service_MainTimeLen.UrlParameterName:          grmi.NewConditionItem(meta.Service_MainTimeLen, grmi.Equal, false),
		meta.Service_TimeUnit.UrlParameterName:             grmi.NewConditionItem(meta.Service_TimeUnit, grmi.Equal, false),
		meta.Service_SchedType.UrlParameterName:            grmi.NewConditionItem(meta.Service_SchedType, grmi.Equal, false),
		meta.Service_Department.UrlParameterName:           grmi.NewConditionItem(meta.Service_Department, grmi.Equal, false),
		meta.Service_LastModify.UrlParameterName:           grmi.NewConditionItem(meta.Service_LastModify, grmi.Approximate, false),
		meta.Service_LastUser.UrlParameterName:             grmi.NewConditionItem(meta.Service_LastUser, grmi.Equal, false),
		meta.Service_CreateTime.UrlParameterName:           grmi.NewConditionItem(meta.Service_CreateTime, grmi.Approximate, false),
	},
	nil,
)

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/ServiceService.InsertOne
 *
 ******************************************************************************/
func (impl *ServiceServiceImplement) InsertOne(user *global.User, entity *model.Service) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewServiceDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.MainServiceNr)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}

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

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

	//批量插入
	alldata := make([]model.ServiceAttrLst, 0)
	for k, v := range entity.Valst {
		one := model.ServiceAttrLst{}
		one.PlantNr = entity.PlantNr
		one.MainServiceNr = entity.MainServiceNr
		one.Pos = k + 1
		one.AttrNr = v.AttrNr
		one.Descr = v.Descr
		one.Attrname = v.AttrName
		one.Parameter = v.Parameter
		one.CreateTime = entity.CreateTime
		one.LastUser = entity.LastUser
		one.LastModify = entity.LastModify
		alldata = append(alldata, one)
	}
	dao_asset_templatelst := dal.NewServiceAttrLstDAO(session, user.PlantNr, user.UserId)
	err = dao_asset_templatelst.Insert(&alldata)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/ServiceService.DeleteOne
 *
 ******************************************************************************/
func (impl *ServiceServiceImplement) DeleteOne(user *global.User, mainServiceNr int) error {

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

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

	dao_asset_templatelst := dal.NewServiceAttrLstDAO(session, user.PlantNr, user.UserId)
	err = dao_asset_templatelst.DeleteWhere([]grmi.Predicate{meta.ServiceAttrLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.ServiceAttrLst_MainServiceNr.NewPredicate(grmi.Equal, record.MainServiceNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/ServiceService.SelectOne
 *
 ******************************************************************************/
func (impl *ServiceServiceImplement) SelectOne(user *global.User, mainServiceNr int) (*model.Service, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/ServiceService.UpdateOne
 *
 ******************************************************************************/
func (impl *ServiceServiceImplement) UpdateOne(user *global.User, entity *model.Service) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewServiceDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.MainServiceNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	dao_asset_templatelst := dal.NewServiceAttrLstDAO(session, user.PlantNr, user.UserId)
	err = dao_asset_templatelst.DeleteWhere([]grmi.Predicate{meta.ServiceAttrLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.ServiceAttrLst_MainServiceNr.NewPredicate(grmi.Equal, record.MainServiceNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	//批量插入
	alldata := make([]model.ServiceAttrLst, 0)
	for k, v := range entity.Valst {
		one := model.ServiceAttrLst{}
		one.PlantNr = entity.PlantNr
		one.MainServiceNr = entity.MainServiceNr
		one.Pos = k + 1
		one.AttrNr = v.AttrNr
		one.Descr = v.Descr
		one.Attrname = v.AttrName
		one.Parameter = v.Parameter
		one.CreateTime = entity.CreateTime
		one.LastUser = entity.LastUser
		one.LastModify = entity.LastModify
		alldata = append(alldata, one)
	}

	err = dao_asset_templatelst.Insert(&alldata)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/ServiceService.Insert
 *
 ******************************************************************************/
func (impl *ServiceServiceImplement) Insert(user *global.User, entities *[]model.Service) error {

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

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

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

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

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

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

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

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

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

	grmi.Log(user, "/services/pm/implments/Service.service.impl.go", "SelectAll", "SelectAll")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	data := make([]model.Attribute, 0, 10)
	err := session.Table("Pm_Attribute").Find(&data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (impl *ServiceServiceImplement) SelectAssetServices(user *global.User, urlParameters map[string]string) ([]model.Service, error) {

	grmi.Log(user, "/services/pm/implments/Service.service.impl.go", "SelectAssetServices", "SelectAssetServices")

	data := make([]model.CreateData, 0)
	serves := make([]model.Service, 0)
	//第一步，多表联查出所有的数据
	engine := db.Eloquent.Master()
	query := engine.Table("PM_ASSET")
	query = query.Join("INNER", "PM_AssetTemplateLst", "PM_Asset.PlantNr = PM_AssetTemplateLst.PlantNr and PM_Asset.AssetNr = PM_AssetTemplateLst.AssetNr")
	query = query.Join("INNER", "PM_Template", "PM_Template.PlantNr = PM_AssetTemplateLst.PlantNr and PM_Template.MainTemplateNr = PM_AssetTemplateLst.MainTemplateNr")
	query = query.Join("INNER", "PM_TemplateServiceLst", "PM_Template.PlantNr = PM_TemplateServiceLst.PlantNr and PM_Template.MainTemplateNr = PM_TemplateServiceLst.MainTemplateNr")
	query = query.Join("INNER", "PM_Service", "PM_Service.PlantNr = PM_TemplateServiceLst.PlantNr and PM_Service.MainServiceNr = PM_TemplateServiceLst.MainServiceNr")

	query = query.Where("PM_Asset.PlantNr = ? and PM_Service.SchedType = ?", 100, "AUTO")
	err := query.Find(&data)
	if err != nil {
		return nil, err
	}
	for _, v := range data {
		one := model.Service{}
		one = v.Service
		serves = append(serves, one)
	}
	return serves, nil
}

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

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

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

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

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

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

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