bdd3a48cc62d72293ea04429176ed8b13cea5b33.svn-base 25 KB

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