grfdApi.go 26 KB

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