f021edeb4863b1e90373c1c845355664ccd7bc5d.svn-base 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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. err := tx.Begin()
  466. defer func() {
  467. switch {
  468. case err != nil:
  469. logging.Error("tx.Begin 事务启动失败__error:", err)
  470. if tx != nil {
  471. tx.Rollback()
  472. }
  473. default:
  474. if tx != nil {
  475. err = 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 from downloadedplan d 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 " +
  483. " and d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') ").Query().List()
  484. 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,
  485. de.Fname AS fName,fc.FCNAME AS feedclassName,de.SORT AS sort,de.feedallowratio AS allowableError,
  486. CAST(IFNULL(de.LWEIGHT,0) AS DECIMAL(10,2)) AS expWeight,CAST(IFNULL(de.ActualWeightMinus,0) AS DECIMAL(10,2)) AS actualWeight,
  487. DATE_FORMAT(de.intime,'%Y-%m-%d %H:%i:%s') AS endTime ,d.tmrtname AS tName ,'' dName
  488. FROM downloadedplan d JOIN downloadplandtl1 de ON d.id=de.PID AND d.pastureid=de.pastureid AND de.type = 0
  489. 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
  490. LEFT JOIN feedclass fc ON f.fclassid=fc.id AND fc.pastureid=d.pastureid
  491. 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
  492. AND d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid')
  493. `).Query().List()
  494. if err1 == nil && err2 == nil {
  495. for i := 0; i < len(queryIdList); i++ {
  496. id := queryIdList[i]["id"]
  497. projName := queryIdList[i]["projName"]
  498. listData := make(map[string]interface{})
  499. listData["farmId"] = 4090
  500. listData["id"] = id
  501. listData["projName"] = projName
  502. feedList := []interface{}{}
  503. for j := 0; j < len(queryDataList); j++ {
  504. id2 := queryDataList[j]["id"]
  505. if id == id2 {
  506. dataList := make(map[string]interface{})
  507. dataList["tmrNo"] = queryDataList[j]["tmrNo"]
  508. dataList["times"] = queryDataList[j]["times"]
  509. dataList["loadDate"] = queryDataList[j]["loadDate"]
  510. dataList["ftId"] = queryDataList[j]["ftId"]
  511. dataList["ftName"] = queryDataList[j]["ftName"]
  512. dataList["fId"] = queryDataList[j]["fId"]
  513. dataList["tName"] = queryDataList[j]["tName"]
  514. dataList["feedclassName"] = queryDataList[j]["feedclassName"]
  515. dataList["fName"] = queryDataList[j]["fName"]
  516. dataList["sort"] = queryDataList[j]["sort"]
  517. dataList["allowableError"] = queryDataList[j]["allowableError"]
  518. xorm.String(queryDataList[j]["expWeight"])
  519. expWeight, _ := strconv.ParseFloat( xorm.String(queryDataList[j]["expWeight"]) , 64)
  520. actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]), 64)
  521. lWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["lWeight"]), 64)
  522. dataList["expWeight"] = expWeight
  523. dataList["actualWeight"] = actualWeight
  524. dataList["lWeight"] = lWeight
  525. dataList["endTime"] = queryDataList[j]["endTime"]
  526. dataList["dName"] = queryDataList[j]["dName"]
  527. feedList = append(feedList, dataList)
  528. }
  529. }
  530. listData["data"] = feedList
  531. jsonStr, _ := json.Marshal(listData)
  532. postData := make(map[string]string)
  533. postData["formData"] = string(jsonStr)
  534. err = util.PostWithFormData("POST", setting.ServerSetting.GRFDURL+"/kaps-cow/api/tmr/addOtherDevice", &postData)
  535. if err != nil{
  536. logging.Error("AddOtherDevice err:",err)
  537. }
  538. }
  539. }
  540. }
  541. func AddOtherDeviceFeeding() {
  542. tx := restful.Engine.NewSession()
  543. err := tx.Begin()
  544. defer func() {
  545. switch {
  546. case err != nil:
  547. logging.Error("tx.Begin 事务启动失败__error:", err)
  548. if tx != nil {
  549. tx.Rollback()
  550. }
  551. default:
  552. if tx != nil {
  553. err = tx.Commit()
  554. }
  555. }
  556. if tx != nil {
  557. tx.Close()
  558. }
  559. }()
  560. queryIdList, err1 := tx.SQL("select d.pid +UNIX_TIMESTAMP(d.mydate) id,d.projname projName from downloadedplan d JOIN downloadplandtl2 d2 on d.id=d2.PID and d.pastureid=d2.pastureid and d2.type = 0 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 " +
  561. " and d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid') group by d.id").Query().List()
  562. 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,
  563. bar.backup1 AS penId,d2.fname AS penName,fp.CCOUNT AS cowCount, d2.SORT AS sort,d.templetName ftName, ft.backup1 ftId,
  564. 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
  565. FROM downloadedplan d JOIN downloadplandtl2 d2 ON d.id=d2.PID AND d.pastureid=d2.pastureid AND d2.type = 0
  566. 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
  567. LEFT JOIN feedtemplet ft ON d.tempid=ft.id AND ft.pastureid=d.pastureid
  568. 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
  569. AND d.pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight' AND table_schema = 'tmrwatch' AND column_name = 'pastureid')`).Query().List()
  570. if err1 == nil && err2 == nil {
  571. for i := 0; i < len(queryIdList); i++ {
  572. id := queryIdList[i]["id"]
  573. projName := queryIdList[i]["projName"]
  574. listData := make(map[string]interface{})
  575. listData["farmId"] = 4090
  576. listData["id"] = id
  577. listData["projName"] = projName
  578. feedList := []interface{}{}
  579. for j := 0; j < len(queryDataList); j++ {
  580. id2 := queryDataList[j]["id"]
  581. if id == id2 {
  582. dataList := make(map[string]interface{})
  583. dataList["dropDate"] = queryDataList[j]["dropDate"]
  584. dataList["times"] = queryDataList[j]["times"]
  585. dataList["tmrNo"] = queryDataList[j]["tmrNo"]
  586. dataList["tName"] = queryDataList[j]["tName"]
  587. dataList["dName"] = queryDataList[j]["dName"]
  588. expWeight, _ := strconv.ParseFloat( xorm.String(queryDataList[j]["expWeight"]), 64)
  589. actualWeight, _ := strconv.ParseFloat(xorm.String(queryDataList[j]["actualWeight"]) , 64)
  590. dataList["expWeight"] = expWeight
  591. dataList["actualWeight"] = actualWeight
  592. dataList["endTime"] = queryDataList[j]["endTime"]
  593. dataList["penId"] = queryDataList[j]["penId"]
  594. dataList["penName"] = queryDataList[j]["penName"]
  595. dataList["cowCount"] = queryDataList[j]["cowCount"]
  596. dataList["sort"] = queryDataList[j]["sort"]
  597. dataList["ftId"] = queryDataList[j]["ftId"]
  598. dataList["ftName"] = queryDataList[j]["ftName"]
  599. feedList = append(feedList, dataList)
  600. }
  601. }
  602. listData["data"] = feedList
  603. jsonStr, _ := json.Marshal(listData)
  604. postData := make(map[string]string)
  605. postData["formData"] = string(jsonStr)
  606. err = util.PostWithFormData("POST", setting.ServerSetting.GRFDURL+"/kaps-cow/api/tmr/addOtherDeviceFeeding", &postData)
  607. if err != nil{
  608. logging.Error("AddOtherDeviceFeeding err:",err)
  609. }else {
  610. _,err = tx.Exec(`update downloadedplan set isuse=1 where mydate=date_format(NOW(),'%Y-%m-%d') and iscompleted=1 and isuse=0
  611. and pastureid =(SELECT column_default FROM information_schema.COLUMNS WHERE table_name = 'recweight'
  612. AND table_schema = 'tmrwatch' AND column_name = 'pastureid') `)
  613. if err != nil{
  614. logging.Error("update downloadedplan err:",err)
  615. }
  616. }
  617. }
  618. }
  619. //data := util.Send_Message1("{\"farmId\":4090}", "http://120.48.30.31:86/kaps-cow/api/tmr/getMaterial")
  620. }
  621. func PostTmrData(){
  622. defer func() { // 必须要先声明defer
  623. if err := recover(); err != nil {
  624. logging.Error("panic recover err ", err)
  625. }
  626. }()
  627. println("开始执行")
  628. AddOtherDevice()
  629. AddOtherDeviceFeeding()
  630. }
  631. func CronGRFD() {
  632. defer func() { // 必须要先声明defer
  633. if err := recover(); err != nil {
  634. fmt.Printf("CronTest pnic err%+v \n", err)
  635. logging.Error("panic recover err ", err)
  636. }
  637. }()
  638. log.Println("Starting CronWXwork...")
  639. c := cron.New()
  640. _, err := c.AddFunc("0/55 * * * *", PostTmrData) //* * * * *, 从分钟开始 每5分钟
  641. if err != nil {
  642. println("cron4 err", err.Error())
  643. }
  644. c.Start()
  645. }