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

package implments

import (
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/jit"
	baseModel "LAPP_ACURA_MOM_BACKEND/models/base"
	model "LAPP_ACURA_MOM_BACKEND/models/jit"
	"fmt"
	"github.com/go-xorm/xorm"
	"xorm.io/core"
)

/******************************************************************************
 *
 * @Struct Name              : PackOrderItemLstDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : PackOrderItemLst的数据访问对象实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
type PackOrderItemLstDAOImplement struct {
	session *xorm.Session
	meta    *grmi.Entity
	plantNr int
	userid  string
}

/******************************************************************************
 *
 * @Function Name            : NewPackOrderItemLstDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个PackOrderItemLstDAOImplement实例
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 基本主键
 *
 * @Return Value             : PackOrderItemLstDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-19 10:26:40
 *
 ******************************************************************************/
func NewPackOrderItemLstDAOImplement(session *xorm.Session, plantNr int, userid string) *PackOrderItemLstDAOImplement {
	return &PackOrderItemLstDAOImplement{session, &meta.PackOrderItemLst, plantNr, userid}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.InsertOne
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) InsertOne(entity *model.PackOrderItemLst) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Insert(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.DeleteOne
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) DeleteOne(packOrderId string, pos int) error {
	_, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, packOrderId, pos}).Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.SelectOne
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) SelectOne(packOrderId string, pos int) (*model.PackOrderItemLst, error) {
	var data model.PackOrderItemLst
	ok, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, packOrderId, pos}).Get(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	if !ok {
		return nil, nil
	}
	return &data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) UpdateOne(entity *model.PackOrderItemLst) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.Insert
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) Insert(entities *[]model.PackOrderItemLst) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]
		entity.PlantNr = impl.plantNr
		entity.LastUser = impl.userid
	}
	_, err := impl.session.Table(impl.meta.TableName).Insert(entities)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.Delete
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) Delete(entities *[]model.PackOrderItemLst) error {
	for _, entity := range *entities {
		entity.PlantNr = impl.plantNr
		_, err := impl.session.Table(impl.meta.TableName).ID(entity.GetKey()).Delete(impl.meta.Indicator)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.DeleteWhere
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) DeleteWhere(predicates []grmi.Predicate) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.PackOrderItemLst_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	_, err := session.Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.Select
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) Select(predicates []grmi.Predicate, orderByFields []grmi.Field) ([]model.PackOrderItemLst, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.PackOrderItemLst_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	session = session.OrderBy(meta.PackOrderItemLst_PlantNr.ColumnName)
	if orderByFields != nil {
		for _, field := range orderByFields {
			session = session.OrderBy(field.ColumnName)
		}
	}

	data := make([]model.PackOrderItemLst, 0, 10)
	err := session.Find(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	return data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.SelectAndPaging
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) SelectAndPaging(paging *grmi.Paging, predicates []grmi.Predicate, orderByFields []grmi.Field) (grmi.PagingResult, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.PackOrderItemLst_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	count, err := session.Count(impl.meta.Indicator)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}

	orderBy := " order by " + meta.PackOrderItemLst_PlantNr.ColumnName
	if orderByFields != nil {
		for _, field := range orderByFields {
			if orderBy == " order by " {
				orderBy += field.ColumnName
			} else {
				orderBy += ", " + field.ColumnName
			}
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.PackOrderItemLst, 0, 10)
	where = " where " + where
	err = impl.session.Table(impl.meta.TableName).SQL("select * from ["+impl.meta.TableName+"]"+where+orderBy+" offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return grmi.PagingResult{Records: data, Count: count, PageNumber: paging.Number, PageSize: paging.Size}, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.Update
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) Update(entities *[]model.PackOrderItemLst) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]
		entity.PlantNr = impl.plantNr
		entity.LastUser = impl.userid
		_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) UpdateWhere(predicates []grmi.Predicate, entity *model.PackOrderItemLst, columns ...string) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.PackOrderItemLst_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	columns = append(columns, meta.PackOrderItemLst_LastUser.Name)
	entity.LastUser = impl.userid
	_, err := session.Cols(columns...).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) SelectActivePackOrder(artId string) ([]model.PackOrder, error) {
	result := make([]model.PackOrder, 0, 1)
	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.PackOrderItemLst_PlantNr.ColumnName)
	orderCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.PackOrderItemLst_PlantNr.ColumnName,
		meta.PackOrder_PlantNr.ColumnName,
		meta.PackOrderItemLst_PackOrderId.ColumnName,
		meta.PackOrder_PackOrderId.ColumnName)
	statusCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.PackOrder_PlantNr.ColumnName,
		meta.PackOrderStatus_PlantNr.ColumnName,
		meta.PackOrder_PackOrderId.ColumnName,
		meta.PackOrderStatus_PackOrderId.ColumnName)
	session := impl.session.Table(impl.meta.TableName).Join("LEFT", meta.PackOrder.TableName, orderCondition)
	session = session.Join("LEFT", meta.PackOrderStatus.TableName, statusCondition)
	where += fmt.Sprintf(" and %s = ? and %s = ? ",
		meta.PackOrderItemLst_PartId.ColumnName,
		meta.PackOrderStatus_Status.ColumnName)
	parameters = append(parameters, artId, baseModel.WO_STATUS_RELEASED)
	err := session.Where(where, parameters...).OrderBy(meta.PackOrder_PackOrderId.ColumnName).Find(&result)
	return result, err
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/jit/PackOrderItemLstDAO.GetMaxPost
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) GetMaxPost(packOrderId string) (int, error) {

	parameters := []interface{}{impl.plantNr, packOrderId}
	where := fmt.Sprintf("%s = ? and %s = ?", meta.PackOrderItemLst_PlantNr.ColumnName, meta.PackOrderItemLst_PackOrderId.ColumnName)
	var data model.PackOrderItemLst
	ok, err := impl.session.Table(impl.meta.TableName).Where(where, parameters...).Desc(meta.PackOrderItemLst_Pos.SortColumnName).Get(&data)
	if err != nil {
		return 0, err
	}
	if !ok {
		return 0, nil
	}
	return data.Pos, nil
}

