package front

import (
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"math"
	mgo "mongodb"
	qu "qfw/util"
	"sort"
	"strconv"
	"strings"
	"util"
)

func (f *Front) RemarkList() {
	qu.Catch()
	pid := qu.ObjToString(f.GetString("pid"))
	tid := qu.ObjToString(f.GetString("tid"))
	sourceinfo := qu.ObjToString(f.GetString("s_sourceinfo"))
	if f.Method() == "POST" {
		//user := f.GetSession("user").(map[string]interface{})
		start, _ := f.GetInteger("start")
		limit, _ := f.GetInteger("length")
		draw, _ := f.GetInteger("draw")
		searchStr := f.GetString("search[value]")
		search := strings.TrimSpace(searchStr)
		query := map[string]interface{}{"s_usertaskid": tid}
		if search != "" {
			query["$or"] = []interface{}{
				bson.M{"v_baseinfo.title": bson.M{"$regex": search}},
			}
		}
		field := map[string]interface{}{"title": 1, "v_baseinfo": 1, "b_istag": 1}
		info, _ := util.Mgo.Find(sourceinfo, query, `{"_id": 1}`, field, false, start, limit)
		count := util.Mgo.Count(sourceinfo, query)
		qu.Debug(query, sourceinfo, count)
		f.ServeJson(map[string]interface{}{
			"draw":            draw,
			"data":            *info,
			"recordsFiltered": count,
			"recordsTotal":    count,
		})

	} else {
		f.T["pid"] = pid
		f.T["tid"] = tid
		f.T["s_sourceinfo"] = sourceinfo
		_ = f.Render("project/remark_list.html", &f.T)
	}
}

func (f *Front) RemarkDetail() {
	pid := f.GetString("pid")
	tid := f.GetString("tid")
	did := f.GetString("did")
	coll := f.GetString("s_sourceinfo")
	project, _ := util.Mgo.FindById(util.PROJECTCOLLNAME, pid, `{"v_fields": 1}`)
	if len(*project) > 0 {
		field := make(map[string]bool)
		vf := (*project)["v_fields"].(map[string]interface{})
		for k := range vf {
			field[k] = true
		}
		f.T["fields"] = field
	}
	qu.Debug(pid, did, coll)
	rep := getDetail(did, coll)         //获取本条公告的信息
	f.T["otherInfo"] = rep["otherInfo"] //展示关联公告信息
	f.T["moreInfo"] = rep["moreInfo"]   //更多关联公告信息
	f.T["tid"] = tid
	f.T["did"] = did
	f.T["info"] = rep["info"]
	f.T["common"] = rep["common"]
	f.T["worder"] = rep["worder"]
	f.T["packs"] = rep["packs"]
	f.T["packskey"] = rep["packskey"]
	f.T["ck_pclistag"] = rep["purchasingTag"]
	f.T["timeplace"] = rep["timeplace"]
	f.T["purchasinglist"] = rep["purchasinglist"]
	f.T["other"] = rep["other"]
	f.T["PurchasinglistField"] = util.PurchasinglistField
	f.T["WinnerorderField"] = util.WinnerorderField
	f.T["PackageField"] = util.PackageField
	f.T["topsubtype"] = util.TopSubStypeArr2
	f.T["ck_purchasinglist"] = rep["ck_purchasinglist"]
	f.T["ck_package"] = rep["ck_package"]
	f.T["ck_winnerorder"] = rep["ck_winnerorder"]
	f.T["worder_new"] = rep["worder_new"]
	f.T["pcl_new"] = rep["pcl_new"]
	f.T["pkg_new"] = rep["pkg_new"]
	f.T["nextid"] = GetNextDataId(did, coll) //下一条id
	_ = f.Render("project/remark_detail.html", &f.T)
}

