c418d4fcd53eae3dfa4e62eab20d96f6c345d76b.svn-base 24 KB

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