package api

import (
	"../../pkg/util"
	"../../routers/restful"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/hequan2017/go-admin/pkg/e"
	"github.com/hequan2017/go-admin/pkg/logging"
	"net/http"
	"strconv"
	"time"

	"../../pkg/app"
	//"time"
	"../../pkg/setting"
)



func GetDorm(c *gin.Context) {
	//appG := app.Gin{C: c}
	//dataByte, _ := ioutil.ReadAll(c.Request.Body)
	//fsion := gofasion.NewFasion(string(dataByte))
	//sqlnamestr := fsion.Get("name").ValueStr()
	//offset := fsion.Get("offset").ValueDefaultInt(0)
	//pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
	//returntype := fsion.Get("returntype").ValueDefaultStr("map")
	data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getDorm")
	if data != nil {
		var feedp util.Feedp
		json.Unmarshal(data, &feedp)
		status := feedp.Status
		feedpData := feedp.Data

		if status == 0 {
			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
			//fsion := gofasion.NewFasion(string(dataByte))
			//pastureid := fsion.Get("pastureid").ValueStr()
			pastureid := 3445271849683387392
			// 开启事务
			appG := app.Gin{C: c}
			tx := restful.Engine.NewSession()
			err := tx.Begin()
			defer func() {
				switch {
				case err != nil:
					logging.Error("tx.Begin 事务启动失败__error:", err)
					if tx != nil {
						tx.Rollback()
					}
				default:
					if tx != nil {
						err = tx.Commit()
					}
				}
				if tx != nil {
					tx.Close()
				}
			}()

			for _, val := range feedpData {
				penId := val.PenId
				penName := val.PenName
				cowCount := val.CowCount
				ccountRatio := val.CcountRatio

				//createdAt := val.CreatedAt
				//modifiedAt := val.ModifiedAt

				ids, err := setting.SnowIds.NextId()
				if err != nil {
					ids = time.Now().UnixNano()
					logging.Info("create SnowIds err", err)
				}

				exec, err := tx.Exec("insert into bar(id,pastureid,bcode,bname) "+
					" values(?,?,?,?)"+
					" ON DUPLICATE KEY UPDATE bcode=?,bname=?",
					ids, pastureid, penId, penName, penId, penName)

				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec)
				}

				exec2, err := tx.Exec("insert into feedp(id,pastureid,barid,barname,ccount,ratio,ccountratio) "+
					" values(?,?,(select id from bar where pastureid=? and bname=?),?,(if(?='',0,?)),REPLACE(?,'%',''),REPLACE(?,'%','')*(if(?='',0,?)))"+
					" ON DUPLICATE KEY UPDATE barid=(select id from bar where pastureid=? and bname=?),barname=?,ccount=(if(?='',0,?)),ratio=REPLACE(?,'%',''),ccountratio=REPLACE(?,'%','')*(if(?='',0,?))",
					ids, pastureid, pastureid, penName, penName, cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, pastureid, penName, penName,
					cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount)

				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec2)
				}

			}
			appG.Response(http.StatusOK, e.SUCCESS, nil)
		}

	}

}

