8c3045102cbbdf2af4180033ae7527e0df35bf1f.svn-base 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. package api
  2. import (
  3. "../../pkg/logging"
  4. "../../pkg/util"
  5. "../../routers/restful"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/Anderson-Lu/gofasion/gofasion"
  9. "github.com/gin-gonic/gin"
  10. "github.com/hequan2017/go-admin/pkg/e"
  11. "github.com/robfig/cron"
  12. "github.com/xormplus/xorm"
  13. "io/ioutil"
  14. "log"
  15. "net/http"
  16. "strconv"
  17. "time"
  18. "../../pkg/app"
  19. //"time"
  20. "../../pkg/setting"
  21. )
  22. func GetDorm(c *gin.Context) {
  23. appG := app.Gin{C: c}
  24. if setting.ServerSetting.GRFD != "1"{ //格润富德
  25. appG.Response(http.StatusOK, e.SUCCESS, nil)
  26. return
  27. }
  28. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  29. fsion := gofasion.NewFasion(string(dataByte))
  30. pastureid := fsion.Get("pastureid").ValueStr()
  31. err := GetMaterialCategory(pastureid) //饲料分类
  32. if err != nil{
  33. appG.Response(http.StatusOK, e.ERROR, "饲料分类同步失败:"+err.Error())
  34. return
  35. }
  36. err = GetCowCategory(pastureid) // 牲畜类别
  37. if err != nil{
  38. appG.Response(http.StatusOK, e.ERROR, "牲畜类别同步失败:"+err.Error())
  39. return
  40. }
  41. err = GetDormBar(pastureid) // 栏舍
  42. if err != nil{
  43. appG.Response(http.StatusOK, e.ERROR, "栏舍同步失败:"+err.Error())
  44. return
  45. }
  46. err = GetMaterial(pastureid) //饲料
  47. if err != nil{
  48. appG.Response(http.StatusOK, e.ERROR, "饲料同步失败:"+err.Error())
  49. return
  50. }
  51. err = GetFormula(pastureid) // 配方
  52. if err != nil{
  53. appG.Response(http.StatusOK, e.ERROR, "配方同步失败:"+err.Error())
  54. return
  55. }
  56. appG.Response(http.StatusOK, e.SUCCESS, nil)
  57. }
  58. func GetDormBar(pastureid string)error {
  59. //appG := app.Gin{C: c}
  60. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  61. //fsion := gofasion.NewFasion(string(dataByte))
  62. //sqlnamestr := fsion.Get("name").ValueStr()
  63. //offset := fsion.Get("offset").ValueDefaultInt(0)
  64. //pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  65. //returntype := fsion.Get("returntype").ValueDefaultStr("map")
  66. data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getDorm")
  67. if data != nil {
  68. var feedp util.Feedp
  69. json.Unmarshal(data, &feedp)
  70. status := feedp.Status
  71. feedpData := feedp.Data
  72. if status == 0 {
  73. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  74. //fsion := gofasion.NewFasion(string(dataByte))
  75. //pastureid := fsion.Get("pastureid").ValueStr()
  76. // 开启事务
  77. tx := restful.Engine.NewSession()
  78. err := tx.Begin()
  79. defer func() {
  80. switch {
  81. case err != nil:
  82. logging.Error("tx.Begin 事务启动失败__error:", err)
  83. if tx != nil {
  84. tx.Rollback()
  85. }
  86. default:
  87. if tx != nil {
  88. err = tx.Commit()
  89. }
  90. }
  91. if tx != nil {
  92. tx.Close()
  93. }
  94. }()
  95. //feedpData := feedpData[:10]
  96. valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,bname FROM bar WHERE pastureid = ?",pastureid).QueryString()
  97. mt := make(map[string]string)
  98. for _, v := range valuesMap {
  99. mt[v["bname"]] = v["backup2"]
  100. }
  101. ise := false
  102. for _, val := range feedpData {
  103. penId := val.PenId
  104. penName := val.PenName
  105. cowCount := val.CowCount
  106. ccountRatio := val.CcountRatio
  107. //createdAt := val.CreatedAt
  108. modifiedAt := val.ModifiedAt
  109. isexec := false
  110. if _,ok :=mt[penName]; ok{
  111. if mt[penName] == modifiedAt{
  112. continue
  113. }
  114. }else{
  115. isexec = true
  116. }
  117. ise = true
  118. fmt.Println(pastureid,penId, penName, cowCount, ccountRatio,modifiedAt,mt[penName])
  119. ids, err := setting.SnowIds.NextId()
  120. if err != nil {
  121. ids = time.Now().UnixNano()
  122. logging.Info("create SnowIds err", err)
  123. }
  124. _, err = tx.Exec("insert into bar(id,pastureid,bcode,backup1,backup2,bname,enable) "+
  125. " values(?,?,?,?,?,?,1)"+
  126. " ON DUPLICATE KEY UPDATE bcode=?,backup2=?",
  127. ids, pastureid, penId,penId,modifiedAt, penName,penId,modifiedAt)
  128. if err != nil {
  129. return err
  130. }
  131. _, err = tx.Exec("insert into feedp(id,pastureid,barid,barname,ccount,ratio,ccountratio) "+
  132. " values(?,?,(select id from bar where pastureid=? and bname=?),?,(if(?='',0,?)),REPLACE(?,'%'," +
  133. "''),REPLACE(?,'%','')*(if(?='',0,?))/100)"+
  134. " ON DUPLICATE KEY UPDATE barname=?,ccount=if(?='',0,?),ccountratio=ratio*ccount/100",
  135. ids, pastureid, pastureid, penName, penName, cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, penName,
  136. cowCount, cowCount)
  137. if err != nil {
  138. return err
  139. }
  140. if !isexec{ //第一次新增栏舍,不去更新feedp
  141. //_, err = tx.Exec(`UPDATE feedp set ccount=(if(?='',0,?)),ratio=REPLACE(?,'%',''),ccountratio=REPLACE(?,'%','')*(if(?='',0,?))/100
  142. // where barid = (select id from bar where pastureid=? and bname=?) and pastureid = ?`,
  143. // cowCount, cowCount, ccountRatio, ccountRatio, cowCount, cowCount, pastureid,penName,pastureid)
  144. //
  145. //if err != nil {
  146. // return err
  147. //}
  148. _, err = tx.Exec(`UPDATE fpdetail fpd
  149. JOIN feedp fp ON fp.pastureid = fpd.pastureid AND fp.barid =fpd.barid
  150. SET
  151. fpd.weight = ifnull(weight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio),0)
  152. WHERE fpd.pastureid = ? and fp.barid =(select id from bar where pastureid=? and bname=?)`,pastureid,pastureid,penName)
  153. if err != nil {
  154. return err
  155. }
  156. _, err = tx.Exec("call updateLPPbyFPChange((select id from bar where pastureid=? and bname=?),?)",pastureid,penName,pastureid)
  157. if err != nil {
  158. return err
  159. }
  160. }
  161. }
  162. if ise{
  163. _, err = tx.Exec(`UPDATE fpdetail fpd
  164. JOIN feedp fp ON fp.pastureid = fpd.pastureid AND fp.barid =fpd.barid
  165. SET
  166. fp.feedweight = ifnull(fp.feedweight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio),0),
  167. fp.ftweight = ifnull(fp.ftweight *(fp.ccount*fp.ratio/fpd.cowcount/fpd.ccountradio),0),
  168. fpd.ccountradio =fp.ratio ,
  169. fpd.cowcount =fp.ccount
  170. WHERE fpd.pastureid = ? `,pastureid)
  171. if err != nil {
  172. return err
  173. }
  174. }
  175. }
  176. }
  177. return nil
  178. }
  179. func GetMaterial(pastureid string) error{
  180. data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getMaterial")
  181. if data != nil {
  182. var feed util.Feed
  183. json.Unmarshal(data, &feed)
  184. status := feed.Status
  185. feedpData := feed.Data
  186. if status == 0 {
  187. // 开启事务
  188. tx := restful.Engine.NewSession()
  189. err := tx.Begin()
  190. defer func() {
  191. switch {
  192. case err != nil:
  193. logging.Error("tx.Begin 事务启动失败__error:", err)
  194. if tx != nil {
  195. tx.Rollback()
  196. }
  197. default:
  198. if tx != nil {
  199. err = tx.Commit()
  200. }
  201. }
  202. if tx != nil {
  203. tx.Close()
  204. }
  205. }()
  206. valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,fname FROM feed WHERE pastureid = ?",pastureid).QueryString()
  207. mt := make(map[string]string)
  208. for _, v := range valuesMap {
  209. mt[v["fname"]] = v["backup2"]
  210. }
  211. for _, val := range feedpData {
  212. fId := val.FId
  213. fName := val.FName
  214. price := val.Price
  215. dryMatter := val.DryMatter
  216. //autoChange := val.AutoChange
  217. //allowDev := val.AllowDev
  218. feedclassName := val.FeedclassName
  219. createdAt := val.CreatedAt
  220. modifiedAt := val.ModifiedAt
  221. if _,ok :=mt[fName]; ok{
  222. if mt[fName] == modifiedAt{
  223. continue
  224. }
  225. }
  226. fmt.Println(pastureid,fName, feedclassName, createdAt, modifiedAt)
  227. ids, err := setting.SnowIds.NextId()
  228. if err != nil {
  229. ids = time.Now().UnixNano()
  230. logging.Info("create SnowIds err", err)
  231. }
  232. _, err = tx.Exec("insert into feed(id,pastureid,feedcode,backup1,backup2,fname,fclass,fclassid,uprice,dry) "+
  233. " values(?,?,?,?,?,?,?,(select id from feedclass where fcname=? and pastureid=?),(if(?='',0,?)),(if(?='' or ?='~',0,?)))"+
  234. " ON DUPLICATE KEY UPDATE feedcode=?,backup2=?,fname=?,fclass=?,fclassid=(select id from feedclass where fcname=? and pastureid=?)," +
  235. " uprice=(if(?='',uprice,?)),dry=(if(?='' or ?='~',dry,?))",
  236. 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)
  237. if err != nil {
  238. return err
  239. }
  240. _, err = tx.Exec(" insert into feednur(id,pastureid,fid,fname,price,dry,fndate) "+
  241. " values(?,?,(select id from feed where fname=? and pastureid=?),?,(if(?='',0,?)),(if(?='' or ?='~',0,?)),now() ) "+
  242. " ON DUPLICATE KEY UPDATE price=(if(?='',0,?)),dry=(if(?='' or ?='~',0,?)),fndate=now() ",
  243. ids, pastureid, fName,pastureid, fName, price, price, dryMatter, dryMatter, dryMatter, price, price, dryMatter, dryMatter, dryMatter)
  244. if err != nil {
  245. fmt.Println(err)
  246. return err
  247. }
  248. }
  249. }
  250. }
  251. return nil
  252. }
  253. func GetMaterialCategory(pastureid string)error {
  254. data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getMaterialCategory")
  255. if data != nil {
  256. var feedClass util.FeedClass
  257. json.Unmarshal(data, &feedClass)
  258. status := feedClass.Status
  259. feedpData := feedClass.Data
  260. if status == 0 {
  261. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  262. //fsion := gofasion.NewFasion(string(dataByte))
  263. //pastureid := fsion.Get("pastureid").ValueStr()
  264. // 开启事务
  265. tx := restful.Engine.NewSession()
  266. err := tx.Begin()
  267. defer func() {
  268. switch {
  269. case err != nil:
  270. logging.Error("tx.Begin 事务启动失败__error:", err)
  271. if tx != nil {
  272. tx.Rollback()
  273. }
  274. default:
  275. if tx != nil {
  276. err = tx.Commit()
  277. }
  278. }
  279. if tx != nil {
  280. tx.Close()
  281. }
  282. }()
  283. for _, val := range feedpData {
  284. feedclassName := val.FeedclassName
  285. feedclassId := val.FeedclassId
  286. createdAt := val.CreatedAt
  287. modifiedAt := val.ModifiedAt
  288. fmt.Println(pastureid,feedclassId,feedclassName,createdAt,modifiedAt)
  289. ids, err := setting.SnowIds.NextId()
  290. if err != nil {
  291. ids = time.Now().UnixNano()
  292. logging.Info("create SnowIds err", err)
  293. }
  294. _, err = tx.Exec("insert into feedclass(id,pastureid,fcname,fccode,backup1,bigfeedclassid,bigfeedclassname,sort,`enable`) values(?,?,?,?,?,?,?,?,?)"+
  295. " ON DUPLICATE KEY UPDATE fccode=?,backup1=?",
  296. ids, pastureid, feedclassName, feedclassId,feedclassId, 3, "精粗各半", 0, 1, feedclassId, feedclassId)
  297. if err != nil {
  298. return err
  299. }
  300. }
  301. }
  302. }
  303. return nil
  304. }
  305. func GetCowCategory(pastureid string)error {
  306. data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getCowCategory")
  307. if data != nil {
  308. var cowClass util.CowClass
  309. json.Unmarshal(data, &cowClass)
  310. status := cowClass.Status
  311. feedpData := cowClass.Data
  312. if status == 0 {
  313. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  314. //fsion := gofasion.NewFasion(string(dataByte))
  315. //pastureid := fsion.Get("pastureid").ValueStr()
  316. // 开启事务
  317. tx := restful.Engine.NewSession()
  318. err := tx.Begin()
  319. defer func() {
  320. switch {
  321. case err != nil:
  322. logging.Error("tx.Begin 事务启动失败__error:", err)
  323. if tx != nil {
  324. tx.Rollback()
  325. }
  326. default:
  327. if tx != nil {
  328. err = tx.Commit()
  329. }
  330. }
  331. if tx != nil {
  332. tx.Close()
  333. }
  334. }()
  335. for _, val := range feedpData {
  336. cowClassCode := val.CowClassCode
  337. cowClassName := val.CowClassName
  338. createdAt := val.CreatedAt
  339. modifiedAt := val.ModifiedAt
  340. fmt.Println(pastureid,cowClassCode, cowClassName, createdAt, modifiedAt)
  341. ids, err := setting.SnowIds.NextId()
  342. if err != nil {
  343. ids = time.Now().UnixNano()
  344. logging.Info("create SnowIds err", err)
  345. }
  346. _, err = tx.Exec("insert into cowclass(id,pastureid,classcode,backup1,classname) values(?,?,?,?,?) "+
  347. " ON DUPLICATE KEY UPDATE classcode=?",
  348. ids, pastureid, cowClassCode,cowClassCode, cowClassName,cowClassCode)
  349. if err != nil {
  350. return err
  351. }
  352. }
  353. }
  354. }
  355. return nil
  356. }
  357. func GetFormula(pastureid string)error {
  358. data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:88/kaps-cow/api/tmr/getFormula")
  359. if data != nil {
  360. var feedTemplet util.FeedTemplet
  361. json.Unmarshal(data, &feedTemplet)
  362. status := feedTemplet.Status
  363. feedpData := feedTemplet.Data
  364. println(len(feedpData))
  365. if status == 0 {
  366. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  367. //fsion := gofasion.NewFasion(string(dataByte))
  368. //pastureid := fsion.Get("pastureid").ValueStr()
  369. // 开启事务
  370. tx := restful.Engine.NewSession()
  371. err := tx.Begin()
  372. defer func() {
  373. switch {
  374. case err != nil:
  375. logging.Error("tx.Begin 事务启动失败__error:", err)
  376. if tx != nil {
  377. tx.Rollback()
  378. }
  379. default:
  380. if tx != nil {
  381. err = tx.Commit()
  382. }
  383. }
  384. if tx != nil {
  385. tx.Close()
  386. }
  387. }()
  388. valuesMap, _ := tx.SQL("SELECT ifnull(backup2,'-1')backup2,tname FROM feedtemplet WHERE pastureid = ?",pastureid).QueryString()
  389. mt := make(map[string]string)
  390. for _, v := range valuesMap {
  391. mt[v["tname"]] = v["backup2"]
  392. }
  393. for _, val := range feedpData {
  394. ftId := val.FtId
  395. ftName := val.FtName
  396. feedList := val.FeedList
  397. //createdAt := val.CreatedAt
  398. modifiedAt := val.ModifiedAt
  399. if _,ok :=mt[ftName]; ok{
  400. if mt[ftName] == modifiedAt{
  401. continue
  402. }
  403. }
  404. println(val.FtName)
  405. ids, err := setting.SnowIds.NextId()
  406. if err != nil {
  407. ids = time.Now().UnixNano()
  408. logging.Info("create SnowIds err", err)
  409. }
  410. _, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,backup1,backup2,tname,fttypeid,fttype) values(?,?,null,?,?,?,?,1,'饲喂配方') "+
  411. " ON DUPLICATE KEY UPDATE tcode=?,backup2= ?",
  412. ids, pastureid, ftId,ftId,modifiedAt, ftName, ftId,modifiedAt)
  413. if err != nil {
  414. return err
  415. }
  416. valuesMap2, _ := tx.SQL("select id,ftid,fname,fid,fweight,autosecond,autosecondname from ftdetail where ftid= " +
  417. " (select id from feedtemplet where pastureid=? and tname=? limit 1 )",pastureid, ftName).QueryString()
  418. tx.Exec("delete from ftdetail where ftid=(select id from feedtemplet where pastureid=? and tname=?) ",pastureid, ftName)
  419. for _, val := range feedList {
  420. fId := val.FId
  421. fName := val.FName
  422. fodderWeight := val.FodderWeight
  423. mixNo := val.MixNo
  424. allowableError := val.AllowableError
  425. autosecond := val.Autosecond
  426. tx.Exec("update feed set allowratio=if(?='',allowratio,?) where pastureid=? and fname=? ",allowableError,allowableError,pastureid, fName)
  427. if valuesMap2!=nil{
  428. for _, v := range valuesMap2 {
  429. fName2 := v["fname"]
  430. autosecond2 := v["autosecond"]
  431. if(fName==fName2 && (autosecond2 != "")){
  432. autosecond=autosecond2
  433. }
  434. }
  435. }
  436. ids, err := setting.SnowIds.NextId()
  437. if err != nil {
  438. ids = time.Now().UnixNano()
  439. logging.Info("create SnowIds err", err)
  440. }
  441. _, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup) "+
  442. " values(?,?,(select id from feedtemplet where pastureid=? and tname=? limit 1)," +
  443. " (select id from feed where pastureid=? and backup1=? limit 1),?,?,?,(if(?='',0,?)),?,?) " ,
  444. ids, pastureid, pastureid, ftName, pastureid, fId, fName, fodderWeight, mixNo,autosecond,autosecond, autosecond,fName)
  445. if err != nil {
  446. return err
  447. }
  448. _, 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)
  449. if err != nil {
  450. return err
  451. }
  452. }
  453. }
  454. }
  455. }
  456. return nil
  457. }
  458. func AddOtherDevice() {
  459. tx := restful.Engine.NewSession()
  460. err := tx.Begin()
  461. defer func() {
  462. switch {
  463. case err != nil:
  464. logging.Error("tx.Begin 事务启动失败__error:", err)
  465. if tx != nil {
  466. tx.Rollback()
  467. }
  468. default:
  469. if tx != nil {
  470. err = tx.Commit()
  471. }
  472. }
  473. if tx != nil {
  474. tx.Close()
  475. }
  476. }()
  477. 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 " +
  478. " and d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()
  479. queryDataList, err2 := tx.SQL("select d.pid 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,"+
  480. " de.Fname as fName,fc.FCNAME as feedclassName,de.SORT as sort,de.feedallowratio as allowableError, "+
  481. " cast(ifnull(de.LWEIGHT,0) as decimal(10,2)) as expWeight,cast(ifnull(de.ActualWeightMinus,0) as decimal(10,2)) as actualWeight,"+
  482. " date_format(de.intime,'%Y-%m-%d %H:%i:%s') as endTime ,d.tmrtname as tName ,'' dName "+
  483. " from downloadedplan d JOIN downloadplandtl1 de on d.id=de.PID and d.pastureid=de.pastureid and de.type = 0"+
  484. " 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 "+
  485. " LEFT JOIN feedclass fc on f.fclassid=fc.id and fc.pastureid=d.pastureid "+
  486. " where d.mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and d.isuse=0 " +
  487. " and d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()
  488. if err1 == nil && err2 == nil {
  489. for i := 0; i < len(queryIdList); i++ {
  490. id := queryIdList[i]["id"]
  491. projName := queryIdList[i]["projName"]
  492. listData := make(map[string]interface{})
  493. listData["farmId"] = 4090
  494. listData["id"] = id
  495. listData["projName"] = projName
  496. feedList := []interface{}{}
  497. for j := 0; j < len(queryDataList); j++ {
  498. id2 := queryDataList[j]["id"]
  499. if id == id2 {
  500. dataList := make(map[string]interface{})
  501. dataList["tmrNo"] = queryDataList[j]["tmrNo"]
  502. dataList["times"] = queryDataList[j]["times"]
  503. dataList["loadDate"] = queryDataList[j]["loadDate"]
  504. dataList["ftId"] = queryDataList[j]["ftId"]
  505. dataList["ftName"] = queryDataList[j]["ftName"]
  506. dataList["fId"] = queryDataList[j]["fId"]
  507. dataList["tName"] = queryDataList[j]["tName"]
  508. dataList["feedclassName"] = queryDataList[j]["feedclassName"]
  509. dataList["fName"] = queryDataList[j]["fName"]
  510. dataList["sort"] = queryDataList[j]["sort"]
  511. dataList["allowableError"] = queryDataList[j]["allowableError"]
  512. xorm.String(queryDataList[j]["expWeight"])
  513. expWeight, _ := strconv.ParseFloat( xorm.String(queryDataList[j]["expWeight"]) , 64)
  514. actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]), 64)
  515. lWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["lWeight"]), 64)
  516. dataList["expWeight"] = expWeight
  517. dataList["actualWeight"] = actualWeight
  518. dataList["lWeight"] = lWeight
  519. dataList["endTime"] = queryDataList[j]["endTime"]
  520. dataList["dName"] = queryDataList[j]["dName"]
  521. feedList = append(feedList, dataList)
  522. }
  523. }
  524. listData["data"] = feedList
  525. jsonStr, _ := json.Marshal(listData)
  526. postData := make(map[string]string)
  527. postData["formData"] = string(jsonStr)
  528. err = util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDevice", &postData)
  529. if err != nil{
  530. fmt.Println("AddOtherDevice err:",err)
  531. logging.Error("AddOtherDevice err:",err)
  532. }
  533. }
  534. }
  535. }
  536. func AddOtherDeviceFeeding() {
  537. tx := restful.Engine.NewSession()
  538. err := tx.Begin()
  539. defer func() {
  540. switch {
  541. case err != nil:
  542. logging.Error("tx.Begin 事务启动失败__error:", err)
  543. if tx != nil {
  544. tx.Rollback()
  545. }
  546. default:
  547. if tx != nil {
  548. err = tx.Commit()
  549. }
  550. }
  551. if tx != nil {
  552. tx.Close()
  553. }
  554. }()
  555. queryIdList, err1 := tx.SQL("select d.pid id,d.projname projName from downloadedplan d JOIN downloadplandtl2 d2 on d.id=d2.PID and d.pastureid=d2.pastureid and d2.type = 0 where d.mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and d.isuse=0 " +
  556. " and d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') group by d.id").Query().List()
  557. 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,
  558. bar.backup1 AS penId,d2.fname AS penName,fp.CCOUNT AS cowCount, d2.SORT AS sort,d.templetName ftName, ft.backup1 ftId,
  559. 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
  560. FROM downloadedplan d JOIN downloadplandtl2 d2 ON d.id=d2.PID AND d.pastureid=d2.pastureid AND d2.type = 0
  561. 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
  562. LEFT JOIN feedtemplet ft ON d.tempid=ft.id AND ft.pastureid=d.pastureid
  563. WHERE d.mydate=DATE_FORMAT(NOW(),'%Y-%m-%d') AND iscompleted=1 AND d.isuse=0
  564. AND d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid')`).Query().List()
  565. if err1 == nil && err2 == nil {
  566. for i := 0; i < len(queryIdList); i++ {
  567. id := queryIdList[i]["id"]
  568. projName := queryIdList[i]["projName"]
  569. listData := make(map[string]interface{})
  570. listData["farmId"] = 4090
  571. listData["id"] = id
  572. listData["projName"] = projName
  573. feedList := []interface{}{}
  574. for j := 0; j < len(queryDataList); j++ {
  575. id2 := queryDataList[j]["id"]
  576. if id == id2 {
  577. dataList := make(map[string]interface{})
  578. dataList["dropDate"] = queryDataList[j]["dropDate"]
  579. dataList["times"] = queryDataList[j]["times"]
  580. dataList["tmrNo"] = queryDataList[j]["tmrNo"]
  581. dataList["tName"] = queryDataList[j]["tName"]
  582. dataList["dName"] = queryDataList[j]["dName"]
  583. expWeight, _ := strconv.ParseFloat( xorm.String(queryDataList[j]["expWeight"]), 64)
  584. actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]) , 64)
  585. dataList["expWeight"] = expWeight
  586. dataList["actualWeight"] = actualWeight
  587. dataList["endTime"] = queryDataList[j]["endTime"]
  588. dataList["penId"] = queryDataList[j]["penId"]
  589. dataList["penName"] = queryDataList[j]["penName"]
  590. dataList["cowCount"] = queryDataList[j]["cowCount"]
  591. dataList["sort"] = queryDataList[j]["sort"]
  592. dataList["ftId"] = queryDataList[j]["ftId"]
  593. dataList["ftName"] = queryDataList[j]["ftName"]
  594. feedList = append(feedList, dataList)
  595. }
  596. }
  597. listData["data"] = feedList
  598. jsonStr, _ := json.Marshal(listData)
  599. postData := make(map[string]string)
  600. postData["formData"] = string(jsonStr)
  601. err = util.PostWithFormData("POST", "http://120.48.30.31:88/kaps-cow/api/tmr/addOtherDeviceFeeding", &postData)
  602. if err != nil{
  603. fmt.Println("AddOtherDeviceFeeding err:",err)
  604. logging.Error("AddOtherDeviceFeeding err:",err)
  605. }else {
  606. _,err = tx.Exec(`update downloadedplan set isuse=1 where mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and isuse=0
  607. and pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight'
  608. AND table_schema = 'tmrwatch' AND column_name = 'pastureid') `)
  609. if err != nil{
  610. logging.Error("update downloadedplan err:",err)
  611. }
  612. }
  613. }
  614. }
  615. //data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:86/kaps-cow/api/tmr/getMaterial")
  616. }
  617. func PostTmrData(){
  618. defer func() { // 必须要先声明defer
  619. if err := recover(); err != nil {
  620. fmt.Printf("CronTest pnic err%+v \n", err)
  621. logging.Error("panic recover err ", err)
  622. //println("pnic err",err.(error).Error()) // 这里的err其实就是panic传入的内容,55
  623. }
  624. }()
  625. println("开始执行")
  626. AddOtherDevice()
  627. AddOtherDeviceFeeding()
  628. }
  629. func CronGRFD() {
  630. defer func() { // 必须要先声明defer
  631. if err := recover(); err != nil {
  632. fmt.Printf("CronTest pnic err%+v \n", err)
  633. logging.Error("panic recover err ", err)
  634. }
  635. }()
  636. log.Println("Starting CronWXwork...")
  637. c := cron.New()
  638. _, err := c.AddFunc("0/3 * * * *", PostTmrData) //* * * * *, 从分钟开始 每5分钟
  639. if err != nil {
  640. println("cron4 err", err.Error())
  641. }
  642. c.Start()
  643. }