cabddfb9b3599d1a61ab3551fa909788a62cb996.svn-base 26 KB

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