search_table_data_logic.go 2.4 KB
package table

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/types"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway/bytelib"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/xerr"
	"sort"
	"strings"
)

type SearchTableDataLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSearchTableDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchTableDataLogic {
	return &SearchTableDataLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SearchTableDataLogic) SearchTableData(req *types.SearchTableDataRequest) (resp interface{}, err error) {
	if req.ObjectId == 0 {
		resp = map[string]interface{}{
			"objectId": 0,
			"fields":   nil,
			"total":    0,
			"data":     make([]string, 0),
		}
		return
	}
	tableDataPreviewRequest := &bytelib.TableDataPreviewRequest{
		Token:      req.Token,
		ObjectType: bytelib.ObjectMetaTable,
		ObjectId:   int64(req.ObjectId),
		Where:      newWhere(req.Condition).WithPageSize(req.PageNumber, req.PageSize),
	}
	var (
		response bytelib.TablePreviewResponse
	)
	response, err = l.svcCtx.ByteMetadataService.TableDataPreview(l.ctx, tableDataPreviewRequest)
	if err != nil {
		return resp, xerr.NewErr(err)
	}
	//排序
	orderField := ""
	orderBy := ""
	for _, item := range req.Condition {
		if item.Order != "" {
			orderField = item.FieldName
			orderBy = item.Order
			break
		}
	}
	sort.Slice(response.Grid.List, func(i, j int) bool {
		if _, ok := response.Grid.List[i][orderField]; ok {
			if _, ok := response.Grid.List[j][orderField]; ok {
				if strings.ToLower(orderBy) == "asc" {
					return response.Grid.List[i][orderField] < response.Grid.List[j][orderField]
				} else {
					return response.Grid.List[i][orderField] > response.Grid.List[j][orderField]
				}
			}
		}
		return true
	})
	resp = map[string]interface{}{
		"objectId": response.ObjectId,
		"fields":   removeIdField(response.Fields),
		"total":    response.Grid.Total,
		"data":     response.Grid.List,
	}
	return
}

func removeIdField(fields []*bytelib.Field) []*bytelib.Field {
	var result = make([]*bytelib.Field, 0)
	for _, f := range fields {
		if f.SQLName == "id" {
			continue
		}
		result = append(result, f)
	}
	return result
}