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"
	"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")
		province := c.PostForm("province")
		city := c.PostForm("city")
		district := c.PostForm("district")
		capital := c.PostForm("capital")
		company_address := c.PostForm("company_address")
		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["province"] = province
		e["city"] = city
		e["district"] = district
		e["capital"] = capitalfloat
		e["company_address"] = company_address
		var sid string
		if strings.TrimSpace(_id) != "" && bson.IsObjectIdHex(_id) {
			sid = _id
			tmpb := Mgo.Update("enterprise_qyxy", bson.M{"_id": bson.ObjectIdHex(_id)}, bson.M{"$set": bson.M{
				"company_name":    company_name,
				"alias":           alias,
				"province":        province,
				"city":            city,
				"district":        district,
				"capital":         capitalfloat,
				"company_address": company_address,
			}}, false, false)
			if tmpb {
				escon := elastic.GetEsConn()
				defer elastic.DestoryEsConn(escon)
				_, err := escon.Update().Index(util.ElasticClientIndex).Type(util.ElasticClientType).
					Id(sid).Doc(map[string]interface{}{
					"company_name":    company_name,
					"alias":           alias,
					"province":        province,
					"city":            city,
					"district":        district,
					"capital":         capitalfloat,
					"company_address": company_address,
				}).Refresh(true).Do()
				if err != nil {
					log.Println("update qyk err:", err)
				}
			}
		} else {
			sid = Mgo.Save("enterprise_qyxy", e)
			delete(e, "_id")
			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": 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)
			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")
		if bson.IsObjectIdHex(_id) {
			delisok := Mgo.Del("enterprise_qyxy", bson.M{"_id": bson.ObjectIdHex(_id)})
			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": 200, "data": delisok})
		} else {
			c.JSON(200, gin.H{"rep": 400})
		}
	})
	//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})
		}
	})
}
