// 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              : Asset的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
var DefaultConditionOfAsset = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Asset_AssetNr.UrlParameterName:        grmi.NewConditionItem(meta.Asset_AssetNr, grmi.Equal, true),
		meta.Asset_Descr.UrlParameterName:          grmi.NewConditionItem(meta.Asset_Descr, grmi.Equal, false),
		meta.Asset_AssetName.UrlParameterName:      grmi.NewConditionItem(meta.Asset_AssetName, grmi.Equal, false),
		meta.Asset_AssetType.UrlParameterName:      grmi.NewConditionItem(meta.Asset_AssetType, grmi.Equal, false),
		meta.Asset_Model.UrlParameterName:          grmi.NewConditionItem(meta.Asset_Model, grmi.Equal, false),
		meta.Asset_Year.UrlParameterName:           grmi.NewConditionItem(meta.Asset_Year, grmi.Equal, false),
		meta.Asset_SerialNo.UrlParameterName:       grmi.NewConditionItem(meta.Asset_SerialNo, grmi.Equal, false),
		meta.Asset_TagNo.UrlParameterName:          grmi.NewConditionItem(meta.Asset_TagNo, grmi.Equal, false),
		meta.Asset_Maker.UrlParameterName:          grmi.NewConditionItem(meta.Asset_Maker, grmi.Equal, false),
		meta.Asset_LocaNr.UrlParameterName:         grmi.NewConditionItem(meta.Asset_LocaNr, grmi.Equal, false),
		meta.Asset_AssetStatus.UrlParameterName:    grmi.NewConditionItem(meta.Asset_AssetStatus, grmi.Equal, false),
		meta.Asset_Operator.UrlParameterName:       grmi.NewConditionItem(meta.Asset_Operator, grmi.Equal, false),
		meta.Asset_WeekModelId.UrlParameterName:    grmi.NewConditionItem(meta.Asset_WeekModelId, grmi.Equal, false),
		meta.Asset_WorkCalEndarId.UrlParameterName: grmi.NewConditionItem(meta.Asset_WorkCalEndarId, grmi.Equal, false),
		meta.Asset_CostCenterId.UrlParameterName:   grmi.NewConditionItem(meta.Asset_CostCenterId, grmi.Equal, false),
		meta.Asset_LastModify.UrlParameterName:     grmi.NewConditionItem(meta.Asset_LastModify, grmi.Approximate, false),
		meta.Asset_LastUser.UrlParameterName:       grmi.NewConditionItem(meta.Asset_LastUser, grmi.Equal, false),
		meta.Asset_CreateTime.UrlParameterName:     grmi.NewConditionItem(meta.Asset_CreateTime, grmi.Approximate, false),
	},
	nil,
)

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/AssetService.InsertOne
 *
 ******************************************************************************/
