yq.go 42 KB

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