package audit

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
	. "jy/admin"
	. "jy/mongodbutil"
	"jy/util"
	"log"
	"qfw/util/elastic"
	"qfw/util/redis"
	"strconv"
	"strings"
	"time"
)

/**
企业库
 */
func init() {
	//页面
	Admin.GET("/audit/agency_info", func(c *gin.Context) {
		c.HTML(200, "agencyinfo.html", gin.H{})
	})
	//save
	Admin.POST("/audit/agency_info/save", func(c *gin.Context) {
		_id := c.PostForm("_id")
		agency_name := c.PostForm("agency_name")
		history_name := strings.ReplaceAll(c.PostForm("history_name"),"；",";")
		area_code := c.PostForm("area_code")
		agency_type :=c.PostForm("type")
		ranks :=c.PostForm("ranks")
		province := c.PostForm("province")
		city := c.PostForm("city")
		district := c.PostForm("district")
		address := c.PostForm("address")
		wechat_accounts := strings.ReplaceAll(c.PostForm("wechat_accounts"),"；",";")
		website := c.PostForm("website")
		contact := c.PostForm("contact")
		contacts := make([]map[string]interface{},0)
		jsonerr :=json.Unmarshal([]byte(contact),&contacts)
		if strings.TrimSpace(agency_name) == "" {
			c.JSON(200, gin.H{"rep": 400})
			return
		}
		//构建map
		e := make(map[string]interface{})
		e["agency_name"] = agency_name
		if len(history_name)>0{
			e["history_name"] = strings.Split(history_name,";")
		}else {
			e["history_name"] =[]string{}
		}
		e["area_code"] = area_code
		e["type"] = agency_type
		e["ranks"] = ranks
		e["province"] = province
		e["city"] = city
		e["district"] = district
		e["address"] = address
		if len(wechat_accounts)>0{
			e["wechat_accounts"] = strings.Split(wechat_accounts,";")
		}else {
			e["wechat_accounts"] = []string{}
		}
		e["website"] = website
		if jsonerr != nil {
			e["contact"] = []map[string]interface{}{}
		}else {
			for k,v := range contacts{
				if v["updatetime"] == nil{
					contacts[k]["updatetime"]=time.Now().Unix()
				}
			}
			e["contact"] = contacts
		}

		e["updatatime"]=time.Now().Unix()
		var sid string
		if bson.IsObjectIdHex(_id) {
			//更新
			sid = _id
			delete(e,"_id")
			delete(e,"agency_name")
			//转换失败不更新
			if jsonerr!= nil {
				delete(e,"contact")
			}
			tmpb := Mgo.Update(util.ElasticClientAgencyDB, bson.M{"_id": bson.ObjectIdHex(_id)}, bson.M{"$set": e}, false, false)
			//更新es
			if tmpb {
				escon := elastic.GetEsConn()
				defer elastic.DestoryEsConn(escon)
				_, err := escon.Update().Index(util.ElasticClientAgencyIndex).Type(util.ElasticClientAgencyType).
					Id(sid).Doc(e).Refresh(true).Do()
				if err != nil {
					log.Println("update agency err:", err)
					c.JSON(200, gin.H{"rep": 500, "err":"更新es错误"})
					return
				}
			}else {
				c.JSON(200, gin.H{"rep": 500, "err":"更新mongo错误"})
				return
			}
			c.JSON(200, gin.H{"rep": 200, "updateid": sid})
		} else {
			e["comeintime"] =time.Now().Unix()
			//不存在直接保存新数据
			sid = Mgo.Save(util.ElasticClientAgencyDB, e)
			if sid == ""{
				c.JSON(200, gin.H{"rep": 500,"err":"保存mongo出错"})
				return
			}else {
				delete(e, "_id")
				qykredis := redis.RedisPool[util.QYK_RedisName].Get()
				defer qykredis.Close()
				if _,err := qykredis.Do("SELECT",util.AgencyDB);err != nil{
					log.Println("保存redis 错误", err)
					c.JSON(200, gin.H{"rep": 500, "err": "select reids出错"})
					return
				}else {
					if _,saveRedisErr := qykredis.Do("SET",agency_name, sid); saveRedisErr != nil {
						log.Println("保存redis 错误", saveRedisErr)
						c.JSON(200, gin.H{"rep": 500, "err": "保存reids出错"})
						return
					}
				}


				escon := elastic.GetEsConn()
				defer elastic.DestoryEsConn(escon)
				_, err := escon.Index().Index(util.ElasticClientAgencyIndex).Type(util.ElasticClientAgencyType).Id(sid).BodyJson(e).Refresh(true).Do()
				if err != nil {
					log.Println("save agency err:", err)
					c.JSON(200, gin.H{"rep": 500, "err": "更新es错误"})
					return
				}
			}
			c.JSON(200, gin.H{"rep": 200, "saveid": sid})
		}
	})



	//列表查询
	Admin.POST("/audit/query_agency/list", func(c *gin.Context) {
		search, _ := c.GetPostForm("search[value]")
		startstr, _ := c.GetPostForm("start")
		limitstr, _ := c.GetPostForm("length")
		start, _ := strconv.Atoi(startstr)
		limit, _ := strconv.Atoi(limitstr)
		if limit < 1 {
			limit = 10
		}
		if search == "" {
			c.JSON(200, gin.H{"data": []map[string]interface{}{}, "recordsFiltered": 0, "recordsTotal": 0})
		} else {
			//log.Println(util.ElasticClientAgencyIndex, util.ElasticClientAgencyType, search)
			//查询es
			escon := elastic.GetEsConn()
			defer elastic.DestoryEsConn(escon)
			res, err := escon.Search(util.ElasticClientAgencyIndex).
				Type(util.ElasticClientAgencyType).Source(`{"query": {"match_phrase":{"agency_name":"`+search+`"}}}`).
				//Query( elastic.NewMatchPhraseQuery("agency_name", search)).
				Size(limit).
				From(start).
				Do()
			if err != nil {
				log.Println(err)
				c.JSON(500, gin.H{"data": []map[string]interface{}{}, "recordsFiltered": 0, "recordsTotal": 0})
				return
			}
			if res.Hits != nil{
				tmps := make([]map[string]interface{}, 0)
				for _, v := range res.Hits.Hits {
					tmp := make(map[string]interface{})
					err := json.Unmarshal(*v.Source, &tmp)
					if err != nil {
						log.Println(err)
						continue
					}
					tmp["_id"] = v.Id
					//log.Println(tmp)
					tmps = append(tmps, tmp)
				}
				//count := Mgo.Count("enterprise_qyxy", bson.M{"agency_name": bson.M{"$regex": bson.RegEx{search, "i"}}})
				//data, _ := Mgo.Find("enterprise_qyxy", bson.M{"agency_name": bson.M{"$regex": bson.RegEx{search, "i"}}}, `{"_id":-1}`, nil, false, start, limit)
				c.JSON(200, gin.H{"data": tmps, "recordsFiltered": res.Hits.TotalHits, "recordsTotal": res.Hits.TotalHits})
			}else {
				c.JSON(200, gin.H{"data": []map[string]interface{}{}, "recordsFiltered": 0, "recordsTotal": 0})
			}
		}
	})
	//delete
	Admin.POST("/audit/agency_info/deleteQyk", func(c *gin.Context) {
		_id := c.PostForm("_id")
		agency_name := c.PostForm("agency_name")
		if bson.IsObjectIdHex(_id) {
			delisok := Mgo.Del(util.ElasticClientAgencyDB, bson.M{"_id": bson.ObjectIdHex(_id)})
			if !delisok {
				c.JSON(200, gin.H{"rep": 500, "err": "删除mongo错误"})
				return
			}
			qykredis := redis.RedisPool[util.QYK_RedisName].Get()
			defer qykredis.Close()
			if _,err :=qykredis.Do("SELECT",util.AgencyDB);err!=nil{
				log.Println("delete agency err:", err, agency_name)
				c.JSON(200, gin.H{"rep": 500, "err": "删除redis错误"})
				return
			}else {
				if _,delErr := qykredis.Do("DEL",agency_name); delErr != nil {
					log.Println("delete agency err:", delErr, agency_name)
					c.JSON(200, gin.H{"rep": 500, "err": "删除redis错误"})
					return
				}
			}


			escon := elastic.GetEsConn()
			defer elastic.DestoryEsConn(escon)
			_, err := escon.Delete().Index(util.ElasticClientAgencyIndex).Type(util.ElasticClientAgencyType).Id(_id).Refresh(true).Do()
			if err != nil {
				log.Println("delete agency err:", err)
				c.JSON(200, gin.H{"rep": 500,"err":"删除es错误"})
				return
			}
			c.JSON(200, gin.H{"rep": 200, "data": delisok})
		} else {
			c.JSON(200, gin.H{"rep": 400,"err":"参数错误"})
		}
	})

}
