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, pastureinfo.Werks)
  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, pastureinfo.Werks)
  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, werks 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. if fmt.Sprintf("%v", arg["farmId"]) == werks {
  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. }
  551. type bar struct {
  552. BarName string `xorm:"barname"`
  553. Ccount string `xorm:"ccount"`
  554. Ratio string `xorm:"ratio"`
  555. Ftname string `xorm:"ftname"`
  556. Times1 float64 `xorm:"times1"`
  557. Times2 float64 `xorm:"times2"`
  558. Times3 float64 `xorm:"times3"`
  559. Times4 float64 `xorm:"times4"`
  560. Times5 float64 `xorm:"times5"`
  561. Times6 float64 `xorm:"times6"`
  562. }
  563. func fpdBatchEdit(pastureid string, b *bar) {
  564. // appG := app.Gin{C: c}
  565. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  566. // fsions := gofasion.NewFasion(string(dataByte))
  567. // barList := fsions.Get("barList").Array()
  568. // pastureid := fsions.Get("pastureId").ValueStr()
  569. tx := restful.Engine.NewSession()
  570. defer tx.Close()
  571. 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
  572. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  573. if err != nil {
  574. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  575. return
  576. }
  577. // for _, barFsions := range barList {
  578. dataexcel := make(map[string]interface{}, 0)
  579. dataexcel["barname"] = b.BarName
  580. dataexcel["ccount"] = b.Ccount
  581. dataexcel["ratio"] = b.Ratio
  582. dataexcel["ftname"] = b.Ftname
  583. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  584. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  585. return
  586. }
  587. dataexcel["1"] = b.Times1
  588. dataexcel["2"] = b.Times2
  589. dataexcel["3"] = b.Times3
  590. dataexcel["4"] = b.Times4
  591. dataexcel["5"] = b.Times5
  592. dataexcel["6"] = b.Times6
  593. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  594. if err != nil {
  595. logs.Error(err)
  596. return
  597. }
  598. if !ftexist {
  599. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  600. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  601. if err != nil {
  602. logs.Error(err)
  603. return
  604. }
  605. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  606. if err != nil {
  607. logs.Error(err)
  608. return
  609. }
  610. }
  611. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  612. if err != nil {
  613. logs.Error(err)
  614. return
  615. }
  616. if !exist {
  617. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  618. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  619. if err != nil {
  620. logs.Error(err)
  621. return
  622. }
  623. }
  624. var feedpargs []interface{}
  625. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  626. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  627. if _, ok := dataexcel["ftname"]; ok {
  628. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  629. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  630. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  631. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  632. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  633. } else {
  634. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  635. }
  636. if _, ok := dataexcel["ptsfname"]; ok {
  637. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  638. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  639. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  640. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  641. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  642. } else {
  643. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  644. }
  645. upFeedpSql += " where barname = ? and pastureid = ? "
  646. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  647. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  648. if err != nil {
  649. logs.Error(err)
  650. return
  651. }
  652. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  653. if err != nil {
  654. logs.Error(err)
  655. return
  656. }
  657. if !exist1 {
  658. _, 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) `,
  659. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  660. if err != nil {
  661. logs.Error(err)
  662. return
  663. }
  664. }
  665. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  666. if err != nil {
  667. logs.Error(err)
  668. return
  669. }
  670. if !exist2 {
  671. _, 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) `,
  672. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  673. if err != nil {
  674. logs.Error(err)
  675. return
  676. }
  677. }
  678. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  679. if err != nil {
  680. logs.Error(err)
  681. return
  682. }
  683. if !exist3 {
  684. _, 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) `,
  685. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  686. if err != nil {
  687. logs.Error(err)
  688. return
  689. }
  690. }
  691. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  692. if err != nil {
  693. logs.Error(err)
  694. return
  695. }
  696. if !exist4 {
  697. _, 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) `,
  698. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  699. if err != nil {
  700. logs.Error(err)
  701. return
  702. }
  703. }
  704. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  705. if err != nil {
  706. logs.Error(err)
  707. return
  708. }
  709. if !exist5 {
  710. _, 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) `,
  711. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  712. if err != nil {
  713. logs.Error(err)
  714. return
  715. }
  716. }
  717. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  718. if err != nil {
  719. logs.Error(err)
  720. return
  721. }
  722. if !exist6 {
  723. _, 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) `,
  724. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  725. if err != nil {
  726. logs.Error(err)
  727. return
  728. }
  729. }
  730. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  731. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  732. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  733. and pastureid = ? and times = ?`
  734. var fpdargs1 []interface{}
  735. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  736. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  737. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  738. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  739. if err != nil {
  740. return
  741. }
  742. var fpdargs2 []interface{}
  743. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  744. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  745. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  746. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  747. if err != nil {
  748. return
  749. }
  750. var fpdargs3 []interface{}
  751. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  752. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  753. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  754. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  755. if err != nil {
  756. return
  757. }
  758. var fpdargs4 []interface{}
  759. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  760. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  761. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  762. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  763. if err != nil {
  764. return
  765. }
  766. var fpdargs5 []interface{}
  767. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  768. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  769. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  770. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  771. if err != nil {
  772. return
  773. }
  774. var fpdargs6 []interface{}
  775. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  776. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  777. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  778. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  779. if err != nil {
  780. return
  781. }
  782. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  783. 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()
  784. if err != nil {
  785. return
  786. }
  787. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  788. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  789. upFpdetailList := make([]*upFpdetail, 0)
  790. for _, newfpd := range newList {
  791. for _, oldfpd := range oldFpdList {
  792. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  793. var oldweight, newweight float64
  794. if oldfpd["weight"] != nil {
  795. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  796. }
  797. if newfpd["weight"] != nil {
  798. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  799. }
  800. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  801. upFpdetailList = append(upFpdetailList, &upFpdetail{
  802. Old: oldweight,
  803. New: newweight,
  804. Times: newfpd["times"].(int64),
  805. Ptid: newfpd["ptid"].(int64),
  806. Fweight: fweight,
  807. Id: oldfpd["id"].(int64),
  808. })
  809. break
  810. }
  811. }
  812. }
  813. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  814. }
  815. type lpplandtlInfo struct {
  816. Id int64 `xorm:"id"`
  817. Pastureid int64 `xorm:"pastureid"`
  818. Lppid int64 `xorm:"lppid"`
  819. Barid int64 `xorm:"barid"`
  820. Barname string `xorm:"barname"`
  821. Fpdid int64 `xorm:"fpdid"`
  822. Fttype int64 `xorm:"fttype"`
  823. Lweight float64 `xorm:"lweight"`
  824. Sort int64 `xorm:"sort"`
  825. Tmrid int64 `xorm:"tmrid"`
  826. Tmrname string `xorm:"tmrname"`
  827. Cowcount int64 `xorm:"cowcount"`
  828. Ccountradio float64 `xorm:"ccountradio"`
  829. Background string `xorm:"background"`
  830. Lweighthis float64 `xorm:"lweighthis"`
  831. Maxweight float64 `xorm:"maxweight"`
  832. }
  833. type upFpdetail struct {
  834. Old float64
  835. New float64
  836. Times int64
  837. Ptid int64
  838. Fweight float64
  839. Id int64
  840. }
  841. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  842. tx := restful.Engine.NewSession()
  843. defer tx.Close()
  844. tx.Begin()
  845. 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 `,
  846. pastureid, barname).Query().List()
  847. if err != nil {
  848. logs.Error(err)
  849. }
  850. for _, fpd := range fpdList {
  851. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  852. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  853. pastureid, fpd["id"], fpd["times"]).Query().List()
  854. if err != nil {
  855. tx.Rollback()
  856. logs.Error(err)
  857. return err
  858. }
  859. var lweight float64
  860. for _, lppland := range lpplandList {
  861. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  862. lweight += lweight1
  863. }
  864. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  865. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  866. if fpdweight >= ptuse && lweight == ptuse {
  867. continue
  868. } else {
  869. if lweight <= fpdweight {
  870. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  871. if err != nil {
  872. tx.Rollback()
  873. logs.Error(err)
  874. return err
  875. }
  876. } else {
  877. weight := lweight - fpdweight
  878. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  879. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  880. if err != nil {
  881. tx.Rollback()
  882. logs.Error(err)
  883. return err
  884. }
  885. for _, lppland := range lpplandList {
  886. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  887. if weight >= lpplandlweight {
  888. weight = weight - lpplandlweight
  889. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  890. if err != nil {
  891. tx.Rollback()
  892. logs.Error(err)
  893. return err
  894. }
  895. } else {
  896. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  897. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  898. if err != nil {
  899. tx.Rollback()
  900. logs.Error(err)
  901. return err
  902. }
  903. weight = 0
  904. break
  905. }
  906. }
  907. }
  908. }
  909. }
  910. for _, list := range dataList {
  911. ftmap := make(map[string]interface{})
  912. ftmap["old"] = list.Old
  913. ftmap["new"] = list.New
  914. ftmap["times"] = list.Times
  915. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  916. ftmap["ptsid"] = ""
  917. // fmt.Println(ftmap)
  918. // 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 ,
  919. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  920. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  921. // UNION
  922. fpdDataList, err := tx.SQL(`
  923. 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 ,
  924. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  925. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  926. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  927. if err != nil {
  928. tx.Rollback()
  929. logs.Error(err)
  930. }
  931. for _, fpd := range fpdDataList {
  932. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  933. // fttype := -1
  934. // if fpd["fttype"].(string) == "1" {
  935. fttype := 1
  936. // }
  937. var fweight float64
  938. var lweight float64
  939. lpplandtl1List := make([]*lpplandtlInfo, 0)
  940. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  941. join lpplandtl1 lppland on lpp.id = lppland.lppid
  942. join tmr t on t.id = lpp.tmrid
  943. where lppland.fpdid =?
  944. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  945. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  946. if err != nil {
  947. tx.Rollback()
  948. logs.Error(err)
  949. }
  950. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  951. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  952. // 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
  953. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  954. var w float64
  955. var status int
  956. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  957. if weight >= 0 {
  958. continue
  959. }
  960. w = weight
  961. status = 0
  962. } else {
  963. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  964. // continue
  965. // }
  966. w = weight
  967. status = 1
  968. }
  969. // for _, lppland := range lpplandtl1List {
  970. // lweight += lppland.Lweight
  971. // }
  972. for _, lppland := range lpplandtl1List {
  973. lpplandInfo := new(lpplandtlInfo)
  974. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  975. lweight = lpplandInfo.Lweight
  976. if status == 1 {
  977. // if w <= lppland.Lweight {
  978. if lppland.Maxweight <= lweight {
  979. continue
  980. }
  981. if w+lweight <= lppland.Maxweight {
  982. lppland.Lweight += w
  983. lweight += w
  984. fweight += w
  985. w = 0
  986. } else {
  987. w = w - (lppland.Maxweight - lweight)
  988. n := (lppland.Maxweight - lweight)
  989. lppland.Lweight = lppland.Lweight + n
  990. lweight += n
  991. fweight += n
  992. }
  993. } else {
  994. if lppland.Lweight == 0 {
  995. continue
  996. }
  997. if w+lppland.Lweight >= 0 {
  998. lppland.Lweight = lppland.Lweight + w
  999. lweight = lweight + w
  1000. fweight = fweight + w
  1001. w = 0
  1002. } else {
  1003. w = w + lppland.Lweight
  1004. lweight = lweight - lppland.Lweight
  1005. fweight = fweight - lppland.Lweight
  1006. lppland.Lweight = 0
  1007. }
  1008. }
  1009. if lppland.Lweight > 0 {
  1010. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  1011. if err != nil {
  1012. tx.Rollback()
  1013. logs.Error(err)
  1014. return err
  1015. }
  1016. } else {
  1017. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  1018. if err != nil {
  1019. tx.Rollback()
  1020. logs.Error(err)
  1021. return err
  1022. }
  1023. }
  1024. if w == 0 {
  1025. break
  1026. }
  1027. }
  1028. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  1029. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  1030. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  1031. if err != nil {
  1032. tx.Rollback()
  1033. logs.Error(err)
  1034. }
  1035. if w == 0 {
  1036. break
  1037. }
  1038. }
  1039. }
  1040. }
  1041. err = tx.Commit()
  1042. if err != nil {
  1043. logs.Error(err)
  1044. tx.Rollback()
  1045. return err
  1046. }
  1047. now := time.Now()
  1048. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1049. if err != nil {
  1050. logs.Error(err)
  1051. return nil
  1052. }
  1053. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1054. if err != nil {
  1055. logs.Error(err)
  1056. return nil
  1057. }
  1058. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  1059. if err != nil {
  1060. logs.Error(err)
  1061. return nil
  1062. }
  1063. for _, newLpplandtl1 := range newLpplandtl1List {
  1064. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  1065. background,cowcount,ccountradio,lweighthis,createdate)
  1066. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  1067. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  1068. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  1069. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  1070. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  1071. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  1072. if err != nil {
  1073. logs.Error(err)
  1074. // appG.Response(http.StatusOK, e.ERROR, false)
  1075. return err
  1076. }
  1077. }
  1078. for _, newFpd := range newFpdDataList {
  1079. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  1080. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  1081. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  1082. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  1083. if err != nil {
  1084. logs.Error(err)
  1085. // appG.Response(http.StatusOK, e.ERROR, false)
  1086. return err
  1087. }
  1088. }
  1089. for _, newFeedp := range newFeedpList {
  1090. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  1091. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  1092. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  1093. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  1094. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  1095. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  1096. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  1097. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  1098. if err != nil {
  1099. logs.Error(err)
  1100. // appG.Response(http.StatusOK, e.ERROR, false)
  1101. return err
  1102. }
  1103. }
  1104. return nil
  1105. }