package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	"context"
	IC "jyBXBase/rpc/init"
	util2 "jyBXBase/rpc/util"
	"log"
	"time"

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

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

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

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

// 招标信息收藏
func (l *BCActionLogic) BCAction(in *bxbase.BCActionReq) (*bxbase.LabelActionRes, error) {
	var (
		insertCollKey = []string{"userid", "bid", "buyerclass", "buyerinfo", "winnerinfo", "createdate"}
		//insertCollKey2 = []string{"userid", "bid", "labelid", "buyerclass", "buyerinfo", "winnerinfo", "createdate"}
	)
	var i = 0
	ok, msg := true, ""
	insertValue := []interface{}{}
	maxCount := 10
	isPay, _ := util2.Power(in.UserId)
	redisArr := []string{}
	if isPay {
		maxCount = 5000
	}
	//已收藏的次数
	collCount := IC.MainMysql.Count("bdcollection", map[string]interface{}{"userid": in.UserId})
	collMap := map[string]bool{}
	for _, v := range util2.IsCollByBids("", in.UserId) {
		collMap[v] = true
	}
	//格式化数据
	info := util2.FormatColl(in.Bids)
	for _, bd := range info {
		queryMap := map[string]interface{}{
			"bid":    util2.DecodeId(bd.Bid),
			"userid": in.UserId,
		}
		redisArr = append(redisArr, util2.DecodeId(bd.Bid))
		//移除收藏
		if in.Baction == "R" {
			if IC.MainMysql.Delete("bdcollection", queryMap) {
				i++
			} else {
				log.Printf("userid :%s,取消收藏失败 id : %s", in.UserId, util2.DecodeId(bd.Bid))
			}
		} else {
			//if db.Mysql.Count(db.DbConf.Bdcollection, queryMap) == 0 {
			if int(collCount) >= maxCount {
				ok, msg = false, common.If(isPay, "付费用户收藏已达上限", "免费用户收藏已达上限").(string)
				log.Printf("userid :%s,收藏失败 id : %s ，已收藏数量:%v ,上限数量:%v", in.UserId, util2.DecodeId(bd.Bid), collCount, maxCount)
			} else {
				if collMap[util2.DecodeId(bd.Bid)] {
					log.Printf("userid :%s,已收藏 id : %s", in.UserId, util2.DecodeId(bd.Bid))
				} else {
					insertValue = append(insertValue, in.UserId, util2.DecodeId(bd.Bid), util2.PushMapping.Buyerclass[bd.Buyerclass], bd.Buyerinfo, bd.Winnerinfo, time.Now().Format("2006-01-02 15:04:05"))
					collCount++
					i++
				}
			}
		}
	}
	//批量插入
	if len(insertValue)/len(insertCollKey) > 0 {
		x, _ := IC.MainMysql.InsertBatch("bdcollection", insertCollKey, insertValue)
		if x < 0 {
			log.Printf("userid :%s收藏失败", in.UserId)
		}
	}
	typ := "a" //新增
	if in.Baction == "R" {
		typ = "d" //删除
	}
	if bl := util2.UpdateCollListRedis(typ, in.UserId, redisArr); !bl { //更新redis
		log.Println("更新redis失败", in.UserId)
	}
	sta, _ := common.If(ok, i <= len(in.Bids), ok).(bool)

	return &bxbase.LabelActionRes{
		ErrMsg: msg,
		Status: sta,
	}, nil
}
