| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735 | 
							- package api
 
- import (
 
- 	"../../pkg/logging"
 
- 	"../../pkg/util"
 
- 	"../../routers/restful"
 
- 	"encoding/json"
 
- 	"fmt"
 
- 	"github.com/Anderson-Lu/gofasion/gofasion"
 
- 	"github.com/gin-gonic/gin"
 
- 	"github.com/hequan2017/go-admin/pkg/e"
 
- 	"github.com/robfig/cron"
 
- 	"io/ioutil"
 
- 	"log"
 
- 	"net/http"
 
- 	"strconv"
 
- 	"time"
 
- 	"../../pkg/app"
 
- 	//"time"
 
- 	"../../pkg/setting"
 
- )
 
- func GetDorm(c *gin.Context) {
 
- 	appG := app.Gin{C: c}
 
- 	if setting.ServerSetting.GRFD != "1"{  //格润富德
 
- 		appG.Response(http.StatusOK, e.SUCCESS, nil)
 
- 		return
 
- 	}
 
- 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 	fsion := gofasion.NewFasion(string(dataByte))
 
- 	pastureid := fsion.Get("pastureid").ValueStr()
 
- 	err := GetMaterialCategory(pastureid) //饲料分类
 
- 	if err != nil{
 
- 		appG.Response(http.StatusOK, e.ERROR, "饲料分类同步失败:"+err.Error())
 
- 		return
 
- 	}
 
- 	err = GetCowCategory(pastureid)  // 牲畜类别
 
- 	if err != nil{
 
- 		appG.Response(http.StatusOK, e.ERROR, "牲畜类别同步失败:"+err.Error())
 
- 		return
 
- 	}
 
- 	err = GetDormBar(pastureid)   // 栏舍
 
- 	if err != nil{
 
- 		appG.Response(http.StatusOK, e.ERROR, "栏舍同步失败:"+err.Error())
 
- 		return
 
- 	}
 
- 	err = GetMaterial(pastureid) //饲料
 
- 	if err != nil{
 
- 		appG.Response(http.StatusOK, e.ERROR, "饲料同步失败:"+err.Error())
 
- 		return
 
- 	}
 
- 	err = GetFormula(pastureid) // 配方
 
- 	if err != nil{
 
- 		appG.Response(http.StatusOK, e.ERROR, "配方同步失败:"+err.Error())
 
- 		return
 
- 	}
 
- 	appG.Response(http.StatusOK, e.SUCCESS, nil)
 
- }
 
- func GetDormBar(pastureid string)error {
 
- 	//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()
 
- 			// 开启事务
 
- 			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()
 
- 				}
 
- 			}()
 
- 			//feedpData := feedpData[:10]
 
- 			valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,bname  FROM bar WHERE  pastureid = ?",pastureid).QueryString()
 
- 			mt :=  make(map[string]string)
 
- 			for _, v := range valuesMap {
 
- 				mt[v["bname"]] = v["backup2"]
 
- 			}
 
- 			ise := false
 
- 			for _, val := range feedpData {
 
- 				penId := val.PenId
 
- 				penName := val.PenName
 
- 				cowCount := val.CowCount
 
- 				ccountRatio := val.CcountRatio
 
- 				//createdAt := val.CreatedAt
 
- 				modifiedAt := val.ModifiedAt
 
- 				isexec := false
 
- 				if _,ok :=mt[penName]; ok{
 
- 					if mt[penName] == modifiedAt{
 
- 						continue
 
- 					}
 
- 				}else{
 
- 					isexec = true
 
- 				}
 
- 				ise = true
 
- 				fmt.Println(pastureid,penId, penName, cowCount, ccountRatio,modifiedAt,mt[penName])
 
- 				ids, err := setting.SnowIds.NextId()
 
- 				if err != nil {
 
- 					ids = time.Now().UnixNano()
 
- 					logging.Info("create SnowIds err", err)
 
- 				}
 
- 				_, err = tx.Exec("insert into bar(id,pastureid,bcode,backup1,backup2,bname,enable) "+
 
- 					" values(?,?,?,?,?,?,1)"+
 
- 					" ON DUPLICATE KEY UPDATE bcode=?,backup2=?",
 
- 					ids, pastureid, penId,penId,modifiedAt, penName,penId,modifiedAt)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 				_, 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 barname=?,ccount=(if(?='',0,?)),ratio=REPLACE(?,'%',''),ccountratio=REPLACE(?,'%','')*(if(?='',0,?))",
 
- 					ids, pastureid, pastureid, penName, penName, cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, penName,
 
- 					cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount)
 
