785d7b004de3af8bfa676a2142a87c16d22b56b7.svn-base 25 KB

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