// 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/me"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	baseMeta "LAPP_ACURA_MOM_BACKEND/meta/base"
	meta "LAPP_ACURA_MOM_BACKEND/meta/me"
	baseModel "LAPP_ACURA_MOM_BACKEND/models/base"
	model "LAPP_ACURA_MOM_BACKEND/models/me"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : BomHead的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-09 14:13:50
 *
 ******************************************************************************/
var DefaultConditionOfBomHead = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.BomHead_BomId.UrlParameterName:        grmi.NewConditionItem(meta.BomHead_BomId, grmi.Equal, true),
		meta.BomHead_MatNr.UrlParameterName:        grmi.NewConditionItem(meta.BomHead_MatNr, grmi.Equal, false),
		meta.BomHead_Descr.UrlParameterName:        grmi.NewConditionItem(meta.BomHead_Descr, grmi.Equal, false),
		meta.BomHead_BomheadCval1.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadCval1, grmi.Equal, false),
		meta.BomHead_BomheadCval2.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadCval2, grmi.Equal, false),
		meta.BomHead_BomheadIval1.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadIval1, grmi.Equal, false),
		meta.BomHead_BomheadIval2.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadIval2, grmi.Equal, false),
		meta.BomHead_BomheadDval1.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadDval1, grmi.Equal, false),
		meta.BomHead_BomheadDval2.UrlParameterName: grmi.NewConditionItem(meta.BomHead_BomheadDval2, grmi.Equal, false),
		meta.BomHead_LastModify.UrlParameterName:   grmi.NewConditionItem(meta.BomHead_LastModify, grmi.Approximate, false),
		meta.BomHead_LastUser.UrlParameterName:     grmi.NewConditionItem(meta.BomHead_LastUser, grmi.Equal, false),
		meta.BomHead_CreateTime.UrlParameterName:   grmi.NewConditionItem(meta.BomHead_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : BomHead的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-09 14:13:50
 *
 ******************************************************************************/
var DefaultConditionOfBomHeadAndPaging = grmi.NewCondition(
	DefaultConditionOfBomHead.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : BomHeadServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : BomHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-09 14:13:50
 *
 ******************************************************************************/
type BomHeadServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewBomHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个BomHeadDAOImplement实例
 *
 * @Return Value             : BomHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-09 14:13:50
 *
 ******************************************************************************/
func NewBomHeadServiceImplement() *BomHeadServiceImplement {
	return &BomHeadServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/BomHeadService.InsertOne
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) InsertOne(user *global.User, entity *model.BomHead) error {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "InsertOneBomHead", "插入一个BomHead")

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

	articleDao := baseDal.NewArticleDAO(session, user.PlantNr, user.UserId)
	articleLi, err := articleDao.Select([]grmi.Predicate{baseMeta.Article_ArtId.NewPredicate(grmi.Equal, entity.MatNr)}, nil)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("查询物料数据失败, error:" + err.Error())
	}
	if len(articleLi) == 0 {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在对应的物料数据")
	}
	article := articleLi[0]
	if article.ArtSpec1 != baseModel.ART_TYPE_FINISHED && article.ArtSpec1 != baseModel.ART_TYPE_CARSET {
		_ = session.Rollback()
		return grmi.NewBusinessError("传递的物料不是总成或虚拟物料ID")
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/BomHeadService.DeleteOne
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) DeleteOne(user *global.User, bomId string) error {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "DeleteOneBomHead", "删除一个BomHead")

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

	dao2 := dal.NewBomLstDAO(session, user.PlantNr, user.UserId)
	err = dao2.DeleteWhere([]grmi.Predicate{meta.BomLst_BomId.NewPredicate(grmi.Equal, bomId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/BomHeadService.SelectOne
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) SelectOne(user *global.User, bomId string) (*model.BomHead, error) {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "SelectOneBomHead", "查询一个BomHead")

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

	if result != nil {
		var Me model.BomLst
		Me.PlantNr = result.PlantNr
		Me.BomId = result.BomId
		bomList, err := Me.SetMenu(result.MatNr)
		if err != nil {
			return nil, err
		}
		result.BomLstLi = bomList
	}

	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/me/BomHeadService.UpdateOne
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) UpdateOne(user *global.User, entity *model.BomHead) error {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "UpdateOneBomHead", "修改一个BomHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewBomHeadDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.BomId)
	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/me/BomHeadService.Insert
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) Insert(user *global.User, entities *[]model.BomHead) error {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "InsertBomHead", "插入多个BomHead")

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

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

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "DeleteBomHead", "删除多个BomHead")

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

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

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "SelectBomHead", "查询BomHead")

	condition := DefaultConditionOfBomHeadAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewBomHeadDAO(session, user.PlantNr, 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/me/BomHeadService.Update
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) Update(user *global.User, entities *[]model.BomHead) error {

	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "UpdateBomHead", "修改多个BomHead")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.BomId)
		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/me/BomHeadService.Copy
 *
 ******************************************************************************/
