package admin_agent

import (
	"context"
	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentMembershipConfigListLogic) AdminGetAgentMembershipConfigList(req *types.AdminGetAgentMembershipConfigListReq) (resp *types.AdminGetAgentMembershipConfigListResp, err error) {
	builder := l.svcCtx.AgentMembershipConfigModel.SelectBuilder()
	if req.LevelName != nil && *req.LevelName != "" {
		builder = builder.Where(squirrel.Eq{"level_name": *req.LevelName})
	}
	list, total, err := l.svcCtx.AgentMembershipConfigModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, err
	}
	items := make([]types.AgentMembershipConfigListItem, 0, len(list))
	for _, v := range list {
		var item types.AgentMembershipConfigListItem
		if err := copier.Copy(&item, v); err != nil {
			l.Logger.Errorf("copy error: %v", err)
			continue
		}
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		items = append(items, item)
	}
	resp = &types.AdminGetAgentMembershipConfigListResp{
		Total: total,
		Items: items,
	}
	return
}