func GetMaterial(c *gin.Context) {
	data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getMaterial")
	if data != nil {
		var feed util.Feed
		json.Unmarshal(data, &feed)
		status := feed.Status
		feedpData := feed.Data

		if status == 0 {
			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
			//fsion := gofasion.NewFasion(string(dataByte))
			//pastureid := fsion.Get("pastureid").ValueStr()
			pastureid := 3445271849683387392
			// 开启事务
			appG := app.Gin{C: c}
			tx := restful.Engine.NewSession()
			err := tx.Begin()
			defer func() {
				switch {
				case err != nil:
					logging.Error("tx.Begin 事务启动失败__error:", err)
					if tx != nil {
						tx.Rollback()
					}
				default:
					if tx != nil {
						err = tx.Commit()
					}
				}
				if tx != nil {
					tx.Close()
				}
			}()

			for _, val := range feedpData {
				fId := val.FId
				fName := val.FName
				price := val.Price
				dryMatter := val.DryMatter
				//autoChange := val.AutoChange
				//allowDev := val.AllowDev
				feedclassName := val.FeedclassName
				createdAt := val.CreatedAt
				modifiedAt := val.ModifiedAt

				fmt.Println(fName, feedclassName, createdAt, modifiedAt)

				ids, err := setting.SnowIds.NextId()
				if err != nil {
					ids = time.Now().UnixNano()
					logging.Info("create SnowIds err", err)
				}

				exec, err := tx.Exec("insert into feed(id,pastureid,feedcode,fname,fclass,fclassid,uprice,dry) "+
					" values(?,?,?,?,?,(select id from feedclass where fcname=? and pastureid=?),(if(?='',0,?)),(if(?='' or ?='~',0,?)))"+
					" ON DUPLICATE KEY UPDATE feedcode=?,fname=?,fclass=?,fclassid=(select id from feedclass where fcname=? and pastureid=?),uprice=(if(?='',0,?)),dry=(if(?='' or ?='~',0,?))",
					ids, pastureid, fId, fName, feedclassName, feedclassName, pastureid, price, price, dryMatter, dryMatter, dryMatter, fId, fName, feedclassName, feedclassName, pastureid, price, price, dryMatter, dryMatter, dryMatter)
				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec)
				}

			}
			appG.Response(http.StatusOK, e.SUCCESS, nil)
		}

	}

}

func GetMaterialCategory(c *gin.Context) {
	data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getMaterialCategory")
	if data != nil {
		var feedClass util.FeedClass
		json.Unmarshal(data, &feedClass)
		status := feedClass.Status
		feedpData := feedClass.Data

		if status == 0 {
			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
			//fsion := gofasion.NewFasion(string(dataByte))
			//pastureid := fsion.Get("pastureid").ValueStr()
			pastureid := 3445271849683387392
			// 开启事务
			appG := app.Gin{C: c}
			tx := restful.Engine.NewSession()
			err := tx.Begin()
			defer func() {
				switch {
				case err != nil:
					logging.Error("tx.Begin 事务启动失败__error:", err)
					if tx != nil {
						tx.Rollback()
					}
				default:
					if tx != nil {
						err = tx.Commit()
					}
				}
				if tx != nil {
					tx.Close()
				}
			}()

			for _, val := range feedpData {
				feedclassName := val.FeedclassName
				feedclassId := val.FeedclassId
				createdAt := val.CreatedAt
				modifiedAt := val.ModifiedAt
				fmt.Println(feedclassId, feedclassName, createdAt, modifiedAt)

				ids, err := setting.SnowIds.NextId()
				if err != nil {
					ids = time.Now().UnixNano()
					logging.Info("create SnowIds err", err)
				}

				exec, err := tx.Exec("insert into feedclass(id,pastureid,fcname,fccode,bigfeedclassid,bigfeedclassname,sort,`enable`) values(?,?,?,?,?,?,?,?)"+
					" ON DUPLICATE KEY UPDATE fcname=?,fccode=?",
					ids, pastureid, feedclassName, feedclassId, 3, "精粗各半", 0, 1, feedclassName, feedclassId)
				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec)
				}

			}
			appG.Response(http.StatusOK, e.SUCCESS, nil)
		}

	}

}

