grfdApi.go 31 KB

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