yq.go 42 KB

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