func getDetail(id, coll string) map[string]interface{} {
	rep := map[string]interface{}{}
	infoTmp, _ := util.Mgo.FindById(coll, id, ``)
	baseInfo := (*infoTmp)["v_baseinfo"].(map[string]interface{}) //字段值
	var bzInfo map[string]interface{}                             //标注信息
	if (*infoTmp)["v_taginfo"] != nil {
		bzInfo = (*infoTmp)["v_taginfo"].(map[string]interface{})
	} else {
		bzInfo = make(map[string]interface{})
	}
	baseInfo["detail"] = qu.ObjToString(baseInfo["title"]) + "</br>" + qu.ObjToString(baseInfo["detail"])
	baseInfo["_id"] = mgo.BsonIdToSId(baseInfo["_id"])
	purchasingTag, _ := bzInfo["purchasinglist_alltag"].(bool)
	rep["purchasingTag"] = purchasingTag
	href := qu.ObjToString(baseInfo["href"])
	if !strings.HasPrefix(href, "http") {
		baseInfo["href"] = "https://" + href
	}
	rep["info"] = baseInfo
	common, timeplace, other := setExtComMap(baseInfo, bzInfo) //拼装抽取common值
	rep["common"] = common
	rep["timeplace"] = timeplace
	rep["other"] = other
	packs, packskey, pkg_new := setPaceMap(baseInfo) //拼装子包信息
	rep["packs"] = packs
	rep["packskey"] = packskey
	rep["pkg_new"] = pkg_new
	purchasinglist, isNewStatus := setPurchasingMap(baseInfo) //标的物
	rep["purchasinglist"] = purchasinglist
	rep["pcl_new"] = isNewStatus
	worder, worder_new := setWorderMap(baseInfo) //中标候选人
	rep["worder"] = worder
	rep["worder_new"] = worder_new
	otherInfo, moreInfo := setOtherInfo(baseInfo) //处理公告关联信息
	rep["otherInfo"] = otherInfo
	rep["moreInfo"] = moreInfo
	//
	if bzInfo["purchasinglist"] != nil {
		rep["ck_purchasinglist"] = "1"
	} else {
		rep["ck_purchasinglist"] = "-1"
	}
	if bzInfo["package"] != nil {
		rep["ck_package"] = "1"
	} else {
		rep["ck_package"] = "-1"
	}
	if bzInfo["winnerorder"] != nil {
		rep["ck_winnerorder"] = "1"
	} else {
		rep["ck_winnerorder"] = "-1"
	}
	return rep
}

//拼装抽取common值
func setExtComMap(info, bzInfo map[string]interface{}) ([]interface{}, []interface{}, []interface{}) {
	//基本参数
	common, _ := util.BiaoZhu["common"].([]interface{})
	for k, tmp := range common {
		if cp, ok := tmp.(map[string]interface{}); ok {
			if info[fmt.Sprint(cp["key"])] == nil {
				cp["value"] = ""
			} else {
				if cp["key"] == "subtype" {
					if info["toptype"] != nil && info["subtype"] != nil {
						cp["value"] = qu.ObjToString(info["toptype"]) + "-" + qu.ObjToString(info[fmt.Sprint(cp["key"])])
					} else {
						cp["value"] = ""
					}
				} else {
					cp["value"] = info[fmt.Sprint(cp["key"])]
				}
			}
			if bzInfo[fmt.Sprint(cp["key"])] == nil {
				cp["status"] = "-1"
			} else {
				cp["status"] = "1"
			}
			common[k] = cp
		}
	}
	//时间地点信息
	timeplace, _ := util.BiaoZhu["timeplace"].([]interface{})
	for k, tmp := range timeplace {
		if tp, ok := tmp.(map[string]interface{}); ok {
			if info[fmt.Sprint(tp["key"])] == nil {
				tp["value"] = ""
			} else {
				key := tp["key"]
				if key == "bidopentime" || key == "publishtime" || key == "bidendtime" || key == "project_startdate" || key == "project_completedate" {
					tmpTime := qu.Int64All(info[fmt.Sprint(tp["key"])])
					if tmpTime > 0 {
						tp["value"] = qu.FormatDateByInt64(&tmpTime, qu.Date_Full_Layout)
					} else {
						tp["value"] = info[qu.ObjToString(tp["key"])]
					}
				} else {
					tp["value"] = info[fmt.Sprint(tp["key"])]
				}
			}
			if bzInfo[fmt.Sprint(tp["key"])] == nil {
				tp["status"] = "-1"
			} else {
				tp["status"] = "1"
			}
			timeplace[k] = tp
		}
	}
	//other信息
	other, _ := util.BiaoZhu["other"].([]interface{})
	for k, tmp := range other {
		if cp, ok := tmp.(map[string]interface{}); ok {
			if info[fmt.Sprint(cp["key"])] == nil {
				cp["value"] = ""
			} else {
				if cp["key"] == "signaturedate" {
					bidopentime := qu.Int64All(info[fmt.Sprint(cp["key"])])
					if bidopentime > 0 {
						cp["value"] = qu.FormatDateByInt64(&bidopentime, qu.Date_Full_Layout)
					} else {
						cp["value"] = info[qu.ObjToString(cp["key"])]
					}
				} else {
					cp["value"] = info[fmt.Sprint(cp["key"])]
				}
			}
			//log.Println(cp)
			if bzInfo[fmt.Sprint(cp["key"])] == nil {
				cp["status"] = "-1"
			} else {
				cp["status"] = "1"
			}
			other[k] = cp
		}
	}
	return common, timeplace, other
}

