package logic

import (
	se "app.yhyue.com/moapp/jybase/encrypt"
	"context"
	"fmt"
	"jyBXBase/rpc/bxbase"
	IC "jyBXBase/rpc/init"
	"jyBXBase/rpc/internal/svc"
	"log"
	"strconv"
	"time"

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

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

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

// 新增标签
func (l *AddlabelLogic) Addlabel(in *bxbase.AddlabelReq) (*bxbase.AddlabelRes, error) {
	userid := in.UserId
	var resp bxbase.AddlabelRes
	if in.Name == "" {
		return &bxbase.AddlabelRes{
			ErrCode: -1,
			ErrMsg:  "未传入名字",
		}, nil
	}
	//now := time.Now().Unix()
	if IC.MainMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where userid =?`, "bdlabel"), userid) >= 50 {
		return &bxbase.AddlabelRes{
			ErrCode: -1,
			ErrMsg:  "标签数量已达上限",
		}, nil
	}
	//是否有重名
	if labArr := IC.MainMysql.SelectBySql(fmt.Sprintf("select * from %s where labelname = ? and userid = ?", "bdlabel"), in.Name, userid); labArr != nil && len(*labArr) == 1 {
		return &bxbase.AddlabelRes{
			ErrCode: -1,
			ErrMsg:  "该标签已经存在",
		}, nil
	} else { //新增标签
		insertMap := map[string]interface{}{
			"userid":     userid,
			"labelname":  in.Name,
			"createdate": time.Now(),
		}
		if lid := IC.MainMysql.Insert("bdlabel", insertMap); lid > 0 {
			resp.Labid = se.SE.EncodeString(strconv.FormatInt(lid, 10))
			return &resp, nil
		} else {
			log.Println("新增标签失败 - name:", in.Name)
			resp.ErrMsg = "保存失败"
			resp.ErrCode = -1
			return &resp, nil
		}
	}
}