func (impl *AssetServiceImplement) InsertOne(user *global.User, entity *model.Asset) error {

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

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

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

	//批量插入
	alldata := make([]model.AssetTemplateLst, 0)
	for k, v := range entity.Valst {
		dataone := model.AssetTemplateLst{}
		dataone.PlantNr = entity.PlantNr
		dataone.AssetNr = entity.AssetNr
		dataone.MainTemplateNr = v.MainTemplateNr
		dataone.Pos = k + 1
		dataone.CreateTime = entity.CreateTime
		dataone.LastModify = entity.LastModify
		dataone.LastUser = entity.LastUser
		alldata = append(alldata, dataone)
	}

	dao_asset_templatelst := dal.NewAssetTemplateLstDAO(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/AssetService.DeleteOne
 *
 ******************************************************************************/
func (impl *AssetServiceImplement) DeleteOne(user *global.User, assetNr int) error {

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

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

	dao_asset_templatelst := dal.NewAssetTemplateLstDAO(session, user.PlantNr, user.UserId)
	err = dao_asset_templatelst.DeleteWhere([]grmi.Predicate{meta.AssetTemplateLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.AssetTemplateLst_AssetNr.NewPredicate(grmi.Equal, record.AssetNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pm/AssetService.SelectOne
 *
 ******************************************************************************/
func (impl *AssetServiceImplement) SelectOne(user *global.User, assetNr int) (*model.Asset, error) {

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

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

	var datalist []model.Template
	var tem1 []model.Template
	var tem2 []model.AssetTemplateLst
	err = session.Table("PM_AssetTemplateLst").Find(&tem2)
	if err != nil {
		return result, err
	}
	err = session.Table("PM_Template").Find(&tem1)
	if err != nil {
		return result, err
	}

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

	var templatedata []model.Template
	err = session.Table("PM_Template").NotIn("MainTemplateNr", 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/AssetService.UpdateOne
 *
 ******************************************************************************/
func (impl *AssetServiceImplement) UpdateOne(user *global.User, entity *model.Asset) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewAssetDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.AssetNr)
	if err != nil {
		session.Rollback()
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		session.Rollback()
		return err
	}
	dao_asset_templatelst := dal.NewAssetTemplateLstDAO(session, user.PlantNr, user.UserId)
	err = dao_asset_templatelst.DeleteWhere([]grmi.Predicate{meta.AssetTemplateLst_PlantNr.NewPredicate(grmi.Equal, record.PlantNr), meta.AssetTemplateLst_AssetNr.NewPredicate(grmi.Equal, record.AssetNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	//批量插入
	alldata := make([]model.AssetTemplateLst, 0)
	for k, v := range entity.Valst {
		dataone := model.AssetTemplateLst{}
		dataone.PlantNr = entity.PlantNr
		dataone.AssetNr = entity.AssetNr
		dataone.MainTemplateNr = v.MainTemplateNr
		dataone.Pos = k + 1
		dataone.CreateTime = entity.CreateTime
		dataone.LastModify = entity.LastModify
		dataone.LastUser = entity.LastUser
		alldata = append(alldata, dataone)
	}

	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/AssetService.Insert
 *
 ******************************************************************************/
func (impl *AssetServiceImplement) Insert(user *global.User, entities *[]model.Asset) error {

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

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

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

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

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

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

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

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

	assetIdLi := make([]int, 0)
	err := session.Table("PM_UserAssetLst").Where("UserId = ?", user.UserId).Cols("AssetId").Find(&assetIdLi)
	if err != nil {
		return nil, err
	}
	var data []model.Asset
	if user.UserId == "admin" {
		err = session.Table("Pm_Asset").Where("PlantNr = ?", user.PlantNr).Find(&data)
	} else {
		err = session.Table("Pm_Asset").Where("PlantNr = ?", user.PlantNr).In("AssetId", assetIdLi).Find(&data)
	}
	if err != nil {
		return data, err
	}
	return data, nil
}

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

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

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

	assetIdLi := make([]int, 0)
	err := session.Table("PM_UserAssetLst").Where("UserId = ?", user.UserId).Cols("AssetId").Find(&assetIdLi)
	if err != nil {
		return nil, err
	}
	var data []model.Asset
	if user.UserId == "admin" {
		err = session.Table("Pm_Asset").Where("PlantNr = ?", user.PlantNr).Find(&data)
	} else {
		err = session.Table("Pm_Asset").Where("PlantNr = ?", user.PlantNr).In("AssetId", assetIdLi).Find(&data)
	}
	if err != nil {
		return data, err
	}
	return data, nil
}

func (impl *AssetServiceImplement) SelectArrPmTemplate(user *global.User, urlParameters map[string]string) ([]model.Template, error) {

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

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

	data := make([]model.Template, 0)
	err := session.Table("Pm_Template").Where("PlantNr = ?", user.PlantNr).Find(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

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

	grmi.Log(user, "/services/pm/implments/Asset.service.impl.go", "GetPmAssetService", "GetPmAssetService")

	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
}

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

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


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

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

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

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

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

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

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