package label_tagging

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/label"
	"wechat-api/ent/labeltagging"
	"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 GetLabelTaggingListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetLabelTaggingListLogic) GetLabelTaggingList(req *types.LabelTaggingListReq) (resp *types.LabelTaggingListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.LabelTagging
	predicates = append(predicates, labeltagging.OrganizationIDEQ(organizationId))
	data, err := l.svcCtx.DB.LabelTagging.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

	resp = &types.LabelTaggingListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		var labelAddInfo []string
		labels, _ := l.svcCtx.DB.Label.Query().Where(label.IDIn(v.ActionLabelAdd...)).All(l.ctx)
		for _, l := range labels {
			labelAddInfo = append(labelAddInfo, l.Name)
		}
		resp.Data.Data = append(resp.Data.Data,
			types.LabelTaggingInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:         &v.Status,
				OrganizationId: &v.OrganizationID,
				Type:           &v.Type,
				Conditions:     v.Conditions,
				ActionLabelAdd: v.ActionLabelAdd,
				LabelAddInfo:   labelAddInfo,
				ActionLabelDel: v.ActionLabelDel,
			})
	}

	return resp, nil
}