//拼装子包信息
func setPaceMap(info map[string]interface{}) ([]map[string]interface{}, []string, []bool) {
	var confpack []interface{}
	confpack, _ = util.BiaoZhu["package"].([]interface{})
	//bzpack := bzInfo["package"].(map[string]interface{})
	packs := map[string]map[string]interface{}{}
	var sortpackskey []string
	isNewPkg := map[string]bool{} //记录子包是否是新增的
	if packages, ok := info["package"].(map[string]interface{}); ok && len(packages) > 0 {
		for k, tmpackage := range packages { //遍历分包
			if tmppack, ok := tmpackage.(map[string]interface{}); ok {
				//isNew, _ := tmppack["isnew"].(bool)
				isNew := false
				status := "-1"
				if tmppack["package_son"] != nil {
					status = "1"
				}
				isNewPkg[k] = isNew
				sortpackskey = append(sortpackskey, k)
				var pack []interface{}
				for _, cpack := range confpack {
					cpack, _ := cpack.(map[string]interface{})
					key := qu.ObjToString(cpack["key"])
					if key == "winner" || key == "bidamount" { //中标单位和中标金额winner_all特殊处理
						continue
					}
					tp := map[string]interface{}{
						"key":      key,
						"descript": cpack["descript"],
					}
					if tmppack[fmt.Sprint(tp["key"])] != nil {
						tp["value"] = tmppack[qu.ObjToString(tp["key"])]
					} else {
						tp["value"] = ""
					}
					tp["status"] = status
					pack = append(pack, tp)
				}
				//特殊处理中标单位和中标金额
				winnerall := []interface{}{}
				if tmpWinnerAll, ok := tmppack["winner_all"].([]interface{}); ok && len(tmpWinnerAll) > 0 {
					for _, tmp := range tmpWinnerAll {
						tmpMap := tmp.(map[string]interface{})
						win := map[string]interface{}{
							"descript": "标段（包）中标单位",
							"key":      "winner",
							"status":   status,
							"value":    qu.ObjToString(tmpMap["winner"]),
						}
						winnerall = append(winnerall, win)
						var bidamount interface{}
						if tmpMap["bidamount"] == nil {
							bidamount = ""
						} else {
							bidamount = strconv.FormatFloat(qu.Float64All(tmpMap["bidamount"]), 'f', -1, 64)
						}
						bid := map[string]interface{}{
							"descript": "标段（包）中标金额",
							"key":      "bidamount",
							"status":   status,
							"value":    bidamount,
						}
						winnerall = append(winnerall, bid)
					}
				} else {
					winnerall = append(winnerall, map[string]interface{}{
						"descript": "标段（包）中标单位",
						"key":      "winner",
						"status":   "-1",
						"value":    "",
					})
					winnerall = append(winnerall, map[string]interface{}{
						"descript": "标段（包）中标金额",
						"key":      "bidamount",
						"status":   "-1",
						"value":    "",
					})
				}
				packs[k] = map[string]interface{}{
					"pack":       pack,
					"packstatus": status,
					"winnerall":  winnerall,
				}
			}
		}
	}
	sort.Strings(sortpackskey)
	var packages []map[string]interface{}
	var isNewPkgArr []bool
	for _, v := range sortpackskey {
		packages = append(packages, packs[v])
		isNewPkgArr = append(isNewPkgArr, isNewPkg[v])
	}
	return packages, sortpackskey, isNewPkgArr
}