func GetCowCategory(c *gin.Context) {
	data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getCowCategory")
	if data != nil {
		var cowClass util.CowClass
		json.Unmarshal(data, &cowClass)
		status := cowClass.Status
		feedpData := cowClass.Data

		if status == 0 {
			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
			//fsion := gofasion.NewFasion(string(dataByte))
			//pastureid := fsion.Get("pastureid").ValueStr()
			pastureid := 3445271849683387392
			// 开启事务
			appG := app.Gin{C: c}
			tx := restful.Engine.NewSession()
			err := tx.Begin()
			defer func() {
				switch {
				case err != nil:
					logging.Error("tx.Begin 事务启动失败__error:", err)
					if tx != nil {
						tx.Rollback()
					}
				default:
					if tx != nil {
						err = tx.Commit()
					}
				}
				if tx != nil {
					tx.Close()
				}
			}()

			for _, val := range feedpData {
				cowClassCode := val.CowClassCode
				cowClassName := val.CowClassName
				createdAt := val.CreatedAt
				modifiedAt := val.ModifiedAt
				fmt.Println(cowClassCode, cowClassName, createdAt, modifiedAt)

				ids, err := setting.SnowIds.NextId()
				if err != nil {
					ids = time.Now().UnixNano()
					logging.Info("create SnowIds err", err)
				}

				exec, err := tx.Exec("insert into cowclass(id,pastureid,classcode,classname) values(?,?,?,?)"+
					" ON DUPLICATE KEY UPDATE classcode=?,classname=?",
					ids, pastureid, cowClassCode, cowClassName, cowClassCode, cowClassName)
				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec)
				}

			}
			appG.Response(http.StatusOK, e.SUCCESS, nil)
		}

	}

}

func GetFormula(c *gin.Context) {
	data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getFormula")
	if data != nil {
		var feedTemplet util.FeedTemplet
		json.Unmarshal(data, &feedTemplet)
		status := feedTemplet.Status
		feedpData := feedTemplet.Data

		if status == 0 {
			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
			//fsion := gofasion.NewFasion(string(dataByte))
			//pastureid := fsion.Get("pastureid").ValueStr()
			pastureid := 3445271849683387392
			// 开启事务
			appG := app.Gin{C: c}
			tx := restful.Engine.NewSession()
			err := tx.Begin()
			defer func() {
				switch {
				case err != nil:
					logging.Error("tx.Begin 事务启动失败__error:", err)
					if tx != nil {
						tx.Rollback()
					}
				default:
					if tx != nil {
						err = tx.Commit()
					}
				}
				if tx != nil {
					tx.Close()
				}
			}()

			for _, val := range feedpData {
				ftId := val.FtId
				ftName := val.FtName
				feedList := val.FeedList
				//createdAt := val.CreatedAt
				//modifiedAt := val.ModifiedAt

				ids, err := setting.SnowIds.NextId()
				if err != nil {
					ids = time.Now().UnixNano()
					logging.Info("create SnowIds err", err)
				}

				exec, err := tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,tname,fttypeid,fttype)  values(?,?,null,?,?,1,'饲喂配方')"+
					" ON DUPLICATE KEY UPDATE tcode=?,tname=?",
					ids, pastureid, ftId, ftName, ftId, ftName)

				if err != nil {
					fmt.Println(err)
					continue
				} else {
					fmt.Println(exec)
				}

				// tx.Exec("delete from ftdetail where ftid=(select id from feedtemplet where pastureid=? and tname=?)",pastureid, ftName)

				for _, val := range feedList {
					fId := val.FId
					fName := val.FName
					fodderWeight := val.FodderWeight
					mixNo := val.MixNo

					ids, err := setting.SnowIds.NextId()

					if err != nil {
						ids = time.Now().UnixNano()
						logging.Info("create SnowIds err", err)
					}

					exec, err := tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort)  "+
						" values(?,?,(select id from feedtemplet where pastureid=? and tname=? limit 1),(select id from feed where pastureid=? and feedcode=? limit 1),?,(if(?='',0,?)),(if(?='',0,?)))",
						ids, pastureid, pastureid, ftName, pastureid, fId, fName, fodderWeight, fodderWeight, mixNo, mixNo)
					if err != nil {
						fmt.Println(err)
						continue
					} else {
						fmt.Println(exec)
					}
				}
			}

			appG.Response(http.StatusOK, e.SUCCESS, nil)
		}

	}

}