- 				if isexec{  //不配置配方,不去新增feedp
 
- 					_, err = tx.Exec(`UPDATE feedp set ccount=(if(?='',0,?)),ratio=REPLACE(?,'%',''),ccountratio=REPLACE(?,'%','')*(if(?='',0,?))/100 
 
- 							where barid = (select id from bar where pastureid=? and bname=?) and pastureid = ?`,
 
- 						cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, pastureid,penName,pastureid)
 
- 					if err != nil {
 
- 						return  err
 
- 					}
 
- 					_, err = tx.Exec(`UPDATE fpdetail  fpd
 
- 								JOIN feedp fp ON fp.pastureid = fpd.pastureid AND fp.barid =fpd.barid
 
- 								SET 
 
- 								fpd.weight = weight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio)
 
- 								WHERE fpd.pastureid = ? and fp.barid =(select id from bar where pastureid=? and bname=?)`,pastureid,pastureid,penName)
 
- 					if err != nil {
 
- 						return  err
 
- 					}
 
- 					_, err = tx.Exec("call updateLPPbyFPChange((select id from bar where pastureid=? and bname=?),?)",pastureid,penName,pastureid)
 
- 					if err != nil {
 
- 						return  err
 
- 					}
 
- 				}
 
- 			}
 
- 			if ise{
 
- 				_, err = tx.Exec(`UPDATE fpdetail  fpd
 
- 								JOIN feedp fp ON fp.pastureid = fpd.pastureid AND fp.barid =fpd.barid
 
- 								SET 
 
- 								fp.feedweight = fp.feedweight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio),
 
- 								fp.ftweight = fp.ftweight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio),
 
- 								fpd.ccountradio =fp.ratio ,
 
- 								fpd.cowcount =fp.ccount
 
- 								WHERE fpd.pastureid = ? `,pastureid)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return  nil
 
- }
 
- func GetMaterial(pastureid string) error{
 
- 	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 {
 
- 			// 开启事务
 
- 			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()
 
- 				}
 
- 			}()
 
- 			valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,fname  FROM feed WHERE  pastureid = ?",pastureid).QueryString()
 
- 			mt :=  make(map[string]string)
 
- 			for _, v := range valuesMap {
 
- 				mt[v["fname"]] = v["backup2"]
 
- 			}
 
- 			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
 
- 				if _,ok :=mt[fName]; ok{
 
- 					if mt[fName] == modifiedAt{
 
- 						continue
 
- 					}
 
- 				}
 
- 				fmt.Println(pastureid,fName, feedclassName, createdAt, modifiedAt)
 
- 				ids, err := setting.SnowIds.NextId()
 
- 				if err != nil {
 
- 					ids = time.Now().UnixNano()
 
- 					logging.Info("create SnowIds err", err)
 
- 				}
 
- 				_, err = tx.Exec("insert into feed(id,pastureid,feedcode,backup1,backup2,fname,fclass,fclassid,uprice,dry) "+
 
- 					" values(?,?,?,?,?,?,?,(select id from feedclass where fcname=? and pastureid=?),(if(?='',0,?)),(if(?='' or ?='~',0,?)))"+
 
- 					" ON DUPLICATE KEY UPDATE feedcode=?,backup2=?,fname=?,fclass=?,fclassid=(select id from feedclass where fcname=? and pastureid=?)," +
 
- 					" uprice=(if(?='',uprice,?)),dry=(if(?='' or ?='~',dry,?))",
 
- 					ids, pastureid, fId,fId,modifiedAt, fName, feedclassName, feedclassName, pastureid, price, price, dryMatter, dryMatter, dryMatter,fId,modifiedAt, fName, feedclassName, feedclassName, pastureid, price, price, dryMatter, dryMatter, dryMatter)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 				_, err = tx.Exec(" insert into feednur(id,pastureid,fid,fname,price,dry,fndate) "+
 
- 					" values(?,?,(select id from feed where fname=? and pastureid=?),?,(if(?='',0,?)),(if(?='' or ?='~',0,?)),now() ) "+
 
- 					" ON DUPLICATE KEY UPDATE price=(if(?='',0,?)),dry=(if(?='' or ?='~',0,?)),fndate=now() ",
 
- 					ids, pastureid, fName,pastureid, fName, price, price, dryMatter, dryMatter, dryMatter, price, price, dryMatter, dryMatter, dryMatter)
 