func (impl *BomHeadServiceImplement) Copy(user *global.User, sourceArtId string, targetArtIdLi []string) error {
	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "Copy", "Copy复制Bom")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	daoBomHead := dal.NewBomHeadDAO(session, user.PlantNr, user.UserId)
	daoBomLst := dal.NewBomLstDAO(session, user.PlantNr, user.UserId)
	daoArticle := baseDal.NewArticleDAO(session, user.PlantNr, user.UserId)
	bomHead, err := daoBomHead.SelectOne(sourceArtId)
	if err != nil {
		return grmi.NewBusinessError("查询bom数据失败, error:" + err.Error())
	}
	if bomHead == nil {
		return grmi.NewBusinessError("来源物料不存在物料的Bom数据")
	}
	bomLstLi, err := daoBomLst.Select([]grmi.Predicate{meta.BomLst_BomId.NewPredicate(grmi.Equal, sourceArtId)}, []grmi.Field{meta.BomLst_Position})
	if err != nil {
		return grmi.NewBusinessError("查询bom子项失败, error:" + err.Error())
	}
	if len(bomLstLi) == 0 {
		return grmi.NewBusinessError("来源物料不存在物料bom子项")
	}
	bomIdLi := make([]interface{}, 0, len(targetArtIdLi))
	for _, artId := range targetArtIdLi {
		bomIdLi = append(bomIdLi, artId)
	}
	if err = session.Begin(); err != nil {
		return err
	}
	for _, artId := range targetArtIdLi {
		articleLi, err := daoArticle.Select([]grmi.Predicate{baseMeta.Article_ArtId.NewPredicate(grmi.Equal, artId)}, nil)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询物料失败, error:" + err.Error())
		}
		if len(articleLi) == 0 {
			_ = session.Rollback()
			return grmi.NewBusinessError("物料不存在, 物料ID:" + artId)
		}
		article := articleLi[0]
		targetBomHead, err := daoBomHead.SelectOne(artId)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询目标物料存在的bom数据失败, error:" + err.Error())
		}
		if targetBomHead == nil {
			targetBomHead = bomHead
			targetBomHead.BomId = artId
			targetBomHead.MatNr = artId
			targetBomHead.Descr = article.Descr1
			err = daoBomHead.InsertOne(targetBomHead)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入目标物料bom数据失败, error:" + err.Error())
			}
		}
		targetBomLstLi := make([]model.BomLst, 0, 20)
		for index, bomLst := range bomLstLi {
			if index != 0 && index%20 == 0 {
				err = daoBomLst.Insert(&targetBomLstLi)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("写入目标物料bom子项失败, error:" + err.Error())
				}
				targetBomLstLi = make([]model.BomLst, 0, 20)
			}
			bomLst.BomId = artId
			if bomLst.FmatNr == sourceArtId {
				bomLst.FmatNr = artId
				bomLst.FmatName = article.Descr1
			}
			targetBomLstLi = append(targetBomLstLi, bomLst)
		}
		if len(targetBomLstLi) != 0 {
			err = daoBomLst.Insert(&targetBomLstLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入目标物料bom子项失败, error:" + err.Error())
			}
		}
	}
	_ = session.Commit()
	return nil
}

