grfdApi.go 27 KB

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