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 GetLabelBatchSelectListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetLabelBatchSelectListLogic) GetLabelBatchSelectList(req *types.LabelListReq) (resp *types.LabelBatchSelectListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.Label
	predicates = append(predicates, label.OrganizationIDEQ(organizationId))
	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)
	}
	var allId uint64 = 0
	allName := "全部"
	resp = &types.LabelBatchSelectListResp{}
	var contact []types.LabelSelectListInfo
	contact = append(contact,
		types.LabelSelectListInfo{
			Value: &allId,
			Label: &allName,
		})
	var group []types.LabelSelectListInfo
	resp.Msg = errormsg.Success

	for _, v := range data.List {
		if v.Type == 1 {
			contact = append(contact,
				types.LabelSelectListInfo{
					Value: &v.ID,
					Label: &v.Name,
				})
		} else {
			group = append(group,
				types.LabelSelectListInfo{
					Value: &v.ID,
					Label: &v.Name,
				})
		}
	}
	resp.Data.Contact = contact
	resp.Data.Group = group

	return resp, nil
}
