package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"jyBXBase/rpc/bxbase"
	IC "jyBXBase/rpc/init"
	"jyBXBase/rpc/internal/svc"
	"log"
	"strconv"
	"strings"
	"time"
)

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

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

// 获取收藏列表
func (l *ShowSearchLogic) ShowSearch(in *bxbase.ShowSearchReq) (res *bxbase.ShowSearchRes, err error) {
	var (
		data  []*bxbase.ListSearchRes
		isOld bool
	)
	log.Println("获取搜索列表:", in)
	res = new(bxbase.ShowSearchRes)
	if in.UserId == "" {
		res.ErrCode = -1
		res.ErrMsg = "用户未登录"
		return res, nil
	}
	query := map[string]interface{}{
		"user_id": in.UserId,
		"type":    in.Type,
	}
	allSearch, b := IC.Mgo.Find("search_condition", query, `{"creation_time":-1}`, "", false, -1, -1)
	if !b {
		res.ErrCode = -1
		res.ErrMsg = "用户搜索信息查询失败"
		return res, nil
	}
	//需判断新老用户
	user := IC.Compatible.Select(in.UserId, `{"i_member_status":1,"i_vip_status":1,"s_m_phone":1,"s_phone":1,"o_vipjy":1,"l_registedate":1}`)
	if user == nil || len(*user) == 0 {
		res.ErrCode = -1
		res.ErrMsg = "用户信息查询失败"
		return res, nil
	}
	registedate, _ := (*user)["l_registedate"].(int64)
	isOld = registedate != 0 && registedate < IC.C.BidSearchOldUserLimit
	if allSearch != nil {
		for _, vlu := range *allSearch {
			var listSearch bxbase.ListSearchRes
			listSearch.Id = common.InterfaceToStr(vlu["_id"])
			listSearch.Searchvalue = common.InterfaceToStr(vlu["keywords"])
			//PC端保存带时间范围的刷选条件时，到期时间选择18号，时间参数为18号0点，正常应该是18号23点59分59秒
			//现对老数据进行处理
			publishTime := common.InterfaceToStr(vlu["publish_time"])
			if publishTime != "" && strings.Contains(publishTime, "_") {
				publishTimeStart := strings.Split(publishTime, "_")[0]
				if publishTimeEnd := strings.Split(publishTime, "_")[1]; publishTimeEnd != "" {
					if endTimeInt, err := strconv.ParseInt(publishTimeEnd, 10, 64); err == nil {
						endTimeUnix := time.Unix(endTimeInt, 0)
						endTimeInt = time.Date(endTimeUnix.Year(), endTimeUnix.Month(), endTimeUnix.Day(), 23, 59, 59, 59, time.Local).Unix()
						publishTime = fmt.Sprintf("%s_%d", publishTimeStart, endTimeInt)
					}
				}
			}
			listSearch.Publishtime = publishTime
			listSearch.Area = common.InterfaceToStr(vlu["area"])
			listSearch.City = common.InterfaceToStr(vlu["city"])
			listSearch.Subtype = common.InterfaceToStr(vlu["subtype"])
			listSearch.Minprice = common.InterfaceToStr(vlu["min_price"])
			listSearch.Maxprice = common.InterfaceToStr(vlu["max_price"])
			listSearch.Industry = common.InterfaceToStr(vlu["industry"])
			listSearch.SelectType = common.InterfaceToStr(vlu["select_type"])
			listSearch.Buyerclass = common.InterfaceToStr(vlu["buyer_class"])
			listSearch.Buyertel = common.InterfaceToStr(vlu["buyer_tel"])
			listSearch.Winnertel = common.InterfaceToStr(vlu["winner_tel"])
			listSearch.FileExists = common.InterfaceToStr(vlu["file_exists"])
			listSearch.Notkey = common.InterfaceToStr(vlu["not_key"])
			listSearch.Tabularflag = common.InterfaceToStr(vlu["tabular_flag"])
			listSearch.SearchGroup = common.Int64All(vlu["searchGroup"])
			listSearch.SearchMode = common.Int64All(vlu["searchMode"])
			listSearch.WordsMode = common.Int64All(vlu["wordsMode"])
			listSearch.AdditionalWords = common.InterfaceToStr(vlu["additionalWords"])
			//ppa,buyer,winner,agency
			if SelectCheck(listSearch.SelectType, isOld) || listSearch.City != "" || listSearch.Notkey != "" ||
				(listSearch.Publishtime != "lately-7" && listSearch.Publishtime != "lately-30" && listSearch.Publishtime != "thisyear") ||
				listSearch.Winnertel != "" || listSearch.Buyertel != "" || listSearch.Buyerclass != "" {
				listSearch.IsPay = true
			}
			data = append(data, &listSearch)
		}
	}
	res.Data = data
	return res, nil
}

func SelectCheck(v string, isOld bool) bool {
	vs := strings.Split(v, ",")
	for _, v1 := range vs {
		if v1 != "content" && v1 != "file" && v1 != "title" {
			//老用户可以选用中标企业
			if isOld && v1 == "winner" {
				continue
			} else {
				return true
			}
		}
	}
	return false
}
