// 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              : Template的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
var DefaultConditionOfTemplate = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Template_MainTemplateNr.UrlParameterName:        grmi.NewConditionItem(meta.Template_MainTemplateNr, grmi.Equal, true),
		meta.Template_Descr.UrlParameterName:                 grmi.NewConditionItem(meta.Template_Descr, grmi.Equal, false),
		meta.Template_TrackByDateToggle.UrlParameterName:     grmi.NewConditionItem(meta.Template_TrackByDateToggle, grmi.Equal, false),
		meta.Template_TrackByPriMeterToggle.UrlParameterName: grmi.NewConditionItem(meta.Template_TrackByPriMeterToggle, grmi.Equal, false),
		meta.Template_PriMeterUom.UrlParameterName:           grmi.NewConditionItem(meta.Template_PriMeterUom, grmi.Equal, false),
		meta.Template_TrackBySecMeterToggle.UrlParameterName: grmi.NewConditionItem(meta.Template_TrackBySecMeterToggle, grmi.Equal, false),
		meta.Template_SecMeterUom.UrlParameterName:           grmi.NewConditionItem(meta.Template_SecMeterUom, grmi.Equal, false),
		meta.Template_LastModify.UrlParameterName:            grmi.NewConditionItem(meta.Template_LastModify, grmi.Approximate, false),
		meta.Template_LastUser.UrlParameterName:              grmi.NewConditionItem(meta.Template_LastUser, grmi.Equal, false),
		meta.Template_CreateTime.UrlParameterName:            grmi.NewConditionItem(meta.Template_CreateTime, grmi.Approximate, false),
	},
	nil,
)

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/TemplateService.InsertOne
 *
 ******************************************************************************/
func (impl *TemplateServiceImplement) InsertOne(user *global.User, entity *model.Template) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewTemplateDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.MainTemplateNr)
	if err != nil {
		return err
	}
	if record != nil {
		session.Rollback()
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	snrDao := baseDal.NewSnrDAO(session, user.PlantNr, user.UserId)
	Maintemplatenr, err := snrDao.GetNextSnr("Templateid")
	if err != nil {
		session.Rollback()
		return err
	}
	entity.MainTemplateNr = utils.ValueToInt(Maintemplatenr,0)
	err = dao.InsertOne(entity)
	if err != nil {
		session.Rollback()
		return err
	}

	//批量插入
	alldata := make([]model.TemplateServiceLst, 0)
	for k, v := range entity.Valst {
		one := model.TemplateServiceLst{}
		one.PlantNr = entity.PlantNr
		one.Pos = k + 1
		one.Descr = v.Descr
		one.MainTemplateNr = entity.MainTemplateNr
		one.MainServiceNr = utils.ValueToInt(v.MainServiceNr, 0)
		one.CreateTime = entity.CreateTime
		one.LastUser = entity.LastUser
		one.LastModify = entity.LastModify
		alldata = append(alldata, one)
	}
	_, err = session.Table("PM_TemplateServiceLst").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/TemplateService.DeleteOne
 *
 ******************************************************************************/
func (impl *TemplateServiceImplement) DeleteOne(user *global.User, mainTemplateNr int) error {

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

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

	dao_TemplateServiceLst := dal.NewTemplateServiceLstDAO(session, user.PlantNr, user.UserId)
	err = dao_TemplateServiceLst.DeleteWhere([]grmi.Predicate{meta.TemplateServiceLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.TemplateServiceLst_MainTemplateNr.NewPredicate(grmi.Equal, record.MainTemplateNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/TemplateService.SelectOne
 *
 ******************************************************************************/
func (impl *TemplateServiceImplement) SelectOne(user *global.User, mainTemplateNr int) (*model.Template, error) {

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

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

	if result == nil{
		return result, err
	}

	var datalist []model.Service
	var tem1 []model.Service
	var tem2 []model.TemplateServiceLst
	var maintemplatenrs []int
	err = session.Table("PM_Service").Find(&tem1)
	if err != nil {
		return result, err
	}
	err = session.Table("PM_TemplateServiceLst").Find(&tem2)
	if err != nil {
		return result, err
	}

	var Maintemplatenrs []int
	for _, v := range tem1 {
		for _, v2 := range tem2{
			if v.PlantNr == v2.PlantNr && v.MainServiceNr == v2.MainServiceNr{
				dataone := model.Service{}
				dataone.MainServiceNr = v.MainServiceNr
				dataone.Descr = v.Descr
				maintemplatenrs = append(maintemplatenrs, v2.MainTemplateNr)
				datalist = append(datalist, dataone)
			}
		}
	}
	result.Valst = datalist

	var templatedata []model.Service
	err = session.Table("PM_Service").NotIn("MainServiceNr", Maintemplatenrs).Where("PlantNr = ?", result.PlantNr).Find(&templatedata)
	if err != nil {
		return result, err
	}
	result.UnValst = templatedata

	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/TemplateService.UpdateOne
 *
 ******************************************************************************/
func (impl *TemplateServiceImplement) UpdateOne(user *global.User, entity *model.Template) error {

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

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

	dao_TemplateServiceLst := dal.NewTemplateServiceLstDAO(session, user.PlantNr, user.UserId)
	err = dao_TemplateServiceLst.DeleteWhere([]grmi.Predicate{meta.TemplateServiceLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.TemplateServiceLst_MainTemplateNr.NewPredicate(grmi.Equal, record.MainTemplateNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	//批量插入
	alldata := make([]model.TemplateServiceLst, 0)
	for k, v := range entity.Valst {
		one := model.TemplateServiceLst{}
		one.PlantNr = entity.PlantNr
		one.Pos = k + 1
		one.Descr = v.Descr
		one.MainTemplateNr = entity.MainTemplateNr
		one.MainServiceNr = utils.ValueToInt(v.MainServiceNr, 0)
		one.CreateTime = entity.CreateTime
		one.LastUser = entity.LastUser
		one.LastModify = entity.LastModify
		alldata = append(alldata, one)
	}
	_, err = session.Table("PM_TemplateServiceLst").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/TemplateService.Insert
 *
 ******************************************************************************/
func (impl *TemplateServiceImplement) Insert(user *global.User, entities *[]model.Template) error {

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

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

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

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

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

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

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

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

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	var data []model.Service
	err := session.Table("Pm_Service").Where("PlantNr = ?", user.PlantNr).Find(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

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

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

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

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

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

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

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