// GetUnFlushBackData 获取回冲包装单数据
func (impl *PackOrderItemLstDAOImplement) GetUnFlushBackData(now string) ([]model.BackFlushData, error) {
	result := make([]model.BackFlushData, 0)
	sql := `SELECT JIT_PackOrder.*, status.*, JIT_PackOrderItemLst.*, OM_SerialOrder.* FROM ( (SELECT * FROM JIT_PackOrderStatus WHERE Status = 80 AND BackflushedToggle = 0 AND LastModify < ? ) status INNER JOIN JIT_PackOrder ON status.PlantNr = JIT_PackOrder.PlantNr AND status.PackOrderId = JIT_PackOrder.PackOrderId LEFT JOIN JIT_PackOrderItemLst ON status.PlantNr = JIT_PackOrderItemLst.PlantNr AND status.PackOrderId = JIT_PackOrderItemLst.PackOrderId LEFT JOIN OM_SerialOrder ON JIT_PackOrderItemLst.PlantNr = OM_SerialOrder.PlantNr AND JIT_PackOrderItemLst.SerialOrderId = OM_SerialOrder.SerialOrderId ) WHERE OM_SerialOrder.BackFlushFlag = 0 Order By JIT_PackOrderItemLst.PackOrderId, JIT_PackOrderItemLst.Pos;`
	err := impl.session.Table(impl.meta.TableName).SQL(sql, now).Find(&result)
	return result, err
}

// SelectPackOrderByBarcode 通过工单条码查询包装单
func (impl *PackOrderItemLstDAOImplement) SelectPackOrderByBarcode(paging *grmi.Paging, barcode string) (grmi.PagingResult, error) {
	condition := fmt.Sprintf("%s = %s and %s = %s",
		meta.PackOrder_PlantNr.ColumnName,
		meta.PackOrderItemLst_PlantNr.ColumnName,
		meta.PackOrder_PackOrderId.ColumnName,
		meta.PackOrderItemLst_PackOrderId.ColumnName)
	parameters := []interface{}{impl.plantNr, barcode}
	where := fmt.Sprintf("%s = ? and %s = ?", meta.PackOrderItemLst_PlantNr.ColumnName, meta.PackOrderItemLst_SerialOrderId.ColumnName)
	var data []model.PackOrder
	count, err := impl.session.Table(impl.meta.TableName).Join("LEFT", meta.PackOrder.TableName, condition).Where(where, parameters...).Count(impl.meta.Indicator)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	joinStr := fmt.Sprintf(" left join %s on %s",
		meta.PackOrder.TableName, condition)
	parameters = append(parameters, paging.Offset(), paging.Size)
	orderBy := " order by " + meta.PackOrderItemLst_PlantNr.ColumnName + " , " + meta.PackOrderItemLst_PackOrderId.SortColumnName
	where = " where " + where
	err = impl.session.Table(impl.meta.TableName).SQL("select * from ["+impl.meta.TableName+"]"+joinStr+where+orderBy+" offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return grmi.PagingResult{Records: data, Count: count, PageNumber: paging.Number, PageSize: paging.Size}, nil
}

// SelectShipOrderBySerialOrderId 通过工单ID查询发运单
func (impl *PackOrderItemLstDAOImplement) SelectShipOrderBySerialOrderId(serialOrderId string) ([]interface{}, error) {
	parameters := []interface{}{impl.plantNr, serialOrderId}
	where := fmt.Sprintf("%s = ? and %s = ?",
		meta.PackOrderItemLst_PlantNr.ColumnName,
		meta.PackOrderItemLst_SerialOrderId.ColumnName)
	condition := fmt.Sprintf("%s = %s and %s = %s",
		meta.ShipOrderDataLst_PlantNr.ColumnName,
		meta.PackOrderItemLst_PlantNr.ColumnName,
		meta.ShipOrderDataLst_PackOrderId.ColumnName,
		meta.PackOrderItemLst_PackOrderId.ColumnName)
	session := impl.session.Table(impl.meta.TableName).Join("LEFT", meta.ShipOrderDataLst.TableName, condition)
	var shipOrderIdLi []interface{}
	err := session.Where(where, parameters...).Cols(meta.ShipOrderDataLst_ShipOrderId.SortColumnName).Find(&shipOrderIdLi)
	return shipOrderIdLi, err
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/log/PackOrderItemlstDAO.SelectListByOrders
 *
 ******************************************************************************/
func (impl *PackOrderItemLstDAOImplement) SelectListByOrders(serialOrderIds []string) ([]model.PackOrderItemLst, error) {
	data := make([]model.PackOrderItemLst, 0)
	for _, serialOrderId := range serialOrderIds {
		oneInfo := model.PackOrderItemLst{}
		ok, err := impl.session.Table(impl.meta.TableName).Where("PlantNr = ? and Status = ? and SerialOrderId = ?", impl.plantNr, baseModel.PACK_STATUS_CLOSED, serialOrderId).Get(&oneInfo)
		if err != nil {
			return nil, grmi.NewDataBaseError(err)
		}
		if ok {
			data = append(data, oneInfo)
		}
	}

	return data, nil
}
