package es

import (
	"fmt"
	"strconv"
	"strings"

	elastic "app.yhyue.com/moapp/jybase/es"
	"log"
)

const (
	queryBoolMustTermDomain = `{"bool": {"must": [{ "term": {"bid_field": "%s" }}]}}` // 领域化数据类型
	multiMatch              = `{"multi_match": {"query": "%s","type": "phrase", "fields": [%s]}}`
	query                   = `{"query":{"bool":{"must":[%s],"must_not":[%s]}}}`
	queryBoolShould         = `{"bool":{"should":[%s],"minimum_should_match": 1}}`
	queryBoolMustBoolShould = `{"bool":{"must":[{"range":{"bidamount":{%s}}}]}},{"bool":{"must":[{"range":{"budget":{%s}}}],"must_not":[{"range":{"bidamount":{"gte":-1}}}]}}`
	queryBoolMust           = `{"bool":{"must":[{"terms":{"s_subscopeclass":[%s]}}]}}`
	queryBoolMustTerm       = `{"bool": {"must": [{ "term": {"isValidFile": %t }}]}}`
	queryExists             = `{"constant_score":{"filter":{"exists":{"field":"%s"}}}}`
	gte                     = `"gte": %s`
	lte                     = `"lte": %s`
	HighlightStr            = `"%s": {"fragment_size": %d,"number_of_fragments": 1}`
	HL                      = `"highlight": {"pre_tags": [""],"post_tags": [""],"fields": {%s}}`
	INDEX                   = "bidding"
	TYPE                    = "bidding"
	BidSearchSort           = `{"dataweight":-1,"publishtime":-1}`
	BidSearchFieldBase      = `"_id","title","publishtime","dataweight","toptype","subtype","type","area","city","s_subscopeclass","bidamount","budget","buyerclass","spidercode","site","buyer","winner","bidopentime"` //搜索列表基础字段
	BidSearchFieldOfVip     = BidSearchFieldBase + `,"buyertel","buyerperson","agency","agencytel","agencyperson","s_winner","winnertel","winnerperson","signendtime","bidendtime","projectinfo","entidlist"`            //付费列表字段
	BidSearchFieldFile      = `,"isValidFile"`                                                                                                                                                                           //根据配置开关 选择是否显示 是否有附件提示，IC.C.FileSignBool
	BidSearchDomainField    = BidSearchFieldOfVip + `,"purchasing"`                                                                                                                                                      //领域数据字段基本字段
	//DefaultFields       = `"title"`
	IndexProjectSet = "projectset" // 项目信息es index
	TypeProjectSet  = "projectset" // 项目信息es type                                                                                                                                                                                                  //最新招标信息
)

var (
	SR = strings.Replace
	//信息类型 一级类型参数和数据类型转换
	topTypeMap = map[string]string{
		"招标预告":   "预告",
		"招标公告":   "招标",
		"招标结果":   "结果",
		"招标信用信息": "其它",
		"拟建项目":   "拟建",
		"采购意向":   "采购意向",
	}
)

type SearchByES struct {
	Index      string
	IType      string
	Query      string
	FindFields string
	Order      string
	Fields     string
	Start      int
	Limit      int
	Count      int
	HighLight  bool
}

// GetAllByNgramWithCount  获取es查询结果及总数量
func (e *SearchByES) GetAllByNgramWithCount() (int64, *[]map[string]interface{}) {
	if e.Query != "" {
		queryStr := e.Query
		if e.HighLight {
			var ws []string
			for _, w := range strings.Split(e.FindFields, ",") {
				ws = append(ws, fmt.Sprintf(HighlightStr, w, e.Count))
			}
			queryStr = queryStr[:len(queryStr)-1] + `,` + fmt.Sprintf(HL, strings.Join(ws, ",")) + `}`
		}
		if len(e.Fields) > 0 {
			queryStr = queryStr[:len(queryStr)-1] + `,"_source":[` + e.Fields + "]}"
		}
		if len(e.Order) > 0 {
			queryStr = queryStr[:len(queryStr)-1] + `,"sort":[` + SR(SR(SR(SR(e.Order, ",", "},{", -1), " ", "", -1), ":-1", `:"desc"`, -1), ":1", `:"asc"`, -1) + `]}`
		}
		if e.Start > -1 {
			queryStr = queryStr[:len(queryStr)-1] + `,"from":` + strconv.Itoa(e.Start) + `,"size":` + strconv.Itoa(e.Limit) + "}"
		}
		log.Println("queryStr:", queryStr)
		return elastic.GetWithCount(e.Index, e.IType, e.Query, queryStr)
	} else {
		return 0, nil
	}
}
