package audit

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

/**
企业库
 */
func init() {
	//页面
	Admin.GET("/audit/qiyeku_info", func(c *gin.Context) {
		c.HTML(200, "qiyekuinfo.html", gin.H{})
	})
	//save
	Admin.POST("/audit/qiyeku_info/save", func(c *gin.Context) {
		_id := c.PostForm("_id")
		company_name := c.PostForm("company_name")
		alias := c.PostForm("alias")
		history_name := strings.ReplaceAll(c.PostForm("history_name"), "；", ";")
		area_code := c.PostForm("area_code")
		province := c.PostForm("province")
		city := c.PostForm("city")
		district := c.PostForm("district")
		capital := c.PostForm("capital")
		company_address := c.PostForm("company_address")
		business_scope := c.PostForm("business_scope")
		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(company_name) == "" {
			c.JSON(200, gin.H{"rep": 400})
			return
		}
		//金额转换
		capitalfloat := clear.ObjToMoney([]interface{}{capital, ""})[0]
		e := make(map[string]interface{})
		e["company_name"] = company_name
		e["alias"] = alias
		e["history_name"] = history_name
		e["area_code"] = area_code
		e["province"] = province
		e["city"] = city
		e["district"] = district
		e["capital"] = capitalfloat
		e["company_address"] = company_address
		e["business_scope"] = business_scope
		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, "company_name")
			//转换失败不更新
			if jsonerr != nil {
				delete(e, "contact")
			}
			tmpb := Mgo.Update(util.ElasticClientDB, 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.ElasticClientIndex).Type(util.ElasticClientType).
					Id(sid).Doc(e).Refresh(true).Do()
				if err != nil {
					log.Println("update qyk 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.ElasticClientDB, 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.WinnerDB);err != nil{
					log.Println("保存redis 错误", err)
					c.JSON(200, gin.H{"rep": 500, "err": "select reids出错"})
					return
				}else {
					if _,saveRedisErr := qykredis.Do("SET",company_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.ElasticClientIndex).Type(util.ElasticClientType).Id(sid).BodyJson(e).Refresh(true).Do()
				if err != nil {
					log.Println("save qyk 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_qyk/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.ElasticClientIndex, util.ElasticClientType, search)
			//查询es
			escon := elastic.GetEsConn()
			defer elastic.DestoryEsConn(escon)
			res, err := escon.Search(util.ElasticClientIndex).
				Type(util.ElasticClientType).Source(`{"query": {"match_phrase":{"company_name":"` + search + `"}}}`).
				//Query( elastic.NewMatchPhraseQuery("company_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{"company_name": bson.M{"$regex": bson.RegEx{search, "i"}}})
				//data, _ := Mgo.Find("enterprise_qyxy", bson.M{"company_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/qiyeku_info/deleteQyk", func(c *gin.Context) {
		_id := c.PostForm("_id")
		company_name := c.PostForm("company_name")
		if bson.IsObjectIdHex(_id) {
			delisok := Mgo.Del(util.ElasticClientDB, 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.WinnerDB);err!=nil{
				log.Println("delete qyk err:", err, company_name)
				c.JSON(200, gin.H{"rep": 500, "err": "删除redis错误"})
				return
			}else {
				if _,delErr := qykredis.Do("DEL",company_name); delErr != nil {
					log.Println("delete qyk err:", delErr, company_name)
					c.JSON(200, gin.H{"rep": 500, "err": "删除redis错误"})
					return
				}
			}
			escon := elastic.GetEsConn()
			defer elastic.DestoryEsConn(escon)
			_, err := escon.Delete().Index(util.ElasticClientIndex).Type(util.ElasticClientType).Id(_id).Refresh(true).Do()
			if err != nil {
				log.Println("delete qyk 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": "参数错误"})
		}
	})
	//queryById
	Admin.POST("/audit/query_qyk/ById", func(c *gin.Context) {
		_id := c.PostForm("_id")
		q_field := c.PostForm("q_field")
		if bson.IsObjectIdHex(_id) && strings.TrimSpace(q_field) != "" {
			data, _ := Mgo.FindById(util.ElasticClientDB, _id, bson.M{q_field: 1})
			c.JSON(200, gin.H{"rep": 200, "data": data})
		} else {
			c.JSON(200, gin.H{"rep": 400})
		}
	})
	//updateIndustrys  更新行业类型
	Admin.POST("/audit/query_qyk/UpdateIndustrys", func(c *gin.Context) {
		_id := c.PostForm("_id")
		industrys := c.PostFormArray("industry")
		//log.Println(_id,industrys)
		if bson.IsObjectIdHex(_id) {
			b := Mgo.Update(util.ElasticClientDB, bson.M{"_id": bson.ObjectIdHex(_id)}, bson.M{"$set": bson.M{"industry": industrys}}, false, false)
			if b {
				escon := elastic.GetEsConn()
				defer elastic.DestoryEsConn(escon)
				_, err := escon.Update().Index(util.ElasticClientIndex).Type(util.ElasticClientType).Id(_id).Doc(map[string]interface{}{
					"industry": industrys,
				}).Refresh(true).Do()
				if err != nil {
					log.Println("update yqk industry err :", err)
				}
			}
			c.JSON(200, gin.H{"rep": 200, "data": b})
		} else {
			c.JSON(200, gin.H{"rep": 400})
		}
	})
	//updateTels  更新联系方式
	Admin.POST("/audit/query_qyk/UpdateTels", func(c *gin.Context) {
		_id := c.PostForm("_id")
		//log.Println(_id)
		contact_persons := c.PostFormArray("contact_persons")
		contact_types := c.PostFormArray("contact_types")
		phones := c.PostFormArray("phones")
		topscopeclasss := c.PostFormArray("topscopeclasss")
		if bson.IsObjectIdHex(_id) && len(contact_persons) == len(contact_types) && len(phones) == len(topscopeclasss) && len(phones) == len(contact_persons) {
			contacts := make([]map[string]interface{}, 0)
			for _, v := range contact_persons {
				tmp := make(map[string]interface{})
				tmp["contact_person"] = v
				contacts = append(contacts, tmp)
			}
			for i, v := range contact_types {
				contacts[i]["contact_type"] = v
			}
			for i, v := range phones {
				contacts[i]["phone"] = v
			}
			for i, v := range topscopeclasss {
				contacts[i]["topscopeclass"] = v
				contacts[i]["updatetime"] = time.Now().Unix()
			}
			//for k,v := range contacts{
			//	log.Println(k,v)
			//}
			b := Mgo.Update(util.ElasticClientDB, bson.M{"_id": bson.ObjectIdHex(_id)}, bson.M{"$set": bson.M{"contact": contacts}}, false, false)
			if b {
				escon := elastic.GetEsConn()
				defer elastic.DestoryEsConn(escon)
				_, err := escon.Update().Index(util.ElasticClientIndex).Type(util.ElasticClientType).Id(_id).Doc(map[string]interface{}{
					"contact": contacts,
				}).Refresh(true).Do()
				if err != nil {
					log.Println("update yqk contact err :", err)
				}
			}
			c.JSON(200, gin.H{"rep": 200, "data": b})
		} else {
			c.JSON(200, gin.H{"rep": 400})
		}
	})
}
