package es

import (
	elastic "app.yhyue.com/moapp/jybase/es"
	"fmt"
	"strings"
	"time"
)

// 项目信息 项目id
func GetProjectInfo(id string) map[string]interface{} {
	projectInfos := elastic.GetById(IndexProjectSet, TypeProjectSet, id)
	if projectInfos != nil && len(*projectInfos) > 0 {
		return (*projectInfos)[0]
	}
	return nil
}

// 招标信息 招标信息id
func GetBiddingInfo(id string) map[string]interface{} {
	biddingInfos := elastic.GetById(INDEX, TYPE, id)
	if biddingInfos != nil && len(*biddingInfos) > 0 {
		return (*biddingInfos)[0]
	}
	return nil
}

// GetValidProjectByInfoId 根据查询有效的参标项目id(未到开标时间及开标时间不存在的)
func GetValidProjectByInfoId(infoIds []string) *[]map[string]interface{} {
	if len(infoIds) == 0 {
		return nil
	}
	nowTime := time.Now().Unix()
	query := `{"_source":["_id","list.infoid"],"query": {"bool": {"must": [{"terms": {"list.infoid": ["` + strings.Join(infoIds, "\",\"") + `"]}},
                {"bool": {"should": [{"range": {"bidopentime": {"gte": ` + fmt.Sprint(nowTime) + `}}},
               {"bool": {"must_not": [{"constant_score": {"filter": {"exists": {"field": "bidopentime"
                        }
                    }
                }
            }
]}}] }},
{"bool": {"should": [{"range": {"bidendtime": {"gte": ` + fmt.Sprint(nowTime) + `}}},
        {
    "bool": {
        "must_not": [
            {
                "constant_score": {
                    "filter": {
                        "exists": {
                            "field": "bidendtime"
                        }
                    }
                }
            }
        ]
    }
}
] }}]}},
"size": 500
}`

	projectResult := elastic.Get(IndexProjectSet, TypeProjectSet, query)
	return projectResult

}

// GetProjectByInfoId 根据信息id查询项目id
func GetProjectByInfoId(infoIds []string) *[]map[string]interface{} {
	if len(infoIds) == 0 {
		return nil
	}
	query := `{"_source":["_id","list.infoid","ids","bidopentime","bidendtime"],"query":{"bool":{"must":[{"terms":{"list.infoid":["` + strings.Join(infoIds, "\",\"") + `"]}}]}}}`

	projectResult := elastic.Get(IndexProjectSet, TypeProjectSet, query)
	return projectResult

}

// GetBidInfoByPId 根据项目id查询招标信息id
func GetBidInfoByPId(infoId string) *[]map[string]interface{} {
	query := `{
				  "query": {
					"bool": {
					  "must": [
						{
						  "term": {
							"projectset.id": "` + infoId + `"
						  }
						}
					  ]
					}
				  },
				  "from": 0,
				  "size": 1,
				  "sort": [],
				  "facets": {}
				}`

	projectResult := elastic.Get(IndexProjectSet, TypeProjectSet, query)
	return projectResult

}