// ImportFromExcel 从excel导入数据
func (impl *BomHeadServiceImplement) ImportFromExcel(user *global.User, filepath string) error {
	grmi.Log(user, "/services/me/implments/BomHead.service.impl.go", "ImportFromExcel", "Copy复制Bom")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	daoArticle := baseDal.NewArticleDAO(session, user.PlantNr, user.UserId)
	daoBomHead := dal.NewBomHeadDAO(session, user.PlantNr, user.UserId)
	daoBomLst := dal.NewBomLstDAO(session, user.PlantNr, user.UserId)
	file, err := excelize.OpenFile(filepath)
	if err != nil {
		return grmi.NewBusinessError("读取文件失败, error:" + err.Error())
	}
	rowsIterator, err := file.Rows("Sheet1")
	if err != nil {
		return grmi.NewBusinessError("读取Sheet1页失败, error:" + err.Error())
	}
	rowIndex := 0
	// 将excel生成的切片通过bomId进行分类
	bomMap := make(map[string][]model.BomLst)
	articleMap := make(map[string]string)
	for rowsIterator.Next() {
		rowIndex++
		if rowIndex == 1 {
			_, err = rowsIterator.Columns()
			if err != nil {
				return grmi.NewBusinessError("去读excel行数据失败, error:" + err.Error())
			}
			continue
		}
		row, err := rowsIterator.Columns()
		if err != nil {
			return grmi.NewBusinessError("去读excel行数据失败, error:" + err.Error())
		}
		if len(row) != 6 {
			return grmi.NewBusinessError("excel数据列数不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		fmatQty, err := strconv.Atoi(row[2])
		if err != nil {
			return grmi.NewBusinessError("excel数据fmatQty不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		cmatQty, err := strconv.Atoi(row[4])
		if err != nil {
			return grmi.NewBusinessError("excel数据cmatQty不合规, 行数:" + strconv.Itoa(rowIndex))
		}
		fmatDesc, exist := articleMap[row[1]]
		if !exist {
			articleLi, err := daoArticle.Select([]grmi.Predicate{baseMeta.Article_ArtId.NewPredicate(grmi.Equal, row[1])}, nil)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("查询物料失败, error:" + err.Error())
			}
			if len(articleLi) == 0 {
				_ = session.Rollback()
				return grmi.NewBusinessError("物料不存在, 物料ID:" + row[1])
			}
			article := articleLi[0]
			articleMap[article.ArtId] = article.Descr1
			fmatDesc = article.Descr1
		}
		cmatDesc, exist := articleMap[row[3]]
		if !exist {
			articleLi, err := daoArticle.Select([]grmi.Predicate{baseMeta.Article_ArtId.NewPredicate(grmi.Equal, row[3])}, nil)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("查询物料失败, error:" + err.Error())
			}
			if len(articleLi) == 0 {
				_ = session.Rollback()
				return grmi.NewBusinessError("物料不存在, 物料ID:" + row[3])
			}
			article := articleLi[0]
			articleMap[article.ArtId] = article.Descr1
			cmatDesc = article.Descr1
		}
		bomLst := model.BomLst{
			BomId:    row[0],
			FmatNr:   row[1],
			FmatName: fmatDesc,
			CmatNr:   row[3],
			FmatQty:  float64(fmatQty),
			CmatName: cmatDesc,
			CmatQty:  float64(cmatQty),
		}
		_, exist = bomMap[row[1]]
		if !exist {
			bomMap[row[1]] = make([]model.BomLst, 0)
		}
		bomMap[row[1]] = append(bomMap[row[1]], bomLst)
	}
	if err = session.Begin(); err != nil {
		return err
	}
	for bomId, bomLstLi := range bomMap {
		bomHead, err := daoBomHead.SelectOne(bomId)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询bom数据失败, error:" + err.Error())
		}
		desc := articleMap[bomId]
		if bomHead == nil {
			bomHead := &model.BomHead{
				BomId: bomId,
				MatNr: bomId,
				Descr: desc,
			}
			err = daoBomHead.InsertOne(bomHead)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入bom数据失败， error:" + err.Error())
			}
		}
		tempBomLstLi := make([]model.BomLst, 0, 20)
		for index, bomLst := range bomLstLi {
			if index != 0 && index % 20 == 0 {
				err = daoBomLst.Insert(&tempBomLstLi)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("写入bom子项失败, error:" + err.Error())
				}
				tempBomLstLi = make([]model.BomLst, 0, 20)
			}
			tempBomLstLi = append(tempBomLstLi, bomLst)
		}
		if len(tempBomLstLi) != 0 {
			 err = daoBomLst.Insert(&tempBomLstLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("写入bom子项失败, error:" + err.Error())
			}
		}
	}
	_ = session.Commit()
	return nil
}
