7b7f97526eed02f895e52c1da641a189bae3215b.svn-base 26 KB

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