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

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/wm"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/wm"
	model "LAPP_ACURA_MOM_BACKEND/models/wm"
	"fmt"
)

/******************************************************************************
 *
 * @Description              : Article的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
var DefaultConditionOfArticle = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Article_ArtId.UrlParameterName:        grmi.NewConditionItem(meta.Article_ArtId, grmi.Equal, true),
		meta.Article_Descr1.UrlParameterName:       grmi.NewConditionItem(meta.Article_Descr1, grmi.Equal, false),
		meta.Article_Descr2.UrlParameterName:       grmi.NewConditionItem(meta.Article_Descr2, grmi.Equal, false),
		meta.Article_ArtType.UrlParameterName:      grmi.NewConditionItem(meta.Article_ArtType, grmi.Equal, false),
		meta.Article_ProjectId.UrlParameterName:    grmi.NewConditionItem(meta.Article_ProjectId, grmi.Equal, false),
		meta.Article_Uom.UrlParameterName:          grmi.NewConditionItem(meta.Article_Uom, grmi.Equal, false),
		meta.Article_Weight.UrlParameterName:       grmi.NewConditionItem(meta.Article_Weight, grmi.Equal, false),
		meta.Article_WeightUom.UrlParameterName:    grmi.NewConditionItem(meta.Article_WeightUom, grmi.Equal, false),
		meta.Article_Length.UrlParameterName:       grmi.NewConditionItem(meta.Article_Length, grmi.Equal, false),
		meta.Article_Width.UrlParameterName:        grmi.NewConditionItem(meta.Article_Width, grmi.Equal, false),
		meta.Article_Height.UrlParameterName:       grmi.NewConditionItem(meta.Article_Height, grmi.Equal, false),
		meta.Article_SizeUom.UrlParameterName:      grmi.NewConditionItem(meta.Article_SizeUom, grmi.Equal, false),
		meta.Article_Fragile.UrlParameterName:      grmi.NewConditionItem(meta.Article_Fragile, grmi.Equal, false),
		meta.Article_Icon.UrlParameterName:         grmi.NewConditionItem(meta.Article_Icon, grmi.Equal, false),
		meta.Article_DisplayColor.UrlParameterName: grmi.NewConditionItem(meta.Article_DisplayColor, grmi.Equal, false),
		meta.Article_Document.UrlParameterName:     grmi.NewConditionItem(meta.Article_Document, grmi.Equal, false),
		meta.Article_LotSize.UrlParameterName:      grmi.NewConditionItem(meta.Article_LotSize, grmi.Equal, false),
		meta.Article_ABCClass.UrlParameterName:     grmi.NewConditionItem(meta.Article_ABCClass, grmi.Equal, false),
		meta.Article_ArtSize1.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSize1, grmi.Equal, false),
		meta.Article_ArtSize2.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSize2, grmi.Equal, false),
		meta.Article_ArtSize3.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSize3, grmi.Equal, false),
		meta.Article_ArtSize4.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSize4, grmi.Equal, false),
		meta.Article_ArtSize5.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSize5, grmi.Equal, false),
		meta.Article_ArtSpec1.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSpec1, grmi.Equal, false),
		meta.Article_ArtSpec2.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSpec2, grmi.Equal, false),
		meta.Article_ArtSpec3.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSpec3, grmi.Equal, false),
		meta.Article_ArtSpec4.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSpec4, grmi.Equal, false),
		meta.Article_ArtSpec5.UrlParameterName:     grmi.NewConditionItem(meta.Article_ArtSpec5, grmi.Equal, false),
		meta.Article_LastModify.UrlParameterName:   grmi.NewConditionItem(meta.Article_LastModify, grmi.Approximate, false),
		meta.Article_LastUser.UrlParameterName:     grmi.NewConditionItem(meta.Article_LastUser, grmi.Equal, false),
		meta.Article_CreateTime.UrlParameterName:   grmi.NewConditionItem(meta.Article_CreateTime, grmi.Approximate, false),
		meta.Article_Qty.UrlParameterName:          grmi.NewConditionItem(meta.Article_Qty, grmi.Equal, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Article的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
var DefaultConditionOfArticleAndPaging = grmi.NewCondition(
	DefaultConditionOfArticle.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ArticleServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Article的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
type ArticleServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewArticleDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ArticleDAOImplement实例
 *
 * @Return Value             : ArticleDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
func NewArticleServiceImplement() *ArticleServiceImplement {
	return &ArticleServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.InsertOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) InsertOne(user *global.User, entity *model.Article) error {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "InsertOneArticle", "插入一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewArticleDAO(session, user.UserId)
	artRepDao := dal.NewArticleReplenishDAO(session, user.UserId)
	artPRDao := dal.NewArticlePickingRateDAO(session, user.UserId)
	record, err := dao.SelectOne(entity.ArtId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	artRep := entity.ArticleReplenish
	artPickRate := entity.ArticlePickingRate
	if artPickRate.ArtId != entity.ArtId || artRep.ArtId != entity.ArtId {
		_ = session.Rollback()
		return grmi.NewBusinessError("ArtId不一致")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = artPRDao.InsertOne(&artPickRate)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = artRepDao.InsertOne(&artRep)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.DeleteOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) DeleteOne(user *global.User, artId string) error {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "DeleteOneArticle", "删除一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewArticleDAO(session, user.UserId)
	replenishDao := dal.NewArticleReplenishDAO(session, user.UserId)
	pickingDao := dal.NewArticlePickingRateDAO(session, user.UserId)
	artAssertDao := dal.NewAssertArtLstDAO(session, user.UserId)
	record, err := dao.SelectOne(artId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = replenishDao.DeleteOne(artId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = pickingDao.DeleteOne(artId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = artAssertDao.DeleteWhere([]grmi.Predicate{meta.AssertArtLst_ArtId.NewPredicate(grmi.Equal, artId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = dao.DeleteOne(artId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.SelectOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) SelectOne(user *global.User, artId string) (*model.Article, error) {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "SelectOneArticle", "查询一个Article")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.UpdateOne
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) UpdateOne(user *global.User, entity *model.Article) error {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "UpdateOneArticle", "修改一个Article")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewArticleDAO(session, user.UserId)
	replenishDao := dal.NewArticleReplenishDAO(session, user.UserId)
	pickingDao := dal.NewArticlePickingRateDAO(session, user.UserId)
	record, err := dao.SelectOne(entity.ArtId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.ArtId != entity.ArtId || entity.ArticleReplenish.ArtId != record.ArtId || entity.ArticlePickingRate.ArtId != record.ArtId {
		_ = session.Rollback()
		return grmi.NewBusinessError("ArtId不一致")
	}
	if record.ArticleReplenish.ArtId == "" {
		err = replenishDao.InsertOne(&entity.ArticleReplenish)
	} else {
		err = replenishDao.UpdateOne(&entity.ArticleReplenish)
	}
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record.ArticlePickingRate.ArtId == "" {
		err = pickingDao.InsertOne(&entity.ArticlePickingRate)

	} else {
		err = pickingDao.UpdateOne(&entity.ArticlePickingRate)
	}
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.Insert
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Insert(user *global.User, entities *[]model.Article) error {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "InsertArticle", "插入多个Article")

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

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

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "DeleteArticle", "删除多个Article")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ArtId)
		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/wm/ArticleService.Select
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Select(user *global.User, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "SelectArticle", "查询Article")

	condition := DefaultConditionOfArticleAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewArticleDAO(session, user.UserId)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/wm/ArticleService.Update
 *
 ******************************************************************************/
func (impl *ArticleServiceImplement) Update(user *global.User, entities *[]model.Article) error {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "UpdateArticle", "修改多个Article")

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

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

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

func (impl *ArticleServiceImplement) ExportExcel(user *global.User, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/wm/implments/Article.service.impl.go", "ExportExcel", "导出excel表")

	condition := DefaultConditionOfArticleAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewArticleDAO(session, user.UserId)
	//condition.OrderByFields = append(condition.OrderByFields, meta.Article_ArtId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	temp := make([]interface{}, len(result))
	for index, item := range result {
		temp[index] = item
	}
	titleList := []string{}

	filepath, err := grmi.SaveExcelFile(temp, titleList, "物料", "物料")
	if err != nil {
		return nil, grmi.NewBusinessError(fmt.Sprintf("导出报表失败，请重试, errors: %s", err.Error()))
	}
	return filepath, nil
}