//拼装标的物
func setPurchasingMap(info map[string]interface{}) ([]interface{}, []map[string]interface{}) {
	purchasinglist, _ := util.BiaoZhu["purchasinglist"].([]interface{})
	var purchasinglists []interface{}
	//isNewPcl := []bool{} //记录子包是否是新增的
	var isNewAndStatus []map[string]interface{}
	if tmpcls, ok := info["purchasinglist"].([]interface{}); ok {
		for _, v := range tmpcls {
			if pcl, ok := v.(map[string]interface{}); ok {
				//isNew, _ := pcl["isnew"].(bool)
				isNew := false
				status := "-1"
				if pcl["purchasinglist_son"] != nil {
					status = "1"
				}
				//isNewPcl = append(isNewPcl, isNew)
				isNewAndStatus = append(isNewAndStatus, map[string]interface{}{"isnew": isNew, "status": status})
				var pcls []interface{}
				for _, ps := range purchasinglist {
					ps, _ := ps.(map[string]interface{})
					value := pcl[qu.ObjToString(ps["key"])]
					if value == nil {
						value = ""
					}
					tp := map[string]interface{}{
						"key":      ps["key"],
						"descript": ps["descript"],
						"value":    value,
						"status":   status,
					}
					// if pcl[preKey+fmt.Sprint(tp["key"])] == nil {
					// 	tp["status"] = "-1"
					// } else {
					// 	tp["status"] = "1"
					// }
					pcls = append(pcls, tp)
				}
				purchasinglists = append(purchasinglists, pcls)
			}
		}
	}
	return purchasinglists, isNewAndStatus
}

//拼装中标候选人
func setWorderMap(info map[string]interface{}) ([]interface{}, []map[string]interface{}) {
	//基本参数--中标候选人
	winnerorder, _ := util.BiaoZhu["winnerorder"].([]interface{})
	worders := []interface{}{}
	isNewAndStatus := []map[string]interface{}{}
	if tmpwds, ok := info["winnerorder"].([]interface{}); ok {
		for _, v := range tmpwds {
			if wd, ok := v.(map[string]interface{}); ok {
				//isNew, _ := wd["isnew"].(bool)
				isNew := false
				status := "-1"
				if wd["winnerorder_son"] != nil {
					status = "1"
				}
				isNewAndStatus = append(isNewAndStatus, map[string]interface{}{"isnew": isNew, "status": status})
				wds := []interface{}{}
				for _, cp := range winnerorder {
					cp, _ := cp.(map[string]interface{})
					value := wd[qu.ObjToString(cp["key"])]
					if value == nil {
						value = ""
					}
					tp := map[string]interface{}{
						"key":      cp["key"],
						"descript": cp["descript"],
						"value":    value,
						"status":   status,
					}
					wds = append(wds, tp)
				}
				worders = append(worders, wds)
			}
		}
	}
	return worders, isNewAndStatus
}

