package gm import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "tmr-watch/conf/setting" "tmr-watch/http/handle/restful" "tmr-watch/pkg/logging" "github.com/astaxie/beego/logs" "github.com/xormplus/xorm" ) // "../../../pkg/setting" // "../../../routers/restful" // http://172.16.86.95:8080/copartner_downloads?equipmentId=48ffa4de-7870-4b18-a052-9f8d3a46089a&farmId=ef275fb06fd847d88422517773e5a616&method=downloadpen func GmUdSync(pastureId, farmId string) { UdMaterialIssuePush(pastureId, farmId, "") UdFeedtempletPush(pastureId, farmId, "") UdUtirPush(pastureId, farmId, "") UdBarFeedRemainPush(pastureId, farmId, "") UdBarSync(pastureId, farmId) UdFeedSync(pastureId, farmId) } func UdBarSync(pastureId, farmId string) { url := fmt.Sprintf("http://172.16.86.95:8080/copartner_downloads?equipmentId=48ffa4de-7870-4b18-a052-9f8d3a46089a&farmId=%s&method=downloadpen", farmId) barByte := getPull(url) fmt.Println(string(barByte)) barMap := make(map[string]interface{}) json.Unmarshal(barByte, &barMap) tx := restful.Engine.NewSession() defer tx.Close() tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, "", string(barByte), "", "", 3, url) if len(barMap) > 0 { if barMap["status"].(string) != "ok" { return } for _, item := range barMap["msg"].([]interface{}) { bar := item.(map[string]interface{}) barname := bar["barname"].(string) count, _ := tx.Table("bar").Where("pastureId = ? ", pastureId).Count() barExist, _ := tx.SQL(` select count(1) from bar where bcode = ? `, bar["barcode"]).Exist() _, err := tx.Exec(`insert into bar(pastureid,bcode,bname,sort)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ?,udname = ? `, pastureId, bar["barcode"], barname, count+1, barname, barname) _, err = tx.Exec(`insert into feedp(pastureid,barid,barname,softccount,ccount)values(?,(select id from bar where bcode= concat(?) and pastureId = ? ),?,?,?) ON DUPLICATE KEY UPDATE softccount = ? `, // tx.Exec(`update bar `, pastureId, bar["barcode"], barname, count+1, barname, barname) pastureId, bar["barcode"], pastureId, barname, bar["cowcount"], bar["cowcount"], bar["cowcount"]) fmt.Println(bar["barcode"], barname, bar["cowcount"], pastureId, err) if !barExist { tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 1, barname) tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 2, barname) tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 3, barname) tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 4, barname) tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 5, barname) tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode= ? and pastureId = ? ),0,0,?,?)`, pastureId, bar["barcode"], 6, barname) } } } } func UdFeedSync(pastureId, farmId string) { url := fmt.Sprintf("http://172.16.86.95:8080/copartner_downloads?equipmentId=48ffa4de-7870-4b18-a052-9f8d3a46089a&farmId=%s&method=downloadmaterial", farmId) feedByte := getPull(url) fmt.Println(string(feedByte)) tx := restful.Engine.NewSession() defer tx.Close() tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, "", string(feedByte), "", "", 3, url) feedMap := make(map[string]interface{}) json.Unmarshal(feedByte, &feedMap) fmt.Println(string(feedByte)) if len(feedMap) > 0 { if feedMap["status"].(string) != "ok" { return } for _, item := range feedMap["msg"].([]interface{}) { fmt.Println(item) feed := item.(map[string]interface{}) feedname := feed["feedname"].(string) feedClassExist, err := tx.Table("feedclass").Where("fccode = ? ", feed["feedclass"]).Where(" pastureId = ? ", pastureId).Exist() fmt.Println(err) if !feedClassExist { count, _ := tx.Table("feedclass").Where("pastureId = ? ", pastureId).Count() ids, err := setting.SnowIds.NextId() if err != nil { ids = time.Now().UnixNano() logging.Info("create SnowIds err", err) } _, err = tx.Exec(`insert into feedclass(id,pastureId,fcname,fccode,bigfeedclassname,sort,bigfeedclassid) values(?,?,?,?,?,?,?)`, ids, pastureId, feed["feedclass"], feed["feedclass"], feed["feedclass"], count+1, ids) fmt.Println(err) } ids, err := setting.SnowIds.NextId() if err != nil { ids = time.Now().UnixNano() logging.Info("create SnowIds err", err) } _, err = tx.Exec(`insert into feed(id,pastureId,feedcode,udname,fclassid,fclass,fname) values(?,?,?,?,(select id from feedclass where fccode = ? and pastureId = ? ),?,if(char_length(?) > 7, left(?,7),?) ) ON DUPLICATE KEY UPDATE udname = ? ,fclassid = (select id from feedclass where fccode = ? and pastureId = ? ) ,fclass = ?`, ids, pastureId, feed["feedcode"], feedname, feed["feedclass"], pastureId, feed["feedclass"], feedname, feedname, feedname, feedname, feed["feedclass"], pastureId, feed["feedclass"]) fmt.Println(err) } } } func getPull(url string) []byte { forwardingReq := new(ForwardingReq) forwardingReq.Url = url forwardingReq.Method = "GET" jsonStr, _ := json.Marshal(forwardingReq) req, err := http.NewRequest("POST", setting.ServerSetting.UDForwardingSvc+":8080/forwarding", bytes.NewBuffer(jsonStr)) if err != nil { logs.Error(err) // return nil } req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { logs.Error(err) return nil } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) if strings.Index(resp.Status, "200") > -1 { bodyData := make(map[string]string) json.Unmarshal(body, &bodyData) if _, ok := bodyData["data"]; ok { return []byte(bodyData["data"]) } } return nil } //搅拌 func UdUtirPush(pastureId, farmId, date string) error { tx := restful.Engine.NewSession() defer tx.Close() var now string if date != "" { now = date } else { now = time.Now().AddDate(0, 0, -1).Format("2006-01-02") } 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, ifnull(ifnull(fc.fcname,(select fcname from feedclass fc1 join feed f1 on f1.fclassid = fc1.id where f1.id =ftd.fid )),'饲料') ingType, 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, 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, DATE_FORMAT(IFNULL((SELECT MAX(intime) FROM downloadplandtl1 d2 WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime 0 , d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)* d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd.version AND ftd2.ftid = d1.fid )), d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)* d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd.version AND ftd2.ftid = d1.fid )) ),'')),0) feedWeight ,ifnull(ftd.sort,"") premixFeedSort , ifnull((select feedcode from feed where id = ftd.fid),"") premixFeedId,ifnull(ftd.fname,"") premixFeedName, ifnull(if(d1.feedcode = '-1', if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 , d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)* d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd.version AND ftd2.ftid = d1.fid )), d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)* d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd.version AND ftd2.ftid = d1.fid )) ),''),'0') premixFeedWeight from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID LEFT JOIN (select dd.pid as lppid,dd1.* from downloadedplan dd join downloadplandtl1 dd1 on dd1.pid = dd.id and dd1.type = 0 where dd.mydate= date_format(?,'%Y-%m-%d') and dd.lpplanType in (0,1) ) d1 on d1.lppid = d.pid LEFT JOIN feedp fp on d2.FBarID=fp.barid left join bar b on fp.barid = b.id and d.pastureid = b.pastureid left join feed f on f.feedcode = d1.feedcode left JOIN feedtempletdate ft on d.tempid=ft.id and ft.date = d1.date and d.tversion = ft.version left join feedtempletdate ft1 on d1.feedcode = '-1' and ft1.date = d1.date and ft1.id = d1.fid left join ftdetaildate ftd on ftd.date = d1.date and ftd.ftid = d1.fid AND d1.feedcode = '-1' and ftd.version = ft1.version where d.mydate= date_format(?,'%Y-%m-%d') and d2.type = 0 and d.havebutton = 1 and d.pastureid = ? and d1.fname is not null order by tmrno `, now, now, pastureId).Query().List() if err != nil { logging.Error(err) return err } dataByte, _ := json.Marshal(&dataList) reqJson := `{ "reqMethod": "PARTY", "param": { "code": "1", "method": "uploaddiliverdata", "resultData": %s, "farmId": "%s", "rowCount": %d, "errMessage": "" }, "regCode": "cpt180511", "command": "3d6e4752", "apiId": "getCptData" }` reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList)) // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存', postPush(reqJson, 0, tx, pastureId) fmt.Println(reqJson) return nil } func UdBarFeedRemainPush(pastureId, farmId, date string) error { tx := restful.Engine.NewSession() defer tx.Close() var now string if date != "" { now = date } else { now = time.Now().AddDate(0, 0, -1).Format("2006-01-02") } dataList, err := tx.SQL(`SELECT '' startTime, '' endTime, br.RemainDate AS overplusDate, ifnull(b.bcode,b.id) AS penId, b.BNAME AS penName, br.Remain AS actualWeight FROM barfeedremain br LEFT JOIN feedp fp ON br.barid = fp.id left join bar b on b.id = fp.barid WHERE date_format( RemainDate, '%Y-%m-%d' ) =? `, now).Query().List() if err != nil { logging.Error(err) return err } dataByte, _ := json.Marshal(&dataList) reqJson := `{ "reqMethod": "PARTY", "param": { "code": "1", "method": "uploadoverplusdata", "resultData": %s, "farmId":"%s", "rowCount": %d, "errMessage": "" }, "regCode": "cpt180511", "command": "3d6e4752", "apiId": "getCptData" }` reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList)) // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存', fmt.Println(reqJson) postPush(reqJson, 1, tx, pastureId) return nil } // method: // 配方 getfeedtempletinfo // 搅拌数据 uploadadddata // 撒料数据 uploaddiliverdata // 剩料 uploadoverplusdata func UdFeedtempletPush(pastureId, farmId, date string) error { tx := restful.Engine.NewSession() defer tx.Close() var now string if date != "" { now = date } else { now = time.Now().AddDate(0, 0, -1).Format("2006-01-02") } dataList, err := tx.SQL(`SELECT ft.tcode AS recipeId, ft.TNAME AS recipeName, f.feedcode AS ingId, ifnull(f.udname,f.fname) AS ingName, round( f.dry * ftd.FWEIGHT, 2 ) AS dmQty, ftd.FWEIGHT AS afQty, ftd.SORT AS mixNo, round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost, fc.fcname AS ingType, f.AllowRatio AS allowableError ,fc.fcname ingType FROM feedtempletdate ft JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date JOIN feed f ON ftd.FID = f.id JOIN feedclass fc ON f.fclassid = fc.id WHERE ft.ENABLE = 1 AND ft.isDelete != 1 and ft.date = ? `, now).Query().List() if err != nil { logging.Error(err) return err } dataByte, _ := json.Marshal(&dataList) reqJson := `{ "reqMethod": "PARTY", "param": { "code": "1", "method": "getfeedtempletinfo", "resultData": %s, "farmId": "%s", "rowCount": %d, "errMessage": "" }, "regCode": "cpt180511", "command": "3d6e4752", "apiId": "getCptData" }` reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList)) fmt.Println(reqJson) postPush(reqJson, 4, tx, pastureId) return nil } type ForwardingReq struct { Body string `json:"body"` Headers []*Headers `json:"headers"` Url string `json:"url"` Method string `json:"method"` } type Headers struct { Key string `json:"key"` Value string `json:"value"` } func postPush(data string, msgtype int, tx *xorm.Session, pastureId string) { forwardingReq := new(ForwardingReq) forwardingReq.Url = "http://172.16.86.95:8080/copartner_uploads/" forwardingReq.Method = "POST" forwardingReq.Body = data jsonStr, _ := json.Marshal(forwardingReq) fmt.Println(setting.ServerSetting.UDForwardingSvc) req, err := http.NewRequest("POST", setting.ServerSetting.UDForwardingSvc+":8080/forwarding", bytes.NewBuffer(jsonStr)) if err != nil { logs.Error(err) // return nil } req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { logs.Error(err) return } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) if strings.Index(resp.Status, "200") > -1 { bodyData := make(map[string]string) json.Unmarshal(body, &bodyData) if _, ok := bodyData["data"]; ok { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, bodyData["data"], "", "", msgtype, forwardingReq.Url) } else { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, forwardingReq.Url) } } else { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, forwardingReq.Url) } }