package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	se "app.yhyue.com/moapp/jybase/encrypt"
	"context"
	"fmt"
	IC "jyBXBase/rpc/init"
	"strconv"

	"jyBXBase/rpc/bxbase"
	"jyBXBase/rpc/internal/svc"

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

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

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

// 获取标签
func (l *GetLabelActionLogic) GetLabelAction(in *bxbase.GetLabelActionReq) (*bxbase.GetLabelActionRes, error) {
	//获取标签数量
	var resp bxbase.GetLabelActionRes
	labcount := map[string]int{}
	selectsql := fmt.Sprintf(`SELECT a.labelname,COUNT(1) count,a.id 
				FROM %s a INNER JOIN %s b ON 
				FIND_IN_SET(a.id,b.labelid) 
				WHERE b.userid =? 
				GROUP BY a.labelname,a.id`, "bdlabel", "bdcollection")
	if data := *IC.MainMysql.SelectBySql(selectsql, in.UserId); len(data) > 0 {
		for _, v := range data {
			labcount[strconv.FormatInt(v["id"].(int64), 10)] = common.IntAll(v["count"])
		}
	}
	data := []*bxbase.LabelByUser{}
	if labArr := IC.MainMysql.SelectBySql(fmt.Sprintf("select * from %s where  userid = ?", "bdlabel"), in.UserId); labArr != nil && len(*labArr) > 0 {
		for _, v := range *labArr {
			l := bxbase.LabelByUser{}
			lid := strconv.FormatInt(v["id"].(int64), 10)
			l.Lid = se.SE.EncodeString(lid)
			l.Lname = common.ObjToString(v["labelname"])
			l.Lcount = int64(labcount[lid])
			data = append(data, &l)
		}
	}
	resp.Labels = data
	return &resp, nil
}