//获取公告关联信息
func setOtherInfo(info map[string]interface{}) (result, moreArr []map[string]interface{}) {
	if otherInfo, ok := info["info"].([]interface{}); ok && len(otherInfo) > 0 {
		//中标，成交、合同、招标(不含变更)
		/*
			[
				{},
				{},
			]
		*/
		zbArr := []map[string]interface{}{}
		cjArr := []map[string]interface{}{}
		htArr := []map[string]interface{}{}
		zbbArr := []map[string]interface{}{}
		for _, tmp := range otherInfo {
			tmpInfo := tmp.(map[string]interface{})
			tmpInfo["detail"] = qu.ObjToString(tmpInfo["title"]) + "</br>" + qu.ObjToString(tmpInfo["title"])
			toptype := tmpInfo["toptype"]
			subtype := tmpInfo["subtype"]
			ptime := ""
			tmpPtime := qu.Int64All(tmpInfo["publishtime"])
			if tmpPtime > 0 {
				ptime = qu.FormatDateByInt64(&tmpPtime, qu.Date_Full_Layout)
			}
			tmpInfo["publishtime_str"] = ptime
			if subtype == "中标" {
				zbArr = append(zbArr, tmpInfo)
			} else if subtype == "成交" {
				cjArr = append(cjArr, tmpInfo)
			} else if subtype == "合同" {
				htArr = append(htArr, tmpInfo)
			} else if toptype == "招标" && subtype != "变更" {
				zbbArr = append(zbbArr, tmpInfo)
			} else { //标注页不展示的信息，更多中展示
				moreArr = append(moreArr, map[string]interface{}{
					"publishtime": tmpInfo["publishtime_str"],
					"subtype":     subtype,
					"title":       tmpInfo["title"],
					"href":        util.GetJyHref(qu.ObjToString(tmpInfo["id"])),
				})
			}
		}
		publishtime := qu.Float64All(info["publishtime"])
		//中标信息
		if zbLen := len(zbArr); zbLen > 0 {
			rzb := DealData(zbLen, publishtime, zbArr, &moreArr)
			result = append(result, rzb)
		}
		//成交
		if cjLen := len(cjArr); cjLen > 0 {
			rcj := DealData(cjLen, publishtime, cjArr, &moreArr)
			result = append(result, rcj)
		}
		//合同
		if htLen := len(htArr); htLen > 0 {
			rht := DealData(htLen, publishtime, htArr, &moreArr)
			result = append(result, rht)
		}
		result = append(result, zbbArr...)
	}
	return
}

func DealData(tmpLen int, publishtime float64, tmp []map[string]interface{}, moreArr *[]map[string]interface{}) (resultTmp map[string]interface{}) {
	if tmpLen == 1 || publishtime <= 0 { //相同类型只有一条或者原公告发布时间异常取第一条公告
		resultTmp = tmp[0]
		for _, t := range tmp[1:] { //将过滤掉的数据加入到更多中
			*moreArr = append(*moreArr, map[string]interface{}{
				"publishtime": t["publishtime_str"],
				"subtype":     t["subtype"],
				"title":       t["title"],
				"href":        util.GetJyHref(qu.ObjToString(t["id"])),
			})
		}
		return
	} else {
		diff := float64(0) //记录差值
		index := 0
		for i, zb := range tmp {
			pTmp := qu.Float64All(zb["publishtime"])
			diffTmp := math.Abs(publishtime - pTmp) //绝对值
			if i == 0 {
				diff = diffTmp
			} else if diffTmp < diff { //记录较小差值的数据索引位置
				diff = diffTmp
				index = i
			} else { //将过滤掉的数据加入到更多中
				*moreArr = append(*moreArr, map[string]interface{}{
					"publishtime": zb["publishtime_str"],
					"subtype":     zb["subtype"],
					"title":       zb["title"],
					"href":        util.GetJyHref(qu.ObjToString(zb["id"])),
				})
			}
		}
		resultTmp = tmp[index]
	}
	return
}

//获取当前数据下一条的id
func GetNextDataId(id, coll string) string {
	nextIdQuery := map[string]interface{}{
		"_id": map[string]interface{}{
			"$gt": mgo.StringTOBsonId(id),
		},
	}

	one, _ := util.Mgo.Find(coll, nextIdQuery, `{"_id":1}`, `{"_id":1}`, true, 0, 1)
	if one != nil && len(*one) == 1 {
		return mgo.BsonIdToSId((*one)[0]["_id"])
	}
	return id
}
