package api import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" "strings" "time" "tmr-watch/conf/setting" "tmr-watch/http/handle/restful" "tmr-watch/pkg/app" "tmr-watch/pkg/logging" "tmr-watch/pkg/util" "github.com/Anderson-Lu/gofasion/gofasion" "github.com/gin-gonic/gin" "github.com/hequan2017/go-admin/pkg/e" "github.com/robfig/cron" "github.com/xormplus/xorm" ) // 本部分是格润富德牧场系统 的下发和上传功能(可咨询刘欢) func GetDorm(c *gin.Context) { appG := app.Gin{C: c} if setting.ServerSetting.GRFD != "1" { //是否启用(格润富德) appG.Response(http.StatusOK, e.SUCCESS, nil) return } logging.Info("GetDorm", c.Keys, c.Request.RemoteAddr) 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}", setting.ServerSetting.GRFDURL+"/grfd-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"] } //已关闭的栏舍不启用 _, err = tx.Exec("update bar set enable = 2 where pastureid = ? and enable = 0", pastureid) if err != nil { return err } _, err = tx.Exec("update bar set enable = 0 where pastureid = ? and enable < 2", pastureid) if err != nil { return err } logging.Info("GetDorm feedpData:", feedpData) 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 ids, err := setting.SnowIds.NextId() if err != nil { ids = time.Now().UnixNano() logging.Info("create SnowIds err", err) } //首先将所有栏舍禁用 _, err = tx.Exec("update bar set bname = ? where bcode = ?", penName, penId) if err != nil { return err } _, err = tx.Exec("insert into bar(id,pastureid,bcode,backup1,backup2,bname,enable) "+ " values(?,?,?,?,?,?,1)"+ " ON DUPLICATE KEY UPDATE bcode=?,backup2=?,enable=if(enable = 2,0,1)", 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,?))/100)"+ " ON DUPLICATE KEY UPDATE barname=?,ccount=if(?='',0,?),ccountratio=ratio*ccount/100", ids, pastureid, pastureid, penName, penName, cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, penName, cowCount, cowCount) if err != nil { return err } if !isexec { //第一次新增栏舍,不去更新feedp _, err = tx.Exec(` UPDATE feedp fp SET fp.ftweight= IFNULL(IF( (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0, IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio, IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio + IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount ),0),fp.feedweight = IFNULL(IF( (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0, IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio, IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio + IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount ),0) +fp.supplyweight WHERE fp.pastureid = ? AND fp.barid =(SELECT id FROM bar WHERE pastureid=? AND bname=?)`, pastureid, pastureid, penName) if err != nil { return err } _, err = tx.Exec(` UPDATE fpdetail fpd INNER JOIN feedp fp ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid SET fpd.ccountradio =fp.ratio, fpd.cowcount =fp.ccount, fpd.weight = fp.feedweight*fpd.tratio/100, ptsrate=fp.supplyweight/(fp.feedweight) WHERE fp.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 } } } _, err = tx.Exec("update bar set enable = 0 where pastureid = ? and enable = 2", pastureid) if err != nil { return err } } } return nil } func GetMaterial(pastureid string) error { data := util.Send_Message1("{\"farmId\":4090}", setting.ServerSetting.GRFDURL+"/grfd-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 fmt.Println(fName) if _, ok := mt[fName]; ok { if mt[fName] == modifiedAt { continue } } 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}", setting.ServerSetting.GRFDURL+"/grfd-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 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}", setting.ServerSetting.GRFDURL+"/grfd-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}", setting.ServerSetting.GRFDURL+"/grfd-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() // 开启事务 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 } } 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() err1 := tx.Begin() defer func() { switch { case err1 != nil: logging.Error("tx.Begin 事务启动失败__error:", err1) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } if tx != nil { tx.Close() } }() queryIdList, err1 := tx.SQL(`SELECT d.pid +UNIX_TIMESTAMP(d.mydate) id,d.pid did,d.projname projName ,DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate FROM downloadedplan d WHERE (d.mydate=DATE_FORMAT(NOW(),'%Y-%m-%d')OR d.mydate=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') ) 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') AND (SELECT COUNT(*) FROM downloadplandtl1 d1 WHERE d.id=d1.PID AND d.pastureid=d1.pastureid AND d1.type = 0)>0 AND (SELECT COUNT(*) FROM downloadedplan WHERE pastureid = d.pastureid AND downloadedplan.lpplantype=1 and mydate = d.mydate AND pid = d.pid AND iscompleted = 0) = 0 GROUP BY d.pid +UNIX_TIMESTAMP(d.mydate)`).Query().List() queryDataList, err2 := tx.SQL(`SELECT d.pid +UNIX_TIMESTAMP(d.mydate) 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 JOIN downloadplandtl1 de ON d.id=de.PID AND d.pastureid=de.pastureid AND de.type = 0 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') OR d.mydate=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') ) 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') AND (SELECT COUNT(*) FROM downloadplandtl1 d1 WHERE d.id=d1.PID AND d.pastureid=d1.pastureid AND d1.type = 0)>0 AND (SELECT COUNT(*) FROM downloadedplan WHERE pastureid = d.pastureid AND downloadedplan.lpplantype=1 and mydate = d.mydate AND pid = d.pid AND iscompleted = 0) = 0 group by d.pid,de.Fname`).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"] xorm.String(queryDataList[j]["expWeight"]) expWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["expWeight"]), 64) actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]), 64) lWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["lWeight"]), 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", setting.ServerSetting.GRFDURL+"/grfd-cow/api/tmr/addOtherDevice", &postData) if (err != nil) && (strings.Contains(err.Error(), "ID已存在") == false) { logging.Error("AddOtherDevice err:", err) } else { _, err = tx.Exec(`update downloadedplan set isuse=1 where pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') and pid =? and mydate = ? `, queryIdList[i]["did"], queryIdList[i]["mydate"]) if err != nil { logging.Error("update downloadedplan err:", err) } } } } } func AddOtherDeviceFeeding() { tx := restful.Engine.NewSession() err1 := tx.Begin() defer func() { switch { case err1 != nil: logging.Error("tx.Begin 事务启动失败__error:", err1) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } if tx != nil { tx.Close() } }() // TODO isuse2 =0 待定 queryIdList, err1 := tx.SQL(`SELECT d.pid +UNIX_TIMESTAMP(d.mydate) id,d.pid did,d.projname projName,DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate FROM downloadedplan d WHERE (d.mydate=DATE_FORMAT(NOW(),'%Y-%m-%d')OR d.mydate=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') ) AND iscompleted=1 AND d.isUse=0 AND (SELECT COUNT(*) FROM downloadplandtl2 d2 WHERE d.id=d2.PID AND d.pastureid=d2.pastureid AND d2.type = 0)>0 AND (SELECT COUNT(*) FROM downloadedplan WHERE pastureid = d.pastureid AND mydate = d.mydate AND pid = d.pid AND iscompleted = 0) = 0`).Query().List() queryDataList, err2 := tx.SQL(` SELECT d.pid +UNIX_TIMESTAMP(d.mydate) 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.backup1 ftId, IFNULL(d2.LWEIGHT,0) AS expWeight,IF(d2.ActualWeightMinus<0,0,d2.ActualWeightMinus) AS actualWeight,DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') AS endTime,d.tmrtname AS tName,'' dName FROM downloadedplan d JOIN downloadplandtl2 d2 ON d.id=d2.PID AND d.pastureid=d2.pastureid AND d2.type = 0 LEFT JOIN bar ON d2.fbarid=bar.id AND bar.pastureid=d2.pastureid LEFT JOIN feedpdate fp ON d2.fbarid=fp.barid AND fp.pastureid=d2.pastureid AND fp.date = d2.date LEFT JOIN feedtemplet ft ON d.tempid=ft.id AND ft.pastureid=d.pastureid WHERE (d.mydate=DATE_FORMAT(NOW(),'%Y-%m-%d')OR d.mydate=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') ) AND iscompleted=1 AND d.isuse2=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(xorm.String(queryDataList[j]["expWeight"]), 64) actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]), 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", setting.ServerSetting.GRFDURL+"/grfd-cow/api/tmr/addOtherDeviceFeeding", &postData) if err != nil { logging.Error("AddOtherDeviceFeeding err:", err) } else { _, err = tx.Exec(`update downloadedplan set isuse2=1 where pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') and pid =? and mydate = ? `, queryIdList[i]["did"], queryIdList[i]["mydate"]) 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") } // PostTmrData 定时任务 func PostTmrData() { defer func() { // 必须要先声明defer if err := recover(); err != nil { logging.Error("panic recover err ", err) } }() //上传饲料 AddOtherDevice() //上传栏舍 AddOtherDeviceFeeding() } func CronGRFD() { defer func() { // 必须要先声明defer if err := recover(); err != nil { fmt.Printf("CronTest pnic err%+v \n", err) logging.Error("CronGRFD panic recover err ", err) } }() log.Println("Starting CronWXwork...") c := cron.New() err := c.AddFunc("0/55 * * * *", PostTmrData) //* * * * *, 从分钟开始 每55分钟执行一次 if err != nil { println("cron4 err", err.Error()) } c.Start() }