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

package implments

import (
	dal "LAPP_LF_MOM_BACKEND/dao/qm"
	baseDal "LAPP_LF_MOM_BACKEND/dao/base"
	omDal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	meta "LAPP_LF_MOM_BACKEND/meta/qm"
	bmeta "LAPP_LF_MOM_BACKEND/meta/base"
	model "LAPP_LF_MOM_BACKEND/models/qm"
	bmodel "LAPP_LF_MOM_BACKEND/models/base"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/models"
	"fmt"
	"strings"
)

/******************************************************************************
 *
 * @Description              : ReclinerReclst的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-07-12 14:05:20
 *
 ******************************************************************************/
var DefaultConditionOfReclinerReclst = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ReclinerReclst_RecNr.UrlParameterName:         grmi.NewConditionItem(meta.ReclinerReclst_RecNr, grmi.Equal, true),
		meta.ReclinerReclst_Line.UrlParameterName:          grmi.NewConditionItem(meta.ReclinerReclst_Line, grmi.Equal, true),
		meta.ReclinerReclst_ArtId.UrlParameterName:         grmi.NewConditionItem(meta.ReclinerReclst_ArtId, grmi.Equal, false),
		meta.ReclinerReclst_SerialOrderId.UrlParameterName: grmi.NewConditionItem(meta.ReclinerReclst_SerialOrderId, grmi.Equal, false),
		meta.ReclinerReclst_ReclinerNr.UrlParameterName:    grmi.NewConditionItem(meta.ReclinerReclst_ReclinerNr, grmi.Equal, false),
		meta.ReclinerReclst_ItemPartNr.UrlParameterName:    grmi.NewConditionItem(meta.ReclinerReclst_ItemPartNr, grmi.Equal, false),
		meta.ReclinerReclst_Status.UrlParameterName:        grmi.NewConditionItem(meta.ReclinerReclst_Status, grmi.Equal, false),
		meta.ReclinerReclst_LastModify.UrlParameterName:    grmi.NewConditionItem(meta.ReclinerReclst_LastModify, grmi.Approximate, false),
		meta.ReclinerReclst_LastUser.UrlParameterName:      grmi.NewConditionItem(meta.ReclinerReclst_LastUser, grmi.Equal, false),
		meta.ReclinerReclst_CreateTime.UrlParameterName:    grmi.NewConditionItem(meta.ReclinerReclst_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ReclinerReclst的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-07-12 14:05:20
 *
 ******************************************************************************/
var DefaultConditionOfReclinerReclstAndPaging = grmi.NewCondition(
	DefaultConditionOfReclinerReclst.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ReclinerReclstServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ReclinerReclst的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-07-12 14:05:20
 *
 ******************************************************************************/
type ReclinerReclstServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewReclinerReclstDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ReclinerReclstDAOImplement实例
 *
 * @Return Value             : ReclinerReclstDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-07-12 14:05:20
 *
 ******************************************************************************/
func NewReclinerReclstServiceImplement() *ReclinerReclstServiceImplement {
	return &ReclinerReclstServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.InsertOne
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) InsertOne(user *models.Usertab, entity *model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "InsertOneReclinerReclst", "插入一个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.RecNr)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	bDao := baseDal.NewLabelParserHeadDAO(session, user.Pid, user.Userid)
	result, err := bDao.SelectOne("Barcode")
	if err != nil {
		return err
	}
	orderId := entity.SerialOrderId
	var artId string
	if utils.ValueIsEmpty(result.Split) {
		lstdao := baseDal.NewLabelParserDetailLstDAO(session, user.Pid, user.Userid)
		list, err := lstdao.Select([]grmi.Predicate{
			bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
		}, nil)
		if err != nil {
			return err
		}
		result.Valst = list
		if len(orderId) < result.Length {
			return grmi.NewBusinessError("序列订单错误!")
		}
		codeInfos := bmodel.ParseBarcode(orderId, result.Valst)
		artId = codeInfos["artId"]
	} else {
		artIds := strings.Split(orderId, result.Split)
		artId = artIds[0]
	}
	entity.ArtId = artId
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.AddPrinterInfo
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) AddPrinterInfo(user *models.Usertab, entity *model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "InsertOneReclinerReclst", "插入一个ReclinerReclst")

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

	templateId := "TSC-BARCODE"
	dao := baseDal.NewPrinterTemplateDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(templateId)
	if err != nil {
		return err
	}
	lstdao := baseDal.NewPrinterTemplateLstDAO(session, user.Pid, user.Userid)
	list, err := lstdao.Select([]grmi.Predicate{
		bmeta.PrinterTemplateLst_TemplateId.NewPredicate(grmi.Equal, templateId),
	}, nil)
	if err != nil {
		return err
	}
	result.PrinterTemplateLst = list

	//查询物料主数据表
	artDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
	artInfo, err := artDao.SelectOne(entity.ArtId)
	if err != nil {
		return err
	}
	if artInfo == nil {
		return grmi.NewBusinessError("客户订单号没有维护!")
	}
	//查询序列订单表
	orderDao := omDal.NewSerialOrderDAO(session, user.Pid, user.Userid)
	orderInfo, err := orderDao.SelectBySerialOrder(entity.SerialOrderId)
	if err != nil {
		return err
	}
	if orderInfo == nil {
		return grmi.NewBusinessError("序列订单订单不存在!")
	}
	snr := new(models.Snrtab)
	snr.Finr = bmodel.PlantNr
	snr.Snrid = "PrintId"
	headId,err :=  snr.GetNextSnr("PrintId")
	if err != nil {
		fmt.Println(err)
		return grmi.NewBusinessError("打印头部生成错误!")
	}

	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	headDao := baseDal.NewPrintHeadDAO(session, user.Pid, user.Userid)
	head := new(bmodel.PrintHead)
	head.PlantNr = result.PlantNr
	head.PrintHeadId = headId
	head.Status = "N"
	head.TemplateFile = result.TemplateFile
	head.PrinterId = result.PrinterId
	head.PrintCopies = 1
	head.PrintFileType = result.TemplateTye
	err = headDao.InsertOne(head)
	if err != nil {
		session.Rollback()
		return err
	}

	detailDao := baseDal.NewPrintDetailDAO(session, user.Pid, user.Userid)
	for k, v := range list {
		detail := new(bmodel.PrintDetail)
		head.PlantNr = result.PlantNr
		detail.PrintHeadId = headId
		detail.Pos = (k + 1)
		detail.VarName = v.VarName
		//映射值
		if detail.VarName == "$SN$" {
			detail.VarValue = entity.SerialOrderId
		} else if detail.VarName == "$DATE$" {
			dateStr := utils.TimeFormat(orderInfo.PlanStartTime.Restore(), "yyyy/MM/dd")
			detail.VarValue = dateStr
		} else if detail.VarName == "$CUSTID$" {
			detail.VarValue = artInfo.CustArtId
		} else if detail.VarName == "$ORDERID$" {
			detail.VarValue = entity.SerialOrderId
		}

		err = detailDao.InsertOne(detail)
		if err != nil {
			session.Rollback()
			return err
		}
	}
	session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.DeleteOne
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) DeleteOne(user *models.Usertab, recNr int) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "DeleteOneReclinerReclst", "删除一个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(recNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(recNr)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.SelectOne
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) SelectOne(user *models.Usertab, recNr int) (*model.ReclinerReclst, error) {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "SelectOneReclinerReclst", "查询一个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(recNr)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.UpdateOne
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) UpdateOne(user *models.Usertab, entity *model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "UpdateOneReclinerReclst", "修改一个ReclinerReclst")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.Insert
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) Insert(user *models.Usertab, entities *[]model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "InsertReclinerReclst", "插入多个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.RecNr)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
	}

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.Delete
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) Delete(user *models.Usertab, entities *[]model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "DeleteReclinerReclst", "删除多个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ReclinerReclstService.Select
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) Select(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "SelectReclinerReclst", "查询ReclinerReclst")

	condition := DefaultConditionOfReclinerReclstAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewReclinerReclstDAO(session, user.Pid, 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_LF_MOM_BACKEND/services/qm/ReclinerReclstService.Update
 *
 ******************************************************************************/
func (impl *ReclinerReclstServiceImplement) Update(user *models.Usertab, entities *[]model.ReclinerReclst) error {

	grmi.Log(user, "/services/qm/implments/ReclinerReclst.service.impl.go", "UpdateReclinerReclst", "修改多个ReclinerReclst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewReclinerReclstDAO(session, user.Pid, user.Userid)

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

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