package logic

import (
	"app.yhyue.com/moapp/jybase/redis"
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	IC "jyBXBuyer/rpc/init"
	"jyBXBuyer/rpc/internal/svc"
	"jyBXBuyer/rpc/model"
	"jyBXBuyer/rpc/type/bxbuyer"
)

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

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

// 采购单位搜索
func (l *BuyerListLogic) BuyerList(in *bxbuyer.BuyerListReq) (*bxbuyer.BuyerListResp, error) {
	logx.Info("----:", model.CheckEmpty(in))
	resp := &bxbuyer.BuyerListResp{
		Data: &bxbuyer.BuyerData{},
	}
	if in.PageNum < 1 {
		in.PageNum = 1
	}
	if in.PageSize > 100 || in.PageSize < 1 {
		in.PageSize = 10
	}
	if in.PageSize > IC.C.BuyerSearchLimit {
		in.PageSize = IC.C.BuyerSearchLimit
	}
	// 判断数量
	// 采购单位搜索过来的 最多查BuyerSearchLimit条
	if in.PageNum*in.PageSize > IC.C.BuyerSearchLimit && (in.PageNum-1)*in.PageSize >= IC.C.BuyerSearchLimit {
		in.PageNum = IC.C.BuyerSearchLimit / in.PageSize
	}

	query, CountQuery := "", ""
	buyerNames := []string{}
	if model.CheckEmpty(in) {
		var isBool = true
		list := []*bxbuyer.BuyerList{} //100条数据
		bs, err := redis.GetBytes("other", fmt.Sprintf(model.P_redis_key))
		if err == nil && bs != nil && len(*bs) > 0 {
			isBool = false
			if err := json.Unmarshal(*bs, &list); err != nil {
				isBool = true
				logx.Info("获取redis缓存，序列化异常")
			} else {
				if len(list) > 0 {
					// 根据页码返回数据
					start := in.PageSize * (in.PageNum - 1)
					end := in.PageSize * in.PageNum
					count := len(list)
					resp.Data.Count = int64(count)
					if end > int64(len(list)) {
						end = int64(len(list))
					}
					resp.Data.List = list[start:end]
					for i := 0; i < len(resp.Data.List); i++ {
						buyerNames = append(buyerNames, resp.Data.List[i].Buyer)
					}
				} else {
					isBool = true
				}
			}
		}
		if isBool {
			query = model.BuyerListRedisCacheQuery()
			buyerNames, resp = model.BuyerListRedisCache(query, in)

		}
	} else {
		query, CountQuery = model.BuyerListQuery(in)
		logx.Info("query:", query)
		buyerNames, resp = model.GetBuyerList(query, CountQuery, false) // 查询数据
	}
	if len(resp.Data.List) > 0 && (in.UserId != "" || in.EntUserId != "") {
		model.SupplyFollowInfo(in, buyerNames, resp)
	}
	if len(resp.Data.List) > 0 {
		if in.PageNum*in.PageSize > IC.C.BuyerSearchLimit && (in.PageNum-1)*in.PageSize < IC.C.BuyerSearchLimit {
			end := IC.C.BuyerSearchLimit - (in.PageNum-1)*in.PageSize
			if len(resp.Data.List) > int(end) {
				resp.Data.List = resp.Data.List[:end]
			}
		}
	}
	if resp.Data.Count > IC.C.BuyerSearchLimit {
		resp.Data.Count = IC.C.BuyerSearchLimit
	}
	return resp, nil
}
