package logic

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

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

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

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

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

// 标签新增或删除
func (l *LabelActionLogic) LabelAction(in *bxbase.LabelActionReq) (*bxbase.LabelActionRes, error) {
	//var resp bxbase.LabelActionRes
	var (
		//insertCollKey  = []string{"userid", "bid", "buyerclass", "buyerinfo", "winnerinfo", "createdate"}
		insertCollKey2 = []string{"userid", "bid", "labelid", "buyerclass", "buyerinfo", "winnerinfo", "createdate"}
	)

	ibool, ok, msg := true, true, ""
	redisArr := []string{}
	if in.Laction == "D" && in.Lids != "" {
		in.Lids = strings.Split(in.Lids, ",")[0]
		labid := se.SE.DecodeString(in.Lids)
		//收藏信息解绑标签成功
		deleteMap := map[string]interface{}{
			"userid": in.UserId,
			"id":     se.SE.DecodeString(in.Lids),
		}
		labBid := map[string]interface{}{}
		//查询出该标签下的三级页
		rdata := IC.MainMysql.SelectBySql(fmt.Sprintf(`select labelid,bid from %s where 
		FIND_IN_SET(?,labelid) and userid = ?`, "bdcollection"), labid, in.UserId)
		if rdata != nil && len(*rdata) > 0 {
			for _, v := range *rdata {
				bid_id := common.ObjToString(v["bid"])
				label_id := labid
				labBid[bid_id] = label_id
			}
		}
		//解绑标签
		index := 0
		for k, v := range labBid {
			if IC.MainMysql.UpdateOrDeleteBySql(`update bdcollection set labelid = 
				(select new.lab from 
					(SELECT TRIM(BOTH ',' FROM REPLACE(CONCAT(',',labelid,','),CONCAT(',',?,','),',')) lab
					 FROM bdcollection WHERE bid = ? and userid =? ) new
				)
				WHERE bid = ? and userid =?`, v, k, in.UserId, k, in.UserId) > -1 {
				index++
			}
		}
		if index == len(labBid) {
			ibool = IC.MainMysql.Delete("bdlabel", deleteMap)
		}
	} else {
		//标签名称不为空  标签id为空 == 新增标签；如果bids 收藏的招标信息id不为空则再进行绑定
		if in.Lname != "" && in.Lids == "" {
			//是否有重名
			if labArr := IC.MainMysql.SelectBySql(fmt.Sprintf("select * from %s where labelname = ? and userid = ?", "bdlabel"), in.Lname, in.UserId); labArr != nil && len(*labArr) == 1 {
				res := (*labArr)[0]
				in.Lids = se.SE.EncodeString(common.ObjToString(res["id"]))
				ibool = true
			} else { //新增标签
				insertMap := map[string]interface{}{
					"userid":     in.UserId,
					"labelname":  in.Lname,
					"createdate": time.Now().Format("2006-01-02 15:04:05"),
				}
				if lid := IC.MainMysql.Insert("bdlabel", insertMap); lid > 0 {
					in.Lids = se.SE.EncodeString(strconv.FormatInt(lid, 10))
					ibool = true
				} else {
					log.Println("新增标签失败 - name:", in.Lname)
				}
			}
		}
		//收藏招标信息
		if in.Lids != "" && len(in.Binfo) > 0 {
			//获取标签
			var lids = ""
			for _, lv := range strings.Split(in.Lids, ",") {
				if lids != "" {
					lids += "," + se.SE.DecodeString(lv)
					continue
				}
				lids += se.SE.DecodeString(lv)
			}
			//更新需要的参数
			updatesql := fmt.Sprintf("update %s set labelid=? where userid = ? and ", "bdcollection") //更新语句
			updateValue := []interface{}{lids, in.UserId}
			//新增需要的参数
			insertValue := []interface{}{}
			collMap := map[string]bool{} //获取用户收藏的列表
			for _, v := range util2.IsCollByBids("", in.UserId) {
				collMap[v] = true
			}
			//maxCount := config.BidCollConfig.FreeUserCollLimit
			maxCount := 50
			isPay, _ := util2.Power(in.UserId)
			if isPay {
				//maxCount = config.BidCollConfig.PayUserCollLimit
				maxCount = 50
			}
			//已收藏的次数
			collCount := len(collMap)
			var i = 0
			info := util2.FormatColl(in.Binfo)
			for _, bd := range info {
				if collMap[util2.DecodeId(bd.Bid)] {
					//更新
					if updatesql == fmt.Sprintf("update %s set labelid=? where userid = ? and ", "bdcollection") {
						updatesql += `( bid =? `
					} else {
						updatesql += `or bid =? `
					}
					updateValue = append(updateValue, util2.DecodeId(bd.Bid))
					i++
				} else {
					if 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 {
						i++
						//新增并绑定标签 "userid", "bid", "labelid", "buyerclass", "buyerinfo", "winnerinfo", "createdate"
						insertValue = append(insertValue, in.UserId, util2.DecodeId(bd.Bid), lids, util2.PushMapping.Buyerclass[bd.Buyerclass], bd.Buyerinfo, bd.Winnerinfo, time.Now().Format("2006-01-02 15:04:05"))
					}
				}
			}
			if len(updateValue) > 2 {
				updatesql += `)`
				log.Println("updatesql:", updatesql)
				_, errs := IC.MainMysql.ExecBySql(updatesql, updateValue...)
				if errs != nil {
					log.Println("更新、绑定标签失败", in.UserId, updateValue)
				}
			}
			if len(insertValue) > 0 {
				x, _ := IC.MainMysql.InsertBatch("bdcollection", insertCollKey2, insertValue)
				if x < 0 {
					log.Printf("userid:%s收藏失败", in.UserId)
				}
			}
			ibool = i == len(in.Binfo)
		}
	}
	if bl := util2.UpdateCollListRedis("a", in.UserId, redisArr); !bl {
		log.Println("更新redis失败", in.UserId)
	}
	sta, _ := common.If(ok, ibool, ok).(bool)
	return &bxbase.LabelActionRes{
		ErrMsg: msg,
		Status: sta,
	}, nil
}
