yq.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. package yq
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "tmr-watch/conf/setting"
  13. "tmr-watch/http/handle/restful"
  14. "tmr-watch/pkg/app"
  15. "tmr-watch/pkg/e"
  16. "tmr-watch/pkg/logging"
  17. "github.com/Anderson-Lu/gofasion/gofasion"
  18. "github.com/astaxie/beego/logs"
  19. "github.com/robfig/cron"
  20. "github.com/xormplus/xorm"
  21. )
  22. type udPastureInfo struct {
  23. Token string `xorm:"token"`
  24. Pastureid string `xorm:"pastureid"`
  25. Werks string `xorm:"werks"`
  26. }
  27. func YqCron() {
  28. tx := restful.Engine.NewSession()
  29. defer tx.Close()
  30. pastureinfo := new(udPastureInfo)
  31. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  32. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  33. if err != nil {
  34. logs.Error(err)
  35. return
  36. }
  37. token := getToken()
  38. syncBar(token, pastureinfo.Pastureid)
  39. c := cron.New()
  40. c.AddFunc("0 0 1 * * *", func() {
  41. token := getToken()
  42. now := time.Now().Format("2006-01-02")
  43. YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  44. YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
  45. YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  46. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  47. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  48. YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  49. syncBar(token, pastureinfo.Pastureid)
  50. })
  51. c.AddFunc("0 0 6 * * *", func() {
  52. token := getToken()
  53. now := time.Now().Format("2006-01-02")
  54. YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  55. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  56. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  57. })
  58. c.AddFunc("0 0 7 * * *", func() {
  59. token := getToken()
  60. now := time.Now().Format("2006-01-02")
  61. YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  62. YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  63. })
  64. c.AddFunc("0 0 12 * * *", func() {
  65. token := getToken()
  66. now := time.Now().Format("2006-01-02")
  67. YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  68. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  69. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  70. })
  71. c.AddFunc("0 0 18 * * *", func() {
  72. token := getToken()
  73. now := time.Now().Format("2006-01-02")
  74. YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  75. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  76. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  77. })
  78. c.AddFunc("0 0 23 * * *", func() {
  79. token := getToken()
  80. now := time.Now().Format("2006-01-02")
  81. YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  82. YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
  83. YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  84. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  85. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  86. YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  87. })
  88. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:05:00", time.Local)
  89. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  90. spec := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  91. c.AddFunc(spec, func() {
  92. token := getToken()
  93. now := time.Now().Format("2006-01-02")
  94. YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  95. YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
  96. })
  97. c.Start()
  98. // YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  99. // fmt.Println(getToken())
  100. // YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
  101. // YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  102. // YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  103. // YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  104. // YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  105. // YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
  106. }
  107. func createApiSign(appId, timeStamp, apiKey, secretKey string) string {
  108. return getMD5Encode(fmt.Sprintf("%s#%s#%s#%s", appId, timeStamp, apiKey, secretKey))
  109. }
  110. func getMD5Encode(data string) string {
  111. fmt.Println(data)
  112. hasher := md5.New()
  113. hasher.Write([]byte(data))
  114. digest := hasher.Sum(nil)
  115. md5HashString := hex.EncodeToString(digest)
  116. return md5HashString
  117. }
  118. func getToken() string {
  119. appId := "6Zub5bed5Yqo55uS"
  120. apiKey := "3c6bbff8cf1e496eb8eb9025cd8537fh"
  121. secretKey := "26b5d9f63b6142de8f102afb1aa2eb7g"
  122. req, err := http.NewRequest("POST", "https://vmuyun.com/base-server/outSide/token", nil)
  123. if err != nil {
  124. logs.Error(err)
  125. }
  126. now := time.Now()
  127. nanos := now.UnixNano()
  128. timeStamp := fmt.Sprintf("%d", nanos/int64(time.Millisecond))
  129. apiSign := createApiSign(appId, timeStamp, apiKey, secretKey)
  130. req.Header.Set("appId", appId)
  131. req.Header.Set("apiKey", apiKey)
  132. req.Header.Set("secretKey", secretKey)
  133. req.Header.Set("timeStamp", timeStamp)
  134. req.Header.Set("apiSign", apiSign)
  135. client := &http.Client{}
  136. resp, err := client.Do(req)
  137. if err != nil {
  138. logs.Error(err)
  139. return ""
  140. }
  141. defer resp.Body.Close()
  142. body, _ := ioutil.ReadAll(resp.Body)
  143. data := make(map[string]string, 0)
  144. json.Unmarshal(body, &data)
  145. fmt.Println(string(body))
  146. if _, ok := data["data"]; ok {
  147. return data["data"]
  148. }
  149. return ""
  150. }
  151. func postPush(data string, msgtype int, tx *xorm.Session, pastureId, token string) {
  152. // jsonStr, _ := json.Marshal(data)
  153. url := "https://vmuyun.com/project-server/openApi/feeding/pushData"
  154. req, err := http.NewRequest("POST", url, strings.NewReader((data)))
  155. if err != nil {
  156. logs.Error(err)
  157. // return nil
  158. }
  159. // req.Header.Set("Content-Type", "application/json")
  160. // req.Header.Set("Content-Length", "13444")
  161. req.Header.Add("Authorization", token)
  162. // req.Header.Set("Host", "test.vmuyun.com")
  163. // req.Header.Set("Accept", "*/*")
  164. // req.Header.Set("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
  165. // req.Header.Add("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
  166. req.Header.Add("Content-Type", "application/json")
  167. // req.Header.Add("Accept", "*/*")
  168. // req.Header.Add("Host", "test.vmuyun.com")
  169. // req.Header.Add("Connection", "keep-alive")
  170. client := &http.Client{}
  171. resp, err := client.Do(req)
  172. if err != nil {
  173. logs.Error(err)
  174. return
  175. }
  176. defer resp.Body.Close()
  177. body, _ := ioutil.ReadAll(resp.Body)
  178. fmt.Println(string(body))
  179. if strings.Index(resp.Status, "200") > -1 {
  180. bodyData := make(map[string]string)
  181. json.Unmarshal(body, &bodyData)
  182. if _, ok := bodyData["data"]; ok {
  183. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  184. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, bodyData["data"], "", "", msgtype, url)
  185. } else {
  186. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  187. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  188. }
  189. } else {
  190. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  191. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  192. }
  193. }
  194. func YcFeedtempletPush(pastureId, farmId, date, token string) error {
  195. tx := restful.Engine.NewSession()
  196. defer tx.Close()
  197. var now string
  198. if date != "" {
  199. now = date
  200. } else {
  201. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  202. }
  203. dataList, err := tx.SQL(`SELECT
  204. ft.tcode AS recipeId,
  205. ft.TNAME AS recipeName,
  206. f.feedcode AS ingId,
  207. ifnull(f.udname,f.fname) AS ingName,
  208. round( f.dry * ftd.FWEIGHT, 2 ) AS dmQty,
  209. ftd.FWEIGHT AS afQty,
  210. ftd.SORT AS mixNo,
  211. round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost,
  212. fc.fcname AS ingType,
  213. f.AllowRatio AS allowableError ,fc.fcname ingType
  214. FROM
  215. feedtempletdate ft
  216. JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date
  217. JOIN feed f ON ftd.FID = f.id
  218. JOIN feedclass fc ON f.fclassid = fc.id
  219. WHERE
  220. ft.ENABLE = 1
  221. AND ft.isDelete != 1 and ft.date = ? `, now).Query().List()
  222. if err != nil {
  223. logging.Error(err)
  224. return err
  225. }
  226. dataByte, _ := json.Marshal(&dataList)
  227. reqJson := `{
  228. "reqMethod": "PARTY",
  229. "param": {
  230. "code": "1",
  231. "method": "getfeedtempletinfo",
  232. "resultData": %s,
  233. "farmId": "%s",
  234. "rowCount": %d,
  235. "errMessage": ""
  236. },
  237. "regCode": "cpt180511",
  238. "command": "3d6e4752",
  239. "apiId": "getCptData"
  240. }`
  241. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
  242. fmt.Println(reqJson)
  243. postPush(reqJson, 4, tx, pastureId, token)
  244. return nil
  245. }
  246. func YcFeedPush(pastureId, farmId, token string) error {
  247. tx := restful.Engine.NewSession()
  248. defer tx.Close()
  249. dataList, err := tx.SQL(`SELECT
  250. dry dmQty,
  251. sort,
  252. feedcode ingId,
  253. fname ingName,
  254. fclass ingType,
  255. allowratio allowableError
  256. FROM
  257. feed
  258. WHERE
  259. pastureId = ? `, pastureId).Query().List()
  260. if err != nil {
  261. logging.Error(err)
  262. return err
  263. }
  264. dataByte, _ := json.Marshal(&dataList)
  265. reqJson := `{
  266. "apiId": "getKPTData ",
  267. "param": {
  268. "farmId": "%s",
  269. "method":"getfeedinfo",
  270. "rowCount": %d,
  271. "resultData":%s
  272. }
  273. }`
  274. reqJson = fmt.Sprintf(reqJson, farmId, len(dataList), string(dataByte))
  275. fmt.Println(reqJson)
  276. postPush(reqJson, 2, tx, pastureId, token)
  277. return nil
  278. }
  279. func YcPlanPush(pastureId, farmId, date, token string) error {
  280. tx := restful.Engine.NewSession()
  281. defer tx.Close()
  282. dataList, err := tx.SQL(`SELECT
  283. projname planName,
  284. datacaptureno tmrNo,
  285. times loadShift,
  286. tempid recipeId,
  287. templetname recipeName,
  288. lweight expWeight,
  289. tmrtname tmrName,
  290. '是' STATUS,
  291. feedpcount cowCount,
  292. id planId,
  293. DATE_FORMAT( mydate, '%H:%i:%s' ) planTime,
  294. DATE_FORMAT( mydate, '%Y-%m-%d' ) planDate,
  295. IF( iscompleted = 1, '是', '否' ) isCompleted,
  296. IF(dlp.driverId != 0,(
  297. SELECT
  298. drivername
  299. FROM
  300. driver
  301. WHERE
  302. id = dlp.driverId
  303. ),(
  304. SELECT
  305. dr.driver
  306. FROM
  307. dutyrecord dr
  308. WHERE
  309. dr.pastureid = dlp.pastureid
  310. AND dr.eqid = dlp.tmrid
  311. AND dr.times = dlp.times
  312. AND dr.operatetime <= dlp.mydate
  313. ORDER BY
  314. dr.operatetime DESC
  315. LIMIT 1
  316. )) driverName
  317. FROM
  318. downloadedplan dlp
  319. WHERE
  320. havebutton = 1
  321. AND mydate = ? `, date).Query().List()
  322. if err != nil {
  323. logging.Error(err)
  324. return err
  325. }
  326. dataByte, _ := json.Marshal(&dataList)
  327. reqJson := `{
  328. "apiId": "getKPTData ",
  329. "param": {
  330. "farmId": "%s",
  331. "method":"getplaninfo",
  332. "rowCount": %d,
  333. "resultData":%s
  334. }
  335. }`
  336. reqJson = fmt.Sprintf(reqJson, farmId, len(dataList), string(dataByte))
  337. fmt.Println(reqJson)
  338. postPush(reqJson, 2, tx, pastureId, token)
  339. return nil
  340. }
  341. //搅拌
  342. func YcUtirPush(pastureId, farmId, date, token string) error {
  343. tx := restful.Engine.NewSession()
  344. defer tx.Close()
  345. var now string
  346. if date != "" {
  347. now = date
  348. } else {
  349. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  350. }
  351. dataList, err := tx.SQL(`select date_format(d1.date,'%Y-%m-%d') dropDate,d.times loadShift,d.datacaptureno tmrNo,ft.tcode recipeId,ft.ccname recipeName,if(d1.feedcode = -1 ,d1.fid,f.feedcode) ingId,ifnull(f.fname,ftd.fname) ingName,
  352. ifnull(ifnull(fc.fcname,(select fcname from feedclass fc1 join feed f1 on f1.fclassid = fc1.id where f1.id =ftd.fid )),'饲料') ingType,
  353. ifnull(f.dry * d1.actualweightminus,0) dmPct,d1.sort mixNo,ifnull(d1.feedallowratio,0) allowableError , if(f.fname is not null, ifnull(d1.lweight,''), ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.lweight,"") ) expWeight,
  354. if(f.fname is not null, ifnull(d1.actualweightminus,''), ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.actualweightminus,"") ) actualWeight,
  355. DATE_FORMAT(IFNULL((SELECT MAX(intime) FROM downloadplandtl1 d2
  356. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime)
  357. , (SELECT MAX(intime) FROM downloadedplan d2
  358. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid)
  359. ), '%Y-%m-%d %H:%i:%s')
  360. startTime ,
  361. date_format(d1.intime,'%Y-%m-%d %H:%i:%s') endTime, driver.drivername tmrName ,d1.feedallowratio allowable_error
  362. from downloadplandtl1 d1 join downloadedplan d on d.id = d1.pid
  363. left join feedtempletdate ft on ft.id = d.tempid and ft.date = d1.date
  364. left join feed f on f.feedcode = d1.feedcode
  365. left join feedclass fc on fc.id = f.fclassid
  366. left join ftdetaildate ftd on ftd.date = d1.date and ftd.ftid = d1.fid
  367. join tmr t on t.id = d.tmrid
  368. left join driver on driver.drivercode = t.eqcode
  369. where d1.date = ? and d.havebutton = 1 and d1.type = 0 `, now).Query().List()
  370. if err != nil {
  371. logging.Error(err)
  372. return err
  373. }
  374. dataByte, _ := json.Marshal(&dataList)
  375. reqJson := `{
  376. "reqMethod": "PARTY",
  377. "param": {
  378. "code": "1",
  379. "method": "uploadadddata",
  380. "resultData": %s,
  381. "farmId": "%s",
  382. "rowCount": %d,
  383. "errMessage": ""
  384. },
  385. "regCode": "cpt180511",
  386. "command": "3d6e4752",
  387. "apiId": "getCptData"
  388. }`
  389. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
  390. postPush(reqJson, 0, tx, pastureId, token)
  391. fmt.Println(reqJson)
  392. return nil
  393. }
  394. func YcBarFeedRemainPush(pastureId, farmId, date, token string) error {
  395. tx := restful.Engine.NewSession()
  396. defer tx.Close()
  397. var now string
  398. if date != "" {
  399. now = date
  400. } else {
  401. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  402. }
  403. dataList, err := tx.SQL(`SELECT
  404. date_format( remaindate, '%Y-%m-%d' ) overplusDate,
  405. ifnull(b.bcode,b.id) AS penId,
  406. b.BNAME AS penName,
  407. br.Remain AS actualWeight
  408. FROM
  409. barfeedremain br
  410. LEFT JOIN feedp fp ON br.barid = fp.id
  411. left join bar b on b.id = fp.barid
  412. WHERE
  413. date_format( remaindate, '%Y-%m-%d' ) =? `, now).Query().List()
  414. if err != nil {
  415. logging.Error(err)
  416. return err
  417. }
  418. dataByte, _ := json.Marshal(&dataList)
  419. reqJson := `{
  420. "reqMethod": "PARTY",
  421. "param": {
  422. "code": "1",
  423. "method": "uploadoverplusdata",
  424. "resultData": %s,
  425. "farmId":"%s",
  426. "rowCount": %d,
  427. "errMessage": ""
  428. },
  429. "regCode": "cpt180511",
  430. "command": "3d6e4752",
  431. "apiId": "getCptData"
  432. }`
  433. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
  434. // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存',
  435. fmt.Println(reqJson)
  436. postPush(reqJson, 1, tx, pastureId, token)
  437. return nil
  438. }
  439. func YcMaterialIssuePush(pastureId, farmId, date, token string) error {
  440. tx := restful.Engine.NewSession()
  441. defer tx.Close()
  442. var now string
  443. if date != "" {
  444. now = date
  445. } else {
  446. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  447. }
  448. dataList, err := tx.SQL(`SELECT
  449. DATE_FORMAT(d.mydate,'%Y-%m-%d') dropDate,
  450. d.datacaptureno tmrNo,
  451. d.times dropShift,
  452. b.bcode penId,
  453. b.bname penName,
  454. fp.ccount cowCount,
  455. d2.sort feedingNo,
  456. d2.lweight expWeight,
  457. d2.actualweight actualWeight,
  458. if((select count(1) from downloadplandtl2 where pid = d.id and sort < d2.sort ) = 0 ,(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id order by sort desc limit 1 ),(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl2 where pid = d.id and sort < d2.sort order by sort desc limit 1)) startTime,
  459. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endTime,
  460. d.tmrtname tmrName, driver.drivername driverName,d.id planId,1 calculation,
  461. ifnull((select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 1 ) ,0) shift1,
  462. ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 2 ) ,0) shift2,
  463. ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 3 ) ,0) shift3,
  464. ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 4 ) ,0) shift4,
  465. ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 5 ) ,0) shift5,
  466. ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 6 ),0) shift6,
  467. d.tempid recipeId,d.templetname recipeName, d.completedtime isCompleted
  468. FROM
  469. downloadedplan d
  470. JOIN downloadplandtl2 d2 ON d.id = d2.pid
  471. JOIN bar b ON d2.fbarid = b.id
  472. join feedp fp on fp.barid = b.id
  473. join tmr t on t.id = d.tmrid
  474. left join driver on driver.drivercode = t.eqcode where d.mydate = ? and d.havebutton = 1
  475. `, now).Query().List()
  476. if err != nil {
  477. logging.Error(err)
  478. return err
  479. }
  480. dataByte, _ := json.Marshal(&dataList)
  481. reqJson := `{
  482. "reqMethod": "PARTY",
  483. "param": {
  484. "code": "1",
  485. "method": "uploaddiliverdata",
  486. "resultData": %s,
  487. "farmId": "%s",
  488. "rowCount": %d,
  489. "errMessage": ""
  490. },
  491. "regCode": "cpt180511",
  492. "command": "3d6e4752",
  493. "apiId": "getCptData"
  494. }`
  495. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
  496. // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存',
  497. postPush(reqJson, 0, tx, pastureId, token)
  498. fmt.Println(reqJson)
  499. return nil
  500. }
  501. func syncBar(token, pastureid string) {
  502. req, err := http.NewRequest("GET", "https://vmuyun.com/project-server/openApi/feeding/penList", nil)
  503. if err != nil {
  504. logs.Error(err)
  505. // return nil
  506. }
  507. req.Header.Set("Authorization", token)
  508. req.Header.Set("Content-Type", "application/json")
  509. client := &http.Client{}
  510. resp, err := client.Do(req)
  511. if err != nil {
  512. logs.Error(err)
  513. return
  514. }
  515. defer resp.Body.Close()
  516. body, _ := ioutil.ReadAll(resp.Body)
  517. data := make(map[string]interface{}, 0)
  518. json.Unmarshal(body, &data)
  519. dataList := data["data"].([]interface{})
  520. tx := restful.Engine.NewSession()
  521. defer tx.Close()
  522. for _, item := range dataList {
  523. arg := item.(map[string]interface{})
  524. fmt.Println(arg)
  525. _, err := tx.Exec(` insert into bar(pen,bname,bcode,pastureid)values(?,?,?,?) ON DUPLICATE KEY UPDATE pen = ? `, arg["districtName"],
  526. fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"]), fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"]), pastureid, arg["houseName"])
  527. fmt.Println(err)
  528. insertSql := `insert into feedp(pastureid,barname,barid,ccount)VALUES(?,?,(select id from bar where bname = ?),?)
  529. ON DUPLICATE KEY UPDATE ccount = ? ,barname = ? `
  530. tx.SQL(insertSql, pastureid, fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"]),
  531. fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"]), arg["sheepCount"], arg["sheepCount"],
  532. fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"])).Execute()
  533. tx.SQL(` select from feedp where barname = ? `)
  534. // barList := make([]*bar,0)
  535. b := new(bar)
  536. // b.BarName = fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"])
  537. // b.Ccount = arg["sheepCount"]
  538. err = tx.SQL(`select fp.barname,fp.ccount,ratio,ft.tname ftname,(select tratio from fpdetail where barid = fp.barid and times = 1 ) times1,
  539. (select tratio from fpdetail where barid = fp.barid and times = 2 ) times2 ,
  540. (select tratio from fpdetail where barid = fp.barid and times = 3 ) times3 ,
  541. (select tratio from fpdetail where barid = fp.barid and times = 4 ) times4 ,
  542. (select tratio from fpdetail where barid = fp.barid and times =5 ) times5 ,
  543. (select tratio from fpdetail where barid = fp.barid and times =6 ) times6
  544. from feedp fp join feedtemplet ft on ft.id = fp.ftid where ratio > 0 and fp.barname = ? `, fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"])).GetFirst(&b).Error
  545. // {"pastureId":"1653271339","barList":[{"barname":"14","ccount":155,"ratio":"100.00","ftname":"高产2配方",
  546. // "times1":"41","times2":"25","times3":"25","times4":0,"times5":0,"times6":0}]}
  547. }
  548. }
  549. type bar struct {
  550. BarName string `xorm:"barname" json:"barname"`
  551. Ccount string `xorm:"ccount" json:"ccount"`
  552. Ratio string `xorm:"ratio" json:"ratio"`
  553. Ftname string `xorm:"ftname" json:"ftname"`
  554. Times1 int64 `xorm:"times1" json:"times1"`
  555. Times2 int64 `xorm:"times2" json:"times2"`
  556. Times3 int64 `xorm:"times3" json:"times3"`
  557. Times4 int64 `xorm:"times4" json:"times4"`
  558. Times5 int64 `xorm:"times5" json:"times5"`
  559. Times6 int64 `xorm:"times6" json:"times6"`
  560. }
  561. func fpdBatchEdit(pastureid string ,b *bar) {
  562. // appG := app.Gin{C: c}
  563. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  564. // fsions := gofasion.NewFasion(string(dataByte))
  565. // barList := fsions.Get("barList").Array()
  566. // pastureid := fsions.Get("pastureId").ValueStr()
  567. tx := restful.Engine.NewSession()
  568. defer tx.Close()
  569. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  570. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  571. if err != nil {
  572. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  573. return
  574. }
  575. // for _, barFsions := range barList {
  576. dataexcel := make(map[string]interface{}, 0)
  577. dataexcel["barname"] =b.BarName
  578. dataexcel["ccount"] = b.Ccount
  579. dataexcel["ratio"] = b.Ratio
  580. dataexcel["ftname"] = b.Ftname
  581. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  582. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  583. return
  584. }
  585. dataexcel["1"] = b.Times1
  586. dataexcel["2"] = b.Times2
  587. dataexcel["3"] = b.Times3
  588. dataexcel["4"] = b.Times4
  589. dataexcel["5"] = b.Times5
  590. dataexcel["6"] = b.Times6
  591. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  592. if err != nil {
  593. logs.Error(err)
  594. return
  595. }
  596. if !ftexist {
  597. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  598. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  599. if err != nil {
  600. logs.Error(err)
  601. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  602. return
  603. }
  604. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  605. if err != nil {
  606. logs.Error(err)
  607. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  608. return
  609. }
  610. }
  611. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  612. if err != nil {
  613. logs.Error(err)
  614. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  615. return
  616. }
  617. if !exist {
  618. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  619. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  620. if err != nil {
  621. logs.Error(err)
  622. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  623. return
  624. }
  625. }
  626. var feedpargs []interface{}
  627. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  628. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  629. if _, ok := dataexcel["ftname"]; ok {
  630. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  631. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  632. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  633. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  634. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  635. } else {
  636. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  637. }
  638. if _, ok := dataexcel["ptsfname"]; ok {
  639. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  640. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  641. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  642. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  643. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  644. } else {
  645. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  646. }
  647. upFeedpSql += " where barname = ? and pastureid = ? "
  648. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  649. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  650. if err != nil {
  651. logs.Error(err)
  652. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  653. return
  654. }
  655. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  656. if err != nil {
  657. logs.Error(err)
  658. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  659. return
  660. }
  661. if !exist1 {
  662. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  663. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  664. if err != nil {
  665. logs.Error(err)
  666. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  667. return
  668. }
  669. }
  670. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  671. if err != nil {
  672. logs.Error(err)
  673. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  674. return
  675. }
  676. if !exist2 {
  677. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  678. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  679. if err != nil {
  680. logs.Error(err)
  681. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  682. return
  683. }
  684. }
  685. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  686. if err != nil {
  687. logs.Error(err)
  688. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  689. return
  690. }
  691. if !exist3 {
  692. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  693. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  694. if err != nil {
  695. logs.Error(err)
  696. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  697. return
  698. }
  699. }
  700. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  701. if err != nil {
  702. logs.Error(err)
  703. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  704. return
  705. }
  706. if !exist4 {
  707. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  708. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  709. if err != nil {
  710. logs.Error(err)
  711. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  712. return
  713. }
  714. }
  715. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  716. if err != nil {
  717. logs.Error(err)
  718. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  719. return
  720. }
  721. if !exist5 {
  722. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  723. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  724. if err != nil {
  725. logs.Error(err)
  726. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  727. return
  728. }
  729. }
  730. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  731. if err != nil {
  732. logs.Error(err)
  733. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  734. return
  735. }
  736. if !exist6 {
  737. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  738. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  739. if err != nil {
  740. logs.Error(err)
  741. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  742. return
  743. }
  744. }
  745. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  746. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  747. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  748. and pastureid = ? and times = ?`
  749. var fpdargs1 []interface{}
  750. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  751. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  752. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  753. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  754. if err != nil {
  755. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  756. return
  757. }
  758. var fpdargs2 []interface{}
  759. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  760. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  761. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  762. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  763. if err != nil {
  764. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  765. return
  766. }
  767. var fpdargs3 []interface{}
  768. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  769. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  770. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  771. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  772. if err != nil {
  773. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  774. return
  775. }
  776. var fpdargs4 []interface{}
  777. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  778. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  779. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  780. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  781. if err != nil {
  782. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  783. return
  784. }
  785. var fpdargs5 []interface{}
  786. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  787. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  788. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  789. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  790. if err != nil {
  791. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  792. return
  793. }
  794. var fpdargs6 []interface{}
  795. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  796. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  797. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  798. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  799. if err != nil {
  800. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  801. return
  802. }
  803. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  804. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  805. if err != nil {
  806. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  807. return
  808. }
  809. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  810. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  811. upFpdetailList := make([]*upFpdetail, 0)
  812. for _, newfpd := range newList {
  813. for _, oldfpd := range oldFpdList {
  814. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  815. var oldweight, newweight float64
  816. if oldfpd["weight"] != nil {
  817. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  818. }
  819. if newfpd["weight"] != nil {
  820. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  821. }
  822. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  823. upFpdetailList = append(upFpdetailList, &upFpdetail{
  824. Old: oldweight,
  825. New: newweight,
  826. Times: newfpd["times"].(int64),
  827. Ptid: newfpd["ptid"].(int64),
  828. Fweight: fweight,
  829. Id: oldfpd["id"].(int64),
  830. })
  831. break
  832. }
  833. }
  834. }
  835. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  836. // }
  837. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  838. }
  839. type lpplandtlInfo struct {
  840. Id int64 `xorm:"id"`
  841. Pastureid int64 `xorm:"pastureid"`
  842. Lppid int64 `xorm:"lppid"`
  843. Barid int64 `xorm:"barid"`
  844. Barname string `xorm:"barname"`
  845. Fpdid int64 `xorm:"fpdid"`
  846. Fttype int64 `xorm:"fttype"`
  847. Lweight float64 `xorm:"lweight"`
  848. Sort int64 `xorm:"sort"`
  849. Tmrid int64 `xorm:"tmrid"`
  850. Tmrname string `xorm:"tmrname"`
  851. Cowcount int64 `xorm:"cowcount"`
  852. Ccountradio float64 `xorm:"ccountradio"`
  853. Background string `xorm:"background"`
  854. Lweighthis float64 `xorm:"lweighthis"`
  855. Maxweight float64 `xorm:"maxweight"`
  856. }
  857. type upFpdetail struct {
  858. Old float64
  859. New float64
  860. Times int64
  861. Ptid int64
  862. Fweight float64
  863. Id int64
  864. }
  865. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  866. tx := restful.Engine.NewSession()
  867. defer tx.Close()
  868. tx.Begin()
  869. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ifnull(ptsrate,0))*weight,2),"") weight,ptuse,times from fpdetail where pastureid = ? and barname = ? order by times `,
  870. pastureid, barname).Query().List()
  871. if err != nil {
  872. logs.Error(err)
  873. }
  874. for _, fpd := range fpdList {
  875. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  876. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  877. pastureid, fpd["id"], fpd["times"]).Query().List()
  878. if err != nil {
  879. tx.Rollback()
  880. logs.Error(err)
  881. return err
  882. }
  883. var lweight float64
  884. for _, lppland := range lpplandList {
  885. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  886. lweight += lweight1
  887. }
  888. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  889. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  890. if fpdweight >= ptuse && lweight == ptuse {
  891. continue
  892. } else {
  893. if lweight <= fpdweight {
  894. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  895. if err != nil {
  896. tx.Rollback()
  897. logs.Error(err)
  898. return err
  899. }
  900. } else {
  901. weight := lweight - fpdweight
  902. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  903. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  904. if err != nil {
  905. tx.Rollback()
  906. logs.Error(err)
  907. return err
  908. }
  909. for _, lppland := range lpplandList {
  910. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  911. if weight >= lpplandlweight {
  912. weight = weight - lpplandlweight
  913. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  914. if err != nil {
  915. tx.Rollback()
  916. logs.Error(err)
  917. return err
  918. }
  919. } else {
  920. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  921. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  922. if err != nil {
  923. tx.Rollback()
  924. logs.Error(err)
  925. return err
  926. }
  927. weight = 0
  928. break
  929. }
  930. }
  931. }
  932. }
  933. }
  934. for _, list := range dataList {
  935. ftmap := make(map[string]interface{})
  936. ftmap["old"] = list.Old
  937. ftmap["new"] = list.New
  938. ftmap["times"] = list.Times
  939. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  940. ftmap["ptsid"] = ""
  941. // fmt.Println(ftmap)
  942. // select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  943. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  944. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  945. // UNION
  946. fpdDataList, err := tx.SQL(`
  947. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  948. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  949. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  950. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  951. if err != nil {
  952. tx.Rollback()
  953. logs.Error(err)
  954. }
  955. for _, fpd := range fpdDataList {
  956. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  957. // fttype := -1
  958. // if fpd["fttype"].(string) == "1" {
  959. fttype := 1
  960. // }
  961. var fweight float64
  962. var lweight float64
  963. lpplandtl1List := make([]*lpplandtlInfo, 0)
  964. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  965. join lpplandtl1 lppland on lpp.id = lppland.lppid
  966. join tmr t on t.id = lpp.tmrid
  967. where lppland.fpdid =?
  968. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  969. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  970. if err != nil {
  971. tx.Rollback()
  972. logs.Error(err)
  973. }
  974. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  975. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  976. // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
  977. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  978. var w float64
  979. var status int
  980. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  981. if weight >= 0 {
  982. continue
  983. }
  984. w = weight
  985. status = 0
  986. } else {
  987. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  988. // continue
  989. // }
  990. w = weight
  991. status = 1
  992. }
  993. // for _, lppland := range lpplandtl1List {
  994. // lweight += lppland.Lweight
  995. // }
  996. for _, lppland := range lpplandtl1List {
  997. lpplandInfo := new(lpplandtlInfo)
  998. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  999. lweight = lpplandInfo.Lweight
  1000. if status == 1 {
  1001. // if w <= lppland.Lweight {
  1002. if lppland.Maxweight <= lweight {
  1003. continue
  1004. }
  1005. if w+lweight <= lppland.Maxweight {
  1006. lppland.Lweight += w
  1007. lweight += w
  1008. fweight += w
  1009. w = 0
  1010. } else {
  1011. w = w - (lppland.Maxweight - lweight)
  1012. n := (lppland.Maxweight - lweight)
  1013. lppland.Lweight = lppland.Lweight + n
  1014. lweight += n
  1015. fweight += n
  1016. }
  1017. } else {
  1018. if lppland.Lweight == 0 {
  1019. continue
  1020. }
  1021. if w+lppland.Lweight >= 0 {
  1022. lppland.Lweight = lppland.Lweight + w
  1023. lweight = lweight + w
  1024. fweight = fweight + w
  1025. w = 0
  1026. } else {
  1027. w = w + lppland.Lweight
  1028. lweight = lweight - lppland.Lweight
  1029. fweight = fweight - lppland.Lweight
  1030. lppland.Lweight = 0
  1031. }
  1032. }
  1033. if lppland.Lweight > 0 {
  1034. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  1035. if err != nil {
  1036. tx.Rollback()
  1037. logs.Error(err)
  1038. return err
  1039. }
  1040. } else {
  1041. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  1042. if err != nil {
  1043. tx.Rollback()
  1044. logs.Error(err)
  1045. return err
  1046. }
  1047. }
  1048. if w == 0 {
  1049. break
  1050. }
  1051. }
  1052. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  1053. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  1054. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  1055. if err != nil {
  1056. tx.Rollback()
  1057. logs.Error(err)
  1058. }
  1059. if w == 0 {
  1060. break
  1061. }
  1062. }
  1063. }
  1064. }
  1065. err = tx.Commit()
  1066. if err != nil {
  1067. logs.Error(err)
  1068. tx.Rollback()
  1069. return err
  1070. }
  1071. now := time.Now()
  1072. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1073. if err != nil {
  1074. logs.Error(err)
  1075. return nil
  1076. }
  1077. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1078. if err != nil {
  1079. logs.Error(err)
  1080. return nil
  1081. }
  1082. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1083. if err != nil {
  1084. logs.Error(err)
  1085. return nil
  1086. }
  1087. for _, newLpplandtl1 := range newLpplandtl1List {
  1088. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  1089. background,cowcount,ccountradio,lweighthis,createdate)
  1090. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  1091. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  1092. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  1093. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  1094. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  1095. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  1096. if err != nil {
  1097. logs.Error(err)
  1098. // appG.Response(http.StatusOK, e.ERROR, false)
  1099. return err
  1100. }
  1101. }
  1102. for _, newFpd := range newFpdDataList {
  1103. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  1104. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  1105. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  1106. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  1107. if err != nil {
  1108. logs.Error(err)
  1109. // appG.Response(http.StatusOK, e.ERROR, false)
  1110. return err
  1111. }
  1112. }
  1113. for _, newFeedp := range newFeedpList {
  1114. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  1115. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  1116. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  1117. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  1118. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  1119. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  1120. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  1121. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  1122. if err != nil {
  1123. logs.Error(err)
  1124. // appG.Response(http.StatusOK, e.ERROR, false)
  1125. return err
  1126. }
  1127. }
  1128. return nil
  1129. }