package label

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/label"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetLabelSelectListLogic) GetLabelSelectList(req *types.LabelListReq) (*types.LabelSelectListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.Label
	predicates = append(predicates, label.OrganizationIDEQ(organizationId))
	if req.Type != nil {
		predicates = append(predicates, label.TypeEQ(*req.Type))
	}
	if req.Name != nil {
		predicates = append(predicates, label.NameContains(*req.Name))
	}
	if req.From != nil {
		predicates = append(predicates, label.FromEQ(*req.From))
	}
	if req.Mode != nil {
		predicates = append(predicates, label.ModeEQ(*req.Mode))
	}
	data, err := l.svcCtx.DB.Label.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.LabelSelectListResp{}
	resp.Msg = errormsg.Success

	for _, v := range data.List {
		resp.Data = append(resp.Data,
			types.LabelSelectListInfo{
				Value: &v.ID,
				Label: &v.Name,
			})
	}

	return resp, nil
}