- 				if err != nil {
 
- 					fmt.Println(err)
 
- 					return  err
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
-  return nil
 
- }
 
- func GetMaterialCategory(pastureid string)error {
 
- 	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()
 
- 			// 开启事务
 
- 			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(pastureid,feedclassId,feedclassName,createdAt,modifiedAt)
 
- 				ids, err := setting.SnowIds.NextId()
 
- 				if err != nil {
 
- 					ids = time.Now().UnixNano()
 
- 					logging.Info("create SnowIds err", err)
 
- 				}
 
- 				_, err = tx.Exec("insert into feedclass(id,pastureid,fcname,fccode,backup1,bigfeedclassid,bigfeedclassname,sort,`enable`) values(?,?,?,?,?,?,?,?,?)"+
 
- 					" ON DUPLICATE KEY UPDATE fccode=?,backup1=?",
 
- 					ids, pastureid, feedclassName, feedclassId,feedclassId, 3, "精粗各半", 0, 1, feedclassId, feedclassId)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- func GetCowCategory(pastureid string)error {
 
- 	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()
 
- 			// 开启事务
 
- 			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(pastureid,cowClassCode, cowClassName, createdAt, modifiedAt)
 
- 				ids, err := setting.SnowIds.NextId()
 
- 				if err != nil {
 
- 					ids = time.Now().UnixNano()
 
- 					logging.Info("create SnowIds err", err)
 
- 				}
 
- 				_, err = tx.Exec("insert into cowclass(id,pastureid,classcode,backup1,classname) values(?,?,?,?,?) "+
 
- 					" ON DUPLICATE KEY UPDATE classcode=?",
 
- 					ids, pastureid, cowClassCode,cowClassCode, cowClassName,cowClassCode)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- func GetFormula(pastureid string)error {
 
- 	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
 
- 		println(len(feedpData))
 
- 		if status == 0 {
 
- 			//dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 			//fsion := gofasion.NewFasion(string(dataByte))
 
- 			//pastureid := fsion.Get("pastureid").ValueStr()
 
- 			// 开启事务
 
- 			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()
 
- 				}
 
- 			}()
 
- 			valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,tname  FROM feedtemplet WHERE  pastureid = ?",pastureid).QueryString()
 
- 			mt :=  make(map[string]string)
 
- 			for _, v := range valuesMap {
 
- 				mt[v["tname"]] = v["backup2"]
 
- 			}
 
- 			for _, val := range feedpData {
 
- 				ftId := val.FtId
 
- 				ftName := val.FtName
 
- 				feedList := val.FeedList
 
- 				//createdAt := val.CreatedAt
 
- 				modifiedAt := val.ModifiedAt
 
- 				if _,ok :=mt[ftName]; ok{
 
- 					if mt[ftName] == modifiedAt{
 
- 						continue
 
- 					}
 
- 				}
 
- 				println(val.FtName)
 
- 				ids, err := setting.SnowIds.NextId()
 
- 				if err != nil {
 
- 					ids = time.Now().UnixNano()
 
- 					logging.Info("create SnowIds err", err)
 
- 				}
 
- 				_, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,backup1,backup2,tname,fttypeid,fttype)  values(?,?,null,?,?,?,?,1,'饲喂配方') "+
 
- 					" ON DUPLICATE KEY UPDATE tcode=?,backup2= ?",
 
- 					ids, pastureid, ftId,ftId,modifiedAt, ftName, ftId,modifiedAt)
 
- 				if err != nil {
 
- 					return  err
 
- 				}
 
- 				valuesMap2, _ := tx.SQL("select id,ftid,fname,fid,fweight,autosecond,autosecondname from ftdetail where ftid= " +
 
- 					" (select id from feedtemplet where pastureid=? and tname=? limit 1 )",pastureid, ftName).QueryString()
 
- 				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
 
- 					allowableError := val.AllowableError
 
- 					autosecond := val.Autosecond
 
- 					tx.Exec("update feed set allowratio=if(?='',allowratio,?) where pastureid=? and fname=? ",allowableError,allowableError,pastureid, fName)
 
- 					if valuesMap2!=nil{
 
- 						for _, v := range valuesMap2 {
 
- 							fName2 := v["fname"]
 
- 							autosecond2 := v["autosecond"]
 
- 							if(fName==fName2 && (autosecond2 != "")){
 
- 								autosecond=autosecond2
 
- 							}
 
- 						}
 
- 					}
 
- 					ids, err := setting.SnowIds.NextId()
 
- 					if err != nil {
 
- 						ids = time.Now().UnixNano()
 
- 						logging.Info("create SnowIds err", err)
 
- 					}
 
- 					_, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup)  "+
 
