package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/encrypt"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	IC "jyBXSubscribe/rpc/init"
	"jyBXSubscribe/rpc/internal/svc"
	"jyBXSubscribe/rpc/model"
	"jyBXSubscribe/rpc/type/bxsubscribe"
	"jyBXSubscribe/rpc/util"
	"strings"
	"time"
)

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

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

// 推送页面筛选导出
func (l *ByPushHistoryLogic) ByPushHistory(in *bxsubscribe.SubscribeInfosReq) (*bxsubscribe.ByPushHistoryResp, error) {
	// todo: add your logic here and delete this line
	vipType := in.UserType
	//分发员工
	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:          1,                                  //当前页码
		PageSize:         20000,                              //每页多少条数据
		SelectTime:       in.SelectTime,                      //时间跨度
		Area:             in.Area,                            //省份
		City:             in.City,                            //城市
		Export:           true,
		Buyerclass:       in.BuyerClass, //采购单位类型
		Subtype:          in.Subtype,    //信息类型
		Subscopeclass:    in.Industry,   //行业
		Key:              in.KeyWords,   //关键词
		Price:            in.Price,      //价格区间
		FileExists:       in.FileExists, //是否有附件
		EntId:            in.EntId,      //商机管理企业id
		EntUserId:        in.EntUserId,  //商机管理用户id
		DeptId:           in.DeptId,     //商机管理部门id
		IsRead:           in.IsRead,
		Source:           in.Source,
		Staffs:           staffIds,
		NewUserId:        in.NewUserId,
		BaseServiceMysql: IC.BaseServiceMysql,
		IsEnt:            in.IsEnt,
		UserType:         in.UserType,
		PositionType:     in.PositionType,
		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
			vipType = model.EntnicheFlag
		}
	}
	if in.UserType == model.EntnicheFlag {
		spqp.UserId = common.InterfaceToStr(spqp.EntUserId)
	}
	logx.Info("数据导出查询参数", in)
	if selectIds := strings.TrimSpace(in.SelectIds); selectIds != "" {
		spqp.SelectInfoIds = strings.Split(selectIds, ",")
	}
	_, _, list := model.NewSubscribePush(vipType).Datas(spqp)
	if list == nil || len(list) == 0 {
		return &bxsubscribe.ByPushHistoryResp{
			ErrorCode: 1,
			ErrorMsg:  "未查询到数据",
		}, nil
	}
	ids := make([]string, 0, len(list))
	keyWords := make([]string, 0, len(list))
	listMap := make(map[string]string)
	//去重 防止list有重复数据
	for _, pushData := range list {
		if pushData.XId != "" {
			listMap[pushData.XId] = strings.Join(pushData.MatchKeys, ",")
		}
	}
	logx.Info("数据导出搜索条数与去重后对比+++++++++++++", len(list), len(listMap))
	//获取id与对应关键词
	for k, v := range listMap {
		if xid := util.DecodeId(k); len(xid) > 0 {
			ids = append(ids, xid)
			keyWords = append(keyWords, v)
		}
	}
	saveData := map[string]interface{}{
		"s_userid":     in.UserId,
		"comeinfrom":   "pushHistory",
		"comeintime":   time.Now().Unix(),
		"selectIds":    ids,
		"pushKeyWords": keyWords,
	}
	_id := IC.Mgo.Save("export_search", saveData)
	if _id == "" {
		return &bxsubscribe.ByPushHistoryResp{
			ErrorCode: 1,
			ErrorMsg:  "创建导出异常",
		}, nil
	}
	return &bxsubscribe.ByPushHistoryResp{
		Data: encrypt.SE.Encode2Hex(_id),
	}, nil
}