func AddOtherDevice(c *gin.Context) {
	appG := app.Gin{C: c}
	tx := restful.Engine.NewSession()
	err := tx.Begin()
	defer func() {
		switch {
		case err != nil:
			logging.Error("tx.Begin 事务启动失败__error:", err)
			if tx != nil {
				tx.Rollback()
			}
		default:
			if tx != nil {
				err = tx.Commit()
			}
		}
		if tx != nil {
			tx.Close()
		}
	}()


	queryIdList, err1 := tx.SQL("select d.id,d.projname projName from downloadedplan d where d.pastureid=? and d.mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and d.isuse=0 " +
		" and d.pastureid =(SELECT column_default  FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()

	queryDataList, err2 := tx.SQL("select  d.id id,d.projname projName,round(d.lweight,2) lWeight,date_format(d.mydate,'%Y-%m-%d') as loadDate,d.SORT as tmrNo,d.Times as times,ft.tcode as ftId,d.templetName  as ftName,f.feedcode as fId,"+
		" de.Fname as fName,fc.FCNAME as feedclassName,de.SORT as sort,de.feedallowratio as allowableError, "+
		" cast(de.LWEIGHT as decimal(10,2)) as expWeight,cast(de.ActualWeightMinus as decimal(10,2)) as actualWeight,"+
		" date_format(de.intime,'%Y-%m-%d %H:%i:%s') as endTime ,d.tmrtname as tName ,'' dName "+
		" from downloadedplan d LEFT JOIN downloadplandtl1 de on d.id=de.PID and d.pastureid=de.pastureid "+
		" LEFT JOIN feed f on de.fid=f.id and f.pastureid=d.pastureid LEFT JOIN feedtemplet ft on d.tempid=ft.id and ft.pastureid=d.pastureid "+
		" LEFT JOIN feedclass fc on f.fclassid=fc.id and fc.pastureid=d.pastureid  "+
		" where d.mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and d.isuse=0  " +
		" and d.pastureid =(SELECT column_default  FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()

	if err1 == nil && err2 == nil {

		for i := 0; i < len(queryIdList); i++ {
			id := queryIdList[i]["id"]
			projName := queryIdList[i]["projName"]

			listData := make(map[string]interface{})

			listData["farmId"] = 4090
			listData["id"] = id
			listData["projName"] = projName

			feedList := []interface{}{}

			for j := 0; j < len(queryDataList); j++ {
				id2 := queryDataList[j]["id"]
				if id == id2 {
					dataList := make(map[string]interface{})
					dataList["tmrNo"] = queryDataList[j]["tmrNo"]
					dataList["times"] = queryDataList[j]["times"]
					dataList["loadDate"] = queryDataList[j]["loadDate"]
					dataList["ftId"] = queryDataList[j]["ftId"]
					dataList["ftName"] = queryDataList[j]["ftName"]
					dataList["fId"] = queryDataList[j]["fId"]
					dataList["tName"] = queryDataList[j]["tName"]
					dataList["feedclassName"] = queryDataList[j]["feedclassName"]
					dataList["fName"] = queryDataList[j]["fName"]
					dataList["sort"] = queryDataList[j]["sort"]

					dataList["allowableError"] = queryDataList[j]["allowableError"]

					expWeight, _ := strconv.ParseFloat(queryDataList[j]["expWeight"].(string), 64)
					actualWeight, _ := strconv.ParseFloat((queryDataList[j]["actualWeight"]).(string), 64)
					lWeight, _ := strconv.ParseFloat(queryDataList[j]["lWeight"].(string), 64)


					dataList["expWeight"] = expWeight
					dataList["actualWeight"] = actualWeight
					dataList["lWeight"] = lWeight

					dataList["endTime"] = queryDataList[j]["endTime"]
					dataList["dName"] = queryDataList[j]["dName"]

					feedList = append(feedList, dataList)
				}
			}
			listData["data"] = feedList

			jsonStr, _ := json.Marshal(listData)

			postData := make(map[string]string)
			postData["formData"] = string(jsonStr)

			fmt.Println(&postData)

			data := util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDevice", &postData)

			appG.Response(http.StatusOK, e.SUCCESS, string(data))

		}
	}

}

func AddOtherDeviceFeeding(c *gin.Context) {
	appG := app.Gin{C: c}

	tx := restful.Engine.NewSession()
	err := tx.Begin()
	defer func() {
		switch {
		case err != nil:
			logging.Error("tx.Begin 事务启动失败__error:", err)
			if tx != nil {
				tx.Rollback()
			}
		default:
			if tx != nil {
				err = tx.Commit()
			}
		}
		if tx != nil {
			tx.Close()
		}
	}()

	queryIdList, err1 := tx.SQL("select d.id,d.projname projName from downloadedplan d where d.mydate=date_format(NOW(),'%Y-%m-%d')   and iscompleted=1 and d.isuse=0  " +
		" and d.pastureid =(SELECT column_default  FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid')").Query().List()

	queryDataList, err2 := tx.SQL("SELECT  d.id id,d.projname projName,date_format(d.mydate,'%Y-%m-%d') as dropDate,d.Times as times,d.SORT as tmrNo,"+
		" bar.bcode as penId,d2.fname as penName,fp.CCOUNT as cowCount, d2.SORT as sort,d.templetName ftName, ft.tcode ftId,"+
		" d2.LWEIGHT as expWeight,d2.ActualWeightMinus as actualWeight,date_format(d2.intime,'%Y-%m-%d %H:%i:%s') as endTime,d.tmrtname as tName,'' dName  "+
		" from  downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID and d.pastureid=d2.pastureid  "+
		" LEFT JOIN bar on  d2.fbarid=bar.id and bar.pastureid=d2.pastureid LEFT JOIN feedp fp on d2.fbarid=fp.barid and fp.pastureid=d2.pastureid "+
		" LEFT JOIN feedtemplet ft on d.tempid=ft.id and ft.pastureid=d.pastureid "+
		" where d.mydate=date_format(NOW(),'%Y-%m-%d')  and iscompleted=1 and d.isuse=0 " +
		" and d.pastureid =(SELECT column_default  FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()

	if err1 == nil && err2 == nil {

		for i := 0; i < len(queryIdList); i++ {
			id := queryIdList[i]["id"]
			projName := queryIdList[i]["projName"]

			listData := make(map[string]interface{})

			listData["farmId"] = 4090
			listData["id"] = id
			listData["projName"] = projName

			feedList := []interface{}{}

			for j := 0; j < len(queryDataList); j++ {
				id2 := queryDataList[j]["id"]
				if id == id2 {
					dataList := make(map[string]interface{})
					dataList["dropDate"] = queryDataList[j]["dropDate"]
					dataList["times"] = queryDataList[j]["times"]
					dataList["tmrNo"] = queryDataList[j]["tmrNo"]
					dataList["tName"] = queryDataList[j]["tName"]
					dataList["dName"] = queryDataList[j]["dName"]

					expWeight, _ := strconv.ParseFloat(queryDataList[j]["expWeight"].(string), 64)
					actualWeight, _ := strconv.ParseFloat((queryDataList[j]["actualWeight"]).(string), 64)


					dataList["expWeight"] = expWeight
					dataList["actualWeight"] = actualWeight

					dataList["endTime"] = queryDataList[j]["endTime"]
					dataList["penId"] = queryDataList[j]["penId"]
					dataList["penName"] = queryDataList[j]["penName"]
					dataList["cowCount"] = queryDataList[j]["cowCount"]
					dataList["sort"] = queryDataList[j]["sort"]
					dataList["ftId"] = queryDataList[j]["ftId"]
					dataList["ftName"] = queryDataList[j]["ftName"]
					feedList = append(feedList, dataList)
				}
			}
			listData["data"] = feedList
			jsonStr, _ := json.Marshal(listData)

			postData := make(map[string]string)
			postData["formData"] = string(jsonStr)
			fmt.Println(&postData)
			data := util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDeviceFeeding", &postData)
			// todo === 修改d isuse =1
			appG.Response(http.StatusOK, e.SUCCESS, string(data))

		}
	}

	//data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:86/kaps-cow/api/tmr/getMaterial")

}