- 						" values(?,?,(select id from feedtemplet where pastureid=? and tname=? limit 1)," +
 
- 						" (select id from feed where pastureid=? and backup1=? limit 1),?,?,?,(if(?='',0,?)),?,?) " ,
 
- 						ids, pastureid, pastureid, ftName, pastureid, fId, fName, fodderWeight, mixNo,autosecond,autosecond, autosecond,fName)
 
- 					if err != nil {
 
- 						return  err
 
- 					}
 
- 					_, err = tx.Exec("call updateFPbyFTChange((select id from feedtemplet where pastureid=? and tname=? limit 1),?,(select fttypeid from feedtemplet where pastureid=? and tname=? limit 1))",pastureid,ftName,pastureid,pastureid,ftName)
 
- 					if err != nil {
 
- 						return  err
 
- 					}
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- func AddOtherDevice() {
 
- 	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,round(d.lweight,2) lWeight,date_format(d.mydate,'%Y-%m-%d') as loadDate,d.SORT as tmrNo,d.Times as times,ft.backup1 as ftId,d.templetName  as ftName,f.backup1 as fId,"+
 
- 		" de.Fname as fName,fc.FCNAME as feedclassName,de.SORT as sort,de.feedallowratio as allowableError, "+
 
- 		" cast(ifnull(de.LWEIGHT,0) as decimal(10,2)) as expWeight,cast(ifnull(de.ActualWeightMinus,0) 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)
 
- 			err = util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDevice", &postData)
 
- 			if err != nil{
 
- 				fmt.Println("AddOtherDevice err:",err)
 
- 				logging.Error("AddOtherDevice err:",err)
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func AddOtherDeviceFeeding() {
 
- 	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.backup1 as penId,d2.fname as penName,fp.CCOUNT as cowCount, d2.SORT as sort,d.templetName ftName, ft.backup1 ftId,"+
 
- 		" ifnull(d2.LWEIGHT,0) 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)
 
- 			err  = util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDeviceFeeding", &postData)
 
- 			if err != nil{
 
- 				fmt.Println("AddOtherDeviceFeeding err:",err)
 
- 				logging.Error("AddOtherDeviceFeeding err:",err)
 
- 			}else {
 
- 				_,err = tx.Exec(`update downloadedplan set isuse=1 where mydate=date_format(NOW(),'%Y-%m-%d')  and iscompleted=1 and isuse=0	
 
- 							and pastureid =(SELECT column_default  FROM information_schema.COLUMNS WHERE table_name = 'recweight' 
 
- 							AND table_schema = 'tmrwatch' AND column_name = 'pastureid') `)
 
- 				if err != nil{
 
- 					logging.Error("update downloadedplan err:",err)
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	//data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:86/kaps-cow/api/tmr/getMaterial")
 
- }
 
- func PostTmrData(){
 
- 	defer func() { // 必须要先声明defer
 
- 		if err := recover(); err != nil {
 
- 			fmt.Printf("CronTest pnic err%+v \n", err)
 
- 			logging.Error("panic recover err ", err)
 
- 			//println("pnic err",err.(error).Error()) // 这里的err其实就是panic传入的内容,55
 
- 		}
 
- 	}()
 
- 	println("开始执行")
 
- 	AddOtherDevice()
 
- 	AddOtherDeviceFeeding()
 
- }
 
- func CronGRFD() {
 
- 	defer func() { // 必须要先声明defer
 
- 		if err := recover(); err != nil {
 
- 			fmt.Printf("CronTest pnic err%+v \n", err)
 
- 			logging.Error("panic recover err ", err)
 
- 		}
 
- 	}()
 
- 	log.Println("Starting CronWXwork...")
 
- 	c := cron.New()
 
- 	_, err := c.AddFunc("0/3 * * * *", PostTmrData) //* * * * *, 从分钟开始 每5分钟
 
- 	if err != nil {
 
- 		println("cron4 err", err.Error())
 
- 	}
 
- 	c.Start()
 
- }
 
 
  |