package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	IC "jyBXCore/api/init"
	"jyBXCore/api/internal/svc"
	"jyBXCore/api/internal/types"
	"jyBXCore/api/internal/util"
	"jyBXCore/rpc/type/bxcore"
	"log"
	"net/http"
	"strings"
	"time"

	"app.yhyue.com/moapp/jybase/common"
)

type SearchListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
	w      http.ResponseWriter
}

func NewSearchListLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request, w http.ResponseWriter) *SearchListLogic {
	return &SearchListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
		w:      w,
	}
}

func (l *SearchListLogic) SearchList(req *types.SearchReq) (resp *types.CommonResp, err error) {
	defer common.Catch()
	t := time.Now()
	limitFlag, isNew := util.GetFlag(l.r, l.w, req.UserId)
	res, err := l.svcCtx.BxCore.GetSearchList(l.ctx, &bxcore.SearchReq{
		AppId:           req.AppId,
		UserId:          req.UserId,
		Phone:           req.Phone,
		NewUserId:       req.NewUserId,
		EntId:           req.EntId,
		EntUserId:       req.EntUserId,
		PageNum:         req.PageNum,
		PageSize:        req.PageSize,
		Province:        req.Province,
		City:            req.City,
		Subtype:         req.Subtype,
		TopType:         req.TopType,
		PublishTime:     req.PublishTime,
		SelectType:      req.SelectType,
		Price:           req.Price,
		Industry:        req.Industry,
		BuyerClass:      req.BuyerClass,
		BuyerTel:        req.BuyerTel,
		WinnerTel:       req.WinnerTel,
		FileExists:      req.FileExists,
		SearchGroup:     req.SearchGroup,
		SearchMode:      req.SearchMode,
		WordsMode:       req.WordsMode,
		KeyWords:        req.KeyWords,
		AdditionalWords: req.AdditionalWords,
		ExclusionWords:  req.ExclusionWords,
		UserType:        req.UserType,
		Platform:        util.CheckPlatform(l.r),
		BidField:        req.BidField,
		PositionType:    req.PositionType,
		PositionId:      req.PositionId,
		AccountId:       req.AccountId,
		MgoUserId:       req.MgoUserId,
		LimitFlag:       limitFlag,
		IsNew:           isNew,
	})

	log.Println("请求接口耗时：", time.Since(t).Seconds())
	if err != nil {
		return &types.CommonResp{
			Err_code: res.ErrCode,
			Err_msg:  res.ErrMsg,
			Data:     nil,
		}, err
	}
	if req.UserId == "" {
		var data []map[string]interface{}
		detailMosaicTxt := IC.C.DetailMosaicTxt
		sm := common.StructToMapMore(IC.C.SearchMosaic)
		for _, v := range res.Data.List {
			d := common.StructToMapMore(v)
			for name, t1 := range sm {
				ts, _ := t1.(bool)
				if !ts {
					continue
				}
				d[name] = detailMosaicTxt
				//if v1, ok := d[name]; ok && v1 != "" && v1 != 0 && ts {
				//	d[name] = detailMosaicTxt
				//}
			}
			data = append(data, d)
		}
		dataAll := common.StructToMapMore(res.Data)
		dataAll["list"] = data
		return &types.CommonResp{
			Err_code: res.ErrCode,
			Err_msg:  res.ErrMsg,
			Data:     dataAll,
		}, nil
	}
	data := map[string]interface{}{
		"ip":                common.GetIp(l.r),
		"count":             res.Data.Count,
		"s_userid":          req.UserId,
		"platform":          strings.ToLower(util.CheckPlatform(l.r)),
		"source":            "超级搜索",
		"createtime":        time.Now().Unix(),
		"userAgent":         l.r.Header.Get("User-Agent"),
		"pagenum":           req.PageNum,
		"pagesize":          req.PageSize,
		"search_area":       req.Province,
		"search_city":       req.City,
		"search_subType":    req.Subtype,
		"search_topType":    req.TopType,
		"search_selectType": req.SelectType,
		"search_price":      req.Price,
		"search_industry":   req.Industry,
		"search_buyerClass": req.BuyerClass,
		"search_buyerTel":   req.BuyerTel,
		"search_winnerTel":  req.WinnerTel,
		"fileExists":        req.FileExists,
		"searchGroup": func(searchGroup int64) string {
			switch searchGroup {
			case 1:
				return "招标采购公告"
			case 2:
				return "超前项目"
			}
			return ""
		}(req.SearchGroup), //搜索分组：默认0：全部；1：招标采购公告；2：超前项目
		"searchMode":         common.If(req.SearchMode == 1, "模糊搜索", "精准搜索"), //搜索模式：0：精准搜索；1：模糊搜索
		"wordsMode":          common.If(req.WordsMode == 1, "包含任意", "包含所有"),  //搜索关键词模式；默认0：包含所有，1：包含任意
		"search_word":        req.KeyWords,
		"additionalWords":    req.AdditionalWords,
		"exclusionWords":     req.ExclusionWords,
		"search_publishtime": req.PublishTime,
	}
	if logId := IC.MgoLog.Save("jy_search_log", data); logId == "" {
		log.Println(fmt.Sprintf("保存搜索日志异常 %s", req.UserId))
	}
	return &types.CommonResp{
		Err_code: res.ErrCode,
		Err_msg:  res.ErrMsg,
		Data:     res.Data,
	}, nil
}
