package logic

import (
	"context"
	IC "jyBXSubscribe/rpc/init"
	"jyBXSubscribe/rpc/internal/svc"
	"jyBXSubscribe/rpc/model"
	"jyBXSubscribe/rpc/type/bxsubscribe"
	"strconv"
	"strings"
	"time"

	"app.yhyue.com/moapp/jybase/common"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

// 获取订阅推送列表
func (l *GetSubListLogic) GetSubList(in *bxsubscribe.SubscribeInfosReq) (*bxsubscribe.SubscribeInfosResp, error) {
	start := time.Now().Unix()
	//1、推送信息已读标识
	//超级订阅 i_apppushunread=0
	//大会员 i_member_apppushunread=0
	//商机管理 i_entniche_apppushunread=0
	if in.IsEnt {
		in.UserType = model.EntnicheFlag
	}
	if in.PageNum == 1 {
		go model.UpdateUserPushUnread(in.UserId, in.UserType)
	}
	accountId, _ := strconv.ParseInt(in.AccountId, 10, 64)
	positionId, _ := strconv.ParseInt(in.PositionId, 10, 64)
	entId, _ := strconv.ParseInt(in.EntId, 10, 64)
	//判断用户身份
	userInfo := IC.Middleground.PowerCheckCenter.Check("10000", in.MgoUserId, in.NewUserId, accountId, entId, in.PositionType, positionId)
	//是否是付费用户
	isPay := !userInfo.Free.IsFree
	isPayUser := false

	//付费用户
	if in.UserType != "fType" && isPay {
		isPayUser = true
	}
	//分发员工
	var staffIds []string
	for _, staffId := range strings.Split(in.Staffs, ",") {
		if staffId != "" {
			staffIds = append(staffIds, staffId)
		}
	}
	spqp := &model.SubPushQueryParam{
		Mgo_bidding:      IC.MgoBidding,                      //mongo
		Bidding:          IC.DB.Mongo.Bidding.Collection,     //招标信息 表
		Bidding_back:     IC.DB.Mongo.Bidding.CollectionBack, //招标信息备份数据 表名
		UserId:           in.UserId,                          //用户id
		PageNum:          int(in.PageNum),                    //当前页码
		PageSize:         int(in.PageSize),                   //每页多少条数据
		SelectTime:       in.SelectTime,                      //时间跨度
		Area:             in.Area,                            //省份
		City:             in.City,                            //城市
		Buyerclass:       in.BuyerClass,                      //采购单位类型
		Subtype:          in.Subtype,                         //信息类型
		Subscopeclass:    in.Industry,                        //行业
		Key:              in.KeyWords,                        //关键词
		Price:            in.Price,                           //价格区间
		FileExists:       in.FileExists,                      //是否有附件
		IsRead:           in.IsRead,
		Source:           in.Source,
		Staffs:           staffIds,
		EntId:            in.EntId,     //商机管理企业id
		EntUserId:        in.EntUserId, //商机管理用户id
		DeptId:           in.DeptId,    //商机管理部门id
		NewUserId:        in.NewUserId,
		BaseServiceMysql: IC.BaseServiceMysql,
		IsEnt:            in.IsEnt,
		BuySubject:       0,
		UserType:         in.UserType,
		PositionType:     in.PositionType,
		IsPayUser:        isPayUser,
		NotReturnCount:   in.NotReturnCount,
		Item:             in.Item,
	}
	//主体处理(fType：普通用户；vType：超级订阅用户；mType：大会员用户；eType：商机管理用户)
	if in.UserType == model.MemberFlag || in.UserType == model.SubVipFlag || in.UserType == model.SubFreeFlag {
		if in.PositionType == 1 {
			in.UserType = model.EntnicheFlag
		}
	}
	if in.UserType == model.EntnicheFlag {
		spqp.UserId = common.InterfaceToStr(spqp.EntUserId)
	}
	hasNextPage, total, list := model.NewSubscribePush(in.UserType).Datas(spqp)
	start1 := time.Now().Unix()
	logx.Info("1、查询数据用户", start1-start)
	/*
	 *无推送记录生成推送记录
	 *免费用户默认推送50条
	 *大会员、新版商机管理、超级订阅用户 默认推送1000条记录
	 */

	if in.PageNum == 1 && spqp.IsEmpty() && len(list) == 0 && in.IsEnt == false {
		hasNextPage, total, list = model.NewSubscribePush(in.UserType).DefaultDatas(spqp)
	}
	start2 := time.Now().Unix()
	logx.Info("2、查询数据用户", start2-start1)
	//查询是否收藏
	model.NewSubscribePush(in.UserType).MakeCollection(in.UserId, list)
	start3 := time.Now().Unix()
	logx.Info("3、查询数据用户", start3-start2)
	logx.Info("总共查询数据用户", start3-start)
	return &bxsubscribe.SubscribeInfosResp{
		Data: &bxsubscribe.SubscribeData{
			List:        list,
			Count:       total,
			HasNextPage: hasNextPage,
		},
	}, nil
}
