Browse Source

正诚对接

baishaojie 2 years ago
parent
commit
dbbf2a922f
49 changed files with 1668 additions and 382 deletions
  1. BIN
      KPTAdmin64.exe
  2. BIN
      TMRWatchComm
  3. 18 1
      conf/app.ini
  4. BIN
      dist(1).zip
  5. BIN
      dist(20).zip
  6. BIN
      dist-TMR-测试地址-20230322-1.zip
  7. BIN
      dist-TMR-测试地址-20230322-2.zip
  8. BIN
      dist-TMR-测试地址-20230322-2/dist/favicon.ico
  9. 0 0
      dist-TMR-测试地址-20230322-2/dist/index.html
  10. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/css/app.99dfb9eb.css
  11. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/css/chunk-elementUI.f92cd1c5.css
  12. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/css/chunk-libs.1664ae71.css
  13. BIN
      dist-TMR-测试地址-20230322-2/dist/static/fonts/element-icons.535877f5.woff
  14. BIN
      dist-TMR-测试地址-20230322-2/dist/static/fonts/element-icons.732389de.ttf
  15. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/404.a57b6f31.png
  16. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/404_cloud.0f4bc32b.png
  17. 28 0
      dist-TMR-测试地址-20230322-2/dist/static/img/iconfont.7d9f8392.svg
  18. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/logo.afed751a.png
  19. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/logo1.0121925c.png
  20. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/logo_u3.3c77f543.png
  21. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/nlogin-bg1.77301f56.jpg
  22. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/row-bg3.b3be7548.png
  23. BIN
      dist-TMR-测试地址-20230322-2/dist/static/img/topBg.69ecd1e1.png
  24. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/app.9e5f3a66.js
  25. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-52ecc0ac.a7dca219.js
  26. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-5c4dc4a9.a119f214.js
  27. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-7085d3cc.df62b750.js
  28. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-b702d234.66ccaac4.js
  29. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-elementUI.60d920b6.js
  30. 0 0
      dist-TMR-测试地址-20230322-2/dist/static/js/chunk-libs.bc9e1339.js
  31. 0 0
      dist/index.html
  32. 0 0
      dist/static/css/app.99dfb9eb.css
  33. 0 0
      dist/static/js/app.8a3d01f3.js
  34. 0 0
      dist/static/js/app.9e5f3a66.js
  35. BIN
      dist现代牧业.zip
  36. 23 0
      models/models.go
  37. 53 35
      pkg/setting/setting.go
  38. 333 91
      routers/api/db.go
  39. 460 0
      routers/api/mqtt.go
  40. 11 7
      routers/api/scheduled.go
  41. 16 3
      routers/api/spillage.go
  42. 60 39
      routers/api/upload.go
  43. 342 0
      routers/api/zc/zc.go
  44. 28 2
      routers/restful/sql_utils.go
  45. 7 3
      routers/router.go
  46. 287 40
      shengji.sql
  47. 2 161
      update.sql
  48. BIN
      uploads/image/abstract.png
  49. BIN
      uploads/image/default.jpg

BIN
KPTAdmin64.exe


BIN
TMRWatchComm


+ 18 - 1
conf/app.ini

@@ -49,7 +49,7 @@ Password = root
 Host = 192.168.1.93:3326
 #Host = 127.0.0.1:3316
 Name = tmrwatch3
-Password = root 
+Password = root
 #Password = root
 #Password = kptzhu@163.com
 #Host = 192.168.1.50:3326
@@ -78,6 +78,23 @@ ShowXormlog = false
 ShowGetSqllog = false
 CacheApiSql = false
 
+
+[sqlserver]
+#Host = "sqlserver://sa:Password@@localhost?database=SysData&connection+timeout=30"
+##张北乐源
+Host = 127.0.0.1
+User = sa
+Password = P@ssword123
+Name = SysData
+
+
+[yyn]
+FarmId = ""
+ProductKey = ""
+DeviceName = ""
+DeviceSecret = ""
+HeartBeat = ""
+
 [comm]
 PortName =
 BaudRate = 9600

BIN
dist(1).zip


BIN
dist(20).zip


BIN
dist-TMR-测试地址-20230322-1.zip


BIN
dist.zip → dist-TMR-测试地址-20230322-2.zip


BIN
dist-TMR-测试地址-20230322-2/dist/favicon.ico


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/index.html


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/css/app.99dfb9eb.css


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/css/chunk-elementUI.f92cd1c5.css


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/css/chunk-libs.1664ae71.css


BIN
dist-TMR-测试地址-20230322-2/dist/static/fonts/element-icons.535877f5.woff


BIN
dist-TMR-测试地址-20230322-2/dist/static/fonts/element-icons.732389de.ttf


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/404.a57b6f31.png


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/404_cloud.0f4bc32b.png


File diff suppressed because it is too large
+ 28 - 0
dist-TMR-测试地址-20230322-2/dist/static/img/iconfont.7d9f8392.svg


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/logo.afed751a.png


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/logo1.0121925c.png


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/logo_u3.3c77f543.png


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/nlogin-bg1.77301f56.jpg


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/row-bg3.b3be7548.png


BIN
dist-TMR-测试地址-20230322-2/dist/static/img/topBg.69ecd1e1.png


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/app.9e5f3a66.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-52ecc0ac.a7dca219.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-5c4dc4a9.a119f214.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-7085d3cc.df62b750.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-b702d234.66ccaac4.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-elementUI.60d920b6.js


File diff suppressed because it is too large
+ 0 - 0
dist-TMR-测试地址-20230322-2/dist/static/js/chunk-libs.bc9e1339.js


File diff suppressed because it is too large
+ 0 - 0
dist/index.html


File diff suppressed because it is too large
+ 0 - 0
dist/static/css/app.99dfb9eb.css


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/app.8a3d01f3.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/app.9e5f3a66.js


BIN
dist现代牧业.zip


+ 23 - 0
models/models.go

@@ -12,6 +12,7 @@ import (
 )
 
 var Engine *xorm.Engine
+var SqlServerEngine *xorm.Engine
 
 func Setup() {
 	var err error
@@ -36,3 +37,25 @@ func Setup() {
 		panic(err)
 	}
 }
+
+func SetupSqlserver() {
+	// if setting.SQlserverSetting.Host != "" {
+	// 	var err error
+	// 	// restful  接口的 数据库初始化
+	// 	if err := restful.SQLInit("odbc", setting.SQlserverSetting.Host, 1000, 10, setting.DatabaseSetting.ShowXormlog); err != nil {
+	// 		log.Fatal(err.Error())
+	// 		fmt.Println("dbs 数据库初始化失败 ")
+	// 	}
+	// 	SqlServerEngine = restful.Engine
+	// 	if err != nil {
+	// 		log.Fatalf("models.Setup err: %v", err)
+	// 	}
+	// 	SqlServerEngine.SetConnMaxLifetime(time.Second * 30)
+	// 	SqlServerEngine.ShowSQL(true)
+	// 	if err = SqlServerEngine.Ping(); err != nil {
+	// 		logs.Error(err)
+	// 		panic(err)
+	// 	}
+	// }
+}
+

+ 53 - 35
pkg/setting/setting.go

@@ -2,9 +2,6 @@ package setting
 
 import (
 	"errors"
-	"github.com/go-ini/ini"
-	"github.com/jacobsa/go-serial/serial"
-	"github.com/kptyun/KPTCOMM/pkg/util"
 	"log"
 	"os"
 	"os/exec"
@@ -12,6 +9,10 @@ import (
 	"runtime"
 	"strings"
 	"time"
+
+	"github.com/go-ini/ini"
+	"github.com/jacobsa/go-serial/serial"
+	"github.com/kptyun/KPTCOMM/pkg/util"
 )
 
 type App struct {
@@ -22,8 +23,8 @@ type App struct {
 	RuntimeRootPath string
 
 	FileSavePath  string
-	FileMaxSize   int  // 普通文件上传的限制大小,单位byte, 最大单位1GB
-	FileAllowType [] string  // 允许上传的文件后缀名
+	FileMaxSize   int      // 普通文件上传的限制大小,单位byte, 最大单位1GB
+	FileAllowType []string // 允许上传的文件后缀名
 
 	ImageSavePath  string
 	ImageMaxSize   int
@@ -46,22 +47,22 @@ type App struct {
 var AppSetting = &App{}
 
 type Server struct {
-	RunMode      string
-	HttpPort     int
-	ReadTimeout  time.Duration
-	WriteTimeout time.Duration
-	NoAuth  int
+	RunMode          string
+	HttpPort         int
+	ReadTimeout      time.Duration
+	WriteTimeout     time.Duration
+	NoAuth           int
 	Mdns_servicename string
 	Mdns_serviceport int
-	HttpsPort int
-	Https  int
-	CrtPath string
-	KeyPath string
-	ServerName string
-	DisplayName string
-	Description string
-	GRFD string
-	GRFDURL string
+	HttpsPort        int
+	Https            int
+	CrtPath          string
+	KeyPath          string
+	ServerName       string
+	DisplayName      string
+	Description      string
+	GRFD             string
+	GRFDURL          string
 }
 
 var ServerSetting = &Server{}
@@ -70,25 +71,42 @@ var CommSetting = &serial.OpenOptions{}
 var SnowIds *util.IdWorker
 
 type Database struct {
-	Type        string
-	User        string
-	Password    string
-	Host        string
-	Name        string
-	ShowXormlog  bool
+	Type          string
+	User          string
+	Password      string
+	Host          string
+	Name          string
+	ShowXormlog   bool
 	ShowGetSqllog bool
-	CacheApiSql bool
-	TablePrefix string
+	CacheApiSql   bool
+	TablePrefix   string
 }
 
+type SQlserver struct {
+	Host string
+	User     string
+	Password string
+	Name     string
+}
+
+type Yyn struct {
+	FarmId       string
+	ProductKey   string
+	DeviceName   string
+	DeviceSecret string
+	HeartBeat    string
+}
 
 var DatabaseSetting = &Database{}
 
+var SQlserverSetting = &SQlserver{}
 
-var cfg *ini.File
+var YynserverSetting = &Yyn{}
 
+var cfg *ini.File
 
 var CurrentPath string
+
 func GetCurrentPath() (string, error) {
 	file, err := exec.LookPath(os.Args[0])
 	if err != nil {
@@ -112,17 +130,17 @@ func GetCurrentPath() (string, error) {
 }
 func Setup(dir string) {
 	var err error
-	if strings.Trim(dir," ")=="" {
+	if strings.Trim(dir, " ") == "" {
 		CurrentPath, err = GetCurrentPath()
-	}else {
-		CurrentPath=dir
+	} else {
+		CurrentPath = dir
 	}
-	cfg, err = ini.Load(CurrentPath+"conf/app.ini")
+	cfg, err = ini.Load(CurrentPath + "conf/app.ini")
 	if err != nil {
 		log.Fatalf("setting.Setup, fail to parse 'conf/app.ini': %v", err)
 	}
 
-	SnowIds,err =util.NewIdWorker(1)
+	SnowIds, err = util.NewIdWorker(1)
 	if err != nil {
 		log.Fatalf("setting.Setup, fail to create SnowIds: %v", err)
 	}
@@ -133,7 +151,9 @@ func Setup(dir string) {
 	mapTo("server", ServerSetting)
 	mapTo("database", DatabaseSetting)
 	mapTo("comm", CommSetting)
+	mapTo("sqlserver", SQlserverSetting)
 
+	mapTo("yyn", YynserverSetting)
 	AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024
 	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
 	ServerSetting.WriteTimeout = ServerSetting.ReadTimeout * time.Second
@@ -141,7 +161,6 @@ func Setup(dir string) {
 	ServerSetting.CrtPath = CurrentPath + ServerSetting.CrtPath
 	ServerSetting.KeyPath = CurrentPath + ServerSetting.KeyPath
 
-
 }
 
 func mapTo(section string, v interface{}) {
@@ -150,4 +169,3 @@ func mapTo(section string, v interface{}) {
 		log.Fatalf("Cfg.MapTo RedisSetting err: %v", err)
 	}
 }
-

+ 333 - 91
routers/api/db.go

@@ -222,13 +222,49 @@ func GetDataByName(c *gin.Context) {
 			_ = xlsxfile.Write(c.Writer)
 
 		} else {
+			if sqlnamestr == "getHomepageStr" {
+				parammaps := fsion.Get("parammaps")
+				pastureid := parammaps.Get("pastureid").ValueStr()
+				var montimeList []float64
+				var montime float64
+				var wg sync.WaitGroup
+
+				now := time.Now()
+				for i := 0; i < 30; i++ {
+					wg.Add(1)
+					nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
+					go func(nowstr string) {
+						defer wg.Done()
+						sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
+						slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
+						m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
+						montimeList = append(montimeList, m)
+					}(nowstr)
+				}
+
+				queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+				if err != nil {
+					logging.Error("GetDataByName  err: ", err)
+					msg := geterrmsg(err.Error())
+					appG.Response(http.StatusOK, e.ERROR, msg)
+				}
+
+				wg.Wait()
+				for _, m := range montimeList {
+					montime += m
+				}
+				queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
 
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+				return
+			}
 			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
 			if err != nil {
 				logging.Error("GetDataByName  err: ", err)
 				msg := geterrmsg(err.Error())
 				appG.Response(http.StatusOK, e.ERROR, msg)
 			} else {
+
 				appG.Response(http.StatusOK, e.SUCCESS, queryData)
 			}
 		}
@@ -2906,6 +2942,8 @@ func GetSummary(c *gin.Context) {
 			sqlnamestr = "getAccuracyMC"
 		} else if status == "6" {
 			sqlnamestr = "getAccuracyFeedHL"
+		} else if status == "7" {
+			sqlnamestr = "getAccuracyRT"
 		}
 	} else {
 		if status == "0" {
@@ -2920,6 +2958,8 @@ func GetSummary(c *gin.Context) {
 			sqlnamestr = "getAccuracySCC"
 		} else if status == "5" {
 			sqlnamestr = "getAccuracySLCL"
+		} else if status == "7" {
+			sqlnamestr = "getAccuracySCCRT"
 		}
 	}
 	if isDate == "1" {
@@ -3485,7 +3525,7 @@ func UpdateFpdetailBar(c *gin.Context) {
 					lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
 					if weight >= lpplandlweight {
 						weight = weight - lpplandlweight
-						_, err := tx.SQL(` delete from  lppland  where id = ? `, lppland["id"]).Execute()
+						_, err := tx.SQL(` delete from  lpplandtl1  where id = ? `, lppland["id"]).Execute()
 						if err != nil {
 							tx.Rollback()
 							logs.Error(err)
@@ -3493,7 +3533,7 @@ func UpdateFpdetailBar(c *gin.Context) {
 							return
 						}
 					} else {
-						_, err := tx.SQL(` update   lppland set lweight = ? where id = ? `, lppland["lweight"].(float64)-weight, lppland["id"]).Execute()
+						_, err := tx.SQL(` update   lpplandtl1 set lweight = ? where id = ? `, lppland["lweight"].(float64)-weight, lppland["id"]).Execute()
 						if err != nil {
 							tx.Rollback()
 							logs.Error(err)
@@ -4151,9 +4191,6 @@ func FpdImportExcel(c *gin.Context) {
 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 		return
 	}
-	for _, item := range oldFpdList {
-		fmt.Println(item)
-	}
 	rows, _ := xlsx1.GetRows(sheetname)
 	// 限制10000条,多余的截取掉
 	if len(rows) > 10000 {
@@ -4578,113 +4615,312 @@ func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) erro
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
 	tx.Begin()
-	for _, data := range dataList {
-		fttype := -1
-		if data.Ptid != -1 {
-			fttype = 1
-		}
 
-		var fweight float64
-		var lweight float64
-		lpplandtl1List := make([]*lpplandtlInfo, 0)
-		err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
-					join lpplandtl1 lppland on lpp.id = lppland.lppid  where lppland.fpdid =?
-					and lppland.fttype = ? and lpp.pastureid = ?  and lpp.times  = ? order by lpp.sort desc `,
-			data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
+	fpdList, err := tx.SQL(` select  id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse,times  from fpdetail where pastureid = ?  and barname = ? order by times `,
+		pastureid, barname).Query().List()
+	if err != nil {
+		logs.Error(err)
+	}
+
+	for _, fpd := range fpdList {
+
+		lpplandList, err := tx.SQL(` select  lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid 
+where lppland.pastureid = ?  and lppland.fpdid = ? and lpp.times = ?  order by lpp.sort desc  `,
+			pastureid, fpd["id"], fpd["times"]).Query().List()
 		if err != nil {
 			tx.Rollback()
 			logs.Error(err)
 			return err
 		}
-
-		weight := data.Fweight
-		// weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
-
-		var w float64
-		var status int
-		if data.New < data.Old {
-			if weight >= 0 {
-				continue
-			}
-			w = weight
-			status = 0
-		} else {
-			// if weight-(data.New-data.Old) > 0 {
-			// 	continue
-			// }
-			w = data.New - data.Old
-			status = 1
+		var lweight float64
+		for _, lppland := range lpplandList {
+			lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
+			lweight += lweight1
 		}
-		for _, lppland := range lpplandtl1List {
-			var lppdata lpplandtlInfo
-			tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp  where lppid = ? and  lpp.pastureid = ? `,
-				lppland.Lppid, pastureid).GetFirst(&lppdata)
-			if err != nil {
-				tx.Rollback()
-				logs.Error(err)
-				return err
-			}
-			lweight = lppdata.Lweight
-			if status == 1 {
-				// if w <= lppland.Lweight {
-				if lppland.Maxweight <= lweight {
-					continue
-				}
-				if w+lweight <= lppland.Maxweight {
-					lppland.Lweight += w
-					lweight += w
-					fweight += w
-					w = 0
-				} else {
 
-					w = w - (lppland.Maxweight - lweight)
-					n := (lppland.Maxweight - lweight)
-					lppland.Lweight = lppland.Lweight + n
-					lweight += n
-					fweight += n
+		fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
+		ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
 
+		if fpdweight >= ptuse && lweight == ptuse {
+			continue
+		} else {
+			if lweight <= fpdweight {
+				_, err := tx.SQL(` update fpdetail set ptuse = ?  where id = ? `, lweight, fpd["id"]).Execute()
+				if err != nil {
+					tx.Rollback()
+					logs.Error(err)
+					return err
 				}
 			} else {
-				if lppland.Lweight == 0 {
-					continue
-				}
-				if w+lppland.Lweight >= 0 {
-					lppland.Lweight = lppland.Lweight + w
-					lweight = lweight + w
-					fweight = fweight + w
-					w = 0
-				} else {
-					w = w + lppland.Lweight
-					lweight = lweight - lppland.Lweight
-					fweight = fweight - lppland.Lweight
-					lppland.Lweight = 0
+				weight := lweight - fpdweight
+				_, err = tx.SQL(`UPDATE fpdetail SET ptuse=? 
+				WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
+				if err != nil {
+					tx.Rollback()
+					logs.Error(err)
+					return err
 				}
 
+				for _, lppland := range lpplandList {
+					lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
+					if weight >= lpplandlweight {
+						weight = weight - lpplandlweight
+						_, err := tx.SQL(` delete from  lpplandtl1  where id = ? `, lppland["id"]).Execute()
+						if err != nil {
+							tx.Rollback()
+							logs.Error(err)
+							return err
+						}
+					} else {
+						lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
+						_, err := tx.SQL(` update   lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
+						if err != nil {
+							tx.Rollback()
+							logs.Error(err)
+							return err
+						}
+						weight = 0
+						break
+					}
+				}
 			}
-
-			_, err = tx.SQL(`update lpplandtl1  set Lweight = ?  where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
-			if err != nil {
-				tx.Rollback()
-				logs.Error(err)
-				return err
-			}
-			break
 		}
-		_, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
-					ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
-					WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
+	}
+
+	for _, list := range dataList {
+		ftmap := make(map[string]interface{})
+		ftmap["old"] = list.Old
+		ftmap["new"] = list.New
+		ftmap["times"] = list.Times
+		ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
+		ftmap["ptsid"] = ""
+		// fmt.Println(ftmap)
+
+		fpdDataList, err := tx.SQL(`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 ,
+			(select bname  from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill  FROM fpdetail
+			WHERE fpdetail.pastureid = ?   and barname = ? and  times = ?
+			UNION
+			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 ,
+			(select bname  from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill  FROM fpdetail
+			WHERE fpdetail.pastureid = ?  and barname = ? and  times = ? ) t
+			order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
+		// fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
 		if err != nil {
 			tx.Rollback()
 			logs.Error(err)
-			return err
 		}
-		// if w == 0 {
-		// 	break
-		// }
-		// }
 
+		for _, fpd := range fpdDataList {
+			if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
+				fttype := -1
+				if ftmap["ptid"].(string) != "-1" {
+					fttype = 1
+				}
+
+				var fweight float64
+				var lweight float64
+				lpplandtl1List := make([]*lpplandtlInfo, 0)
+				err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
+					join lpplandtl1 lppland on lpp.id = lppland.lppid  where lppland.fpdid =?
+					and lppland.fttype = ? and lpp.pastureid = ?  and lpp.times  = ? order by lpp.sort desc `,
+					fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
+				if err != nil {
+					tx.Rollback()
+					logs.Error(err)
+				}
+
+				weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
+				// ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
+
+				var w float64
+				var status int
+
+				if ftmap["new"].(float64) < ftmap["old"].(float64) {
+					if weight >= 0 {
+						continue
+					}
+					w = weight
+					status = 0
+				} else {
+					if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
+						continue
+					}
+					w = weight
+					status = 1
+				}
+
+				for _, lppland := range lpplandtl1List {
+					lweight += lppland.Lweight
+				}
+
+				for _, lppland := range lpplandtl1List {
+
+					if status == 1 {
+						// if w <= lppland.Lweight {
+						if lppland.Maxweight <= lweight {
+							continue
+						}
+						if w+lweight <= lppland.Maxweight {
+							lppland.Lweight += w
+							lweight += w
+							fweight += w
+							w = 0
+						} else {
+
+							w = w - (lppland.Maxweight - lweight)
+							n := (lppland.Maxweight - lweight)
+							lppland.Lweight = lppland.Lweight + n
+							lweight += n
+							fweight += n
+
+						}
+					} else {
+						if lppland.Lweight == 0 {
+							continue
+						}
+						if w+lppland.Lweight >= 0 {
+							lppland.Lweight = lppland.Lweight + w
+							lweight = lweight + w
+							fweight = fweight + w
+							w = 0
+						} else {
+							w = w + lppland.Lweight
+							lweight = lweight - lppland.Lweight
+							fweight = fweight - lppland.Lweight
+							lppland.Lweight = 0
+						}
+
+					}
+
+					_, err = tx.SQL(`update lpplandtl1  set Lweight = ?  where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
+					if err != nil {
+						tx.Rollback()
+						logs.Error(err)
+						return err
+					}
+					break
+				}
+				_, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
+					ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
+					WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
+				if err != nil {
+					tx.Rollback()
+					logs.Error(err)
+				}
+				if w == 0 {
+					break
+				}
+			}
+
+		}
 	}
-	err := tx.Commit()
+	// for _, data := range dataList {
+	// 	fttype := -1
+	// 	if data.Ptid != -1 {
+	// 		fttype = 1
+	// 	}
+
+	// 	var fweight float64
+	// 	var lweight float64
+	// 	lpplandtl1List := make([]*lpplandtlInfo, 0)
+	// 	err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
+	// 				join lpplandtl1 lppland on lpp.id = lppland.lppid  where lppland.fpdid =?
+	// 				and lppland.fttype = ? and lpp.pastureid = ?  and lpp.times  = ? order by lpp.sort desc `,
+	// 		data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
+	// 	if err != nil {
+	// 		tx.Rollback()
+	// 		logs.Error(err)
+	// 		return err
+	// 	}
+
+	// 	weight := data.Fweight
+	// 	// weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
+
+	// 	var w float64
+	// 	var status int
+	// 	if data.New < data.Old {
+	// 		if weight >= 0 {
+	// 			continue
+	// 		}
+	// 		w = weight
+	// 		status = 0
+	// 	} else {
+	// 		// if weight-(data.New-data.Old) > 0 {
+	// 		// 	continue
+	// 		// }
+	// 		w = data.New - data.Old
+	// 		status = 1
+	// 	}
+	// 	for _, lppland := range lpplandtl1List {
+	// 		var lppdata lpplandtlInfo
+	// 		tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp  where lppid = ? and  lpp.pastureid = ? `,
+	// 			lppland.Lppid, pastureid).GetFirst(&lppdata)
+	// 		if err != nil {
+	// 			tx.Rollback()
+	// 			logs.Error(err)
+	// 			return err
+	// 		}
+	// 		lweight = lppdata.Lweight
+	// 		if status == 1 {
+	// 			// if w <= lppland.Lweight {
+	// 			if lppland.Maxweight <= lweight {
+	// 				continue
+	// 			}
+	// 			if w+lweight <= lppland.Maxweight {
+	// 				lppland.Lweight += w
+	// 				lweight += w
+	// 				fweight += w
+	// 				w = 0
+	// 			} else {
+
+	// 				w = w - (lppland.Maxweight - lweight)
+	// 				n := (lppland.Maxweight - lweight)
+	// 				lppland.Lweight = lppland.Lweight + n
+	// 				lweight += n
+	// 				fweight += n
+
+	// 			}
+	// 		} else {
+	// 			if lppland.Lweight == 0 {
+	// 				continue
+	// 			}
+	// 			if w+lppland.Lweight >= 0 {
+	// 				lppland.Lweight = lppland.Lweight + w
+	// 				lweight = lweight + w
+	// 				fweight = fweight + w
+	// 				w = 0
+	// 			} else {
+	// 				w = w + lppland.Lweight
+	// 				lweight = lweight - lppland.Lweight
+	// 				fweight = fweight - lppland.Lweight
+	// 				lppland.Lweight = 0
+	// 			}
+
+	// 		}
+
+	// 		_, err = tx.SQL(`update lpplandtl1  set Lweight = ?  where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
+	// 		if err != nil {
+	// 			tx.Rollback()
+	// 			logs.Error(err)
+	// 			return err
+	// 		}
+	// 		break
+	// 	}
+	// 	_, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
+	// 				ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
+	// 				WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
+	// 	if err != nil {
+	// 		tx.Rollback()
+	// 		logs.Error(err)
+	// 		return err
+	// 	}
+	// 	// if w == 0 {
+	// 	// 	break
+	// 	// }
+	// 	// }
+
+	// }
+	err = tx.Commit()
 	if err != nil {
 		logs.Error(err)
 		tx.Rollback()
@@ -6297,3 +6533,9 @@ func UpdateMaterialTMRDate(c *gin.Context) {
 
 	appG.Response(http.StatusOK, e.SUCCESS, true)
 }
+
+func Decimal(value float64) float64 {
+	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
+	return value
+}
+

+ 460 - 0
routers/api/mqtt.go

@@ -0,0 +1,460 @@
+package api
+
+import (
+	"bytes"
+	"crypto/hmac"
+	"crypto/sha1"
+	"crypto/tls"
+	"crypto/x509"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"os"
+	"strconv"
+	"time"
+
+	"../../pkg/logging"
+	"../../pkg/setting"
+	"../../routers/restful"
+	"github.com/astaxie/beego/logs"
+	MQTT "github.com/eclipse/paho.mqtt.golang"
+	"github.com/robfig/cron"
+)
+
+func InitMqttClient() {
+	if setting.YynserverSetting.FarmId != "" {
+		c, pubTopic := MqttClient()
+		deviceHeartbeat(c, pubTopic)
+
+		mqttCron := cron.New()
+		mqttCron.AddFunc("10 06 * * *", func() {
+			feedtempletPush(c, pubTopic)
+			stirPush(c, pubTopic)
+			dustingPush(c, pubTopic)
+			equipmentAccuracyPush(c, pubTopic)
+			finishedWeightPush(c, pubTopic)
+			CompletedTrainNumberPush(c, pubTopic)
+		})
+		mqttCron.Start()
+	}
+
+}
+
+func MqttClient() (MQTT.Client, string) {
+	// set the device info, include product key, device name, and device secret
+	// var productKey string = "a1NmXfrjL8M"
+	// var deviceName string = "4776_p_breed"
+	// var deviceSecret string = "c2591b89adff22e1c9f0fc03363f56a4"
+	// 	ProductKey
+	// DeviceName
+	// DeviceSecret
+	var productKey string = setting.YynserverSetting.ProductKey
+	var deviceName string = setting.YynserverSetting.DeviceName
+	var deviceSecret string = setting.YynserverSetting.DeviceSecret
+
+	// set timestamp, clientid, subscribe topic and publish topic
+	var timeStamp string = strconv.FormatInt(time.Now().UnixNano(), 10)
+	var clientId string = "go_device_id_0001"
+	var subTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/get"
+	var pubTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/post"
+
+	// set the login broker url
+	var raw_broker bytes.Buffer
+	raw_broker.WriteString("tls://")
+	raw_broker.WriteString(productKey)
+	raw_broker.WriteString(".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883")
+	opts := MQTT.NewClientOptions().AddBroker(raw_broker.String())
+
+	// calculate the login auth info, and set it into the connection options
+	auth := calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp)
+	opts.SetClientID(auth.mqttClientId)
+	opts.SetUsername(auth.username)
+	opts.SetPassword(auth.password)
+	opts.SetMaxReconnectInterval(1 * time.Second)
+	opts.AutoReconnect = true
+	// opts.SetKeepAlive(60 * 2 * time.Second)
+
+	opts.OnConnect = func(c MQTT.Client) {
+		if token := c.Subscribe(subTopic, 0, feedHeatwatch); token.Wait() && token.Error() != nil {
+			logging.Error("mqtt Subscribe err: ", token.Error())
+			os.Exit(1)
+		}
+	}
+
+	// create and start a client using the above ClientOptions
+	c := MQTT.NewClient(opts)
+	if token := c.Connect(); token.Wait() && token.Error() != nil {
+		logging.Error("mqtt Connect err: ", token.Error())
+
+	}
+	fmt.Print("Connect aliyun IoT Cloud Sucess\n")
+
+	// if token := c.Subscribe(subTopic, 0, feedHeatwatch); token.Wait() && token.Error() != nil {
+	// 	fmt.Println(token.Error())
+	// 	os.Exit(1)
+	// }
+	// subscribe to subTopic("/a1Zd7n5yTt8/deng/user/get") and request messages to be delivered
+
+	// fmt.Println("Subscribe topic "+subTopic+" success\n", c.IsConnected())
+
+	// publish 5 messages to pubTopic("/a1Zd7n5yTt8/deng/user/update")
+	// for i := 0; i < 50; i++ {
+	// 	fmt.Println("publish msg:", i)
+	// 	text := fmt.Sprintf("ABC #%d", i)
+	// 	token := c.Publish(pubTopic, 0, false, text)
+	// 	fmt.Println("publish msg: ", text)
+	// 	token.Wait()
+
+	// 	time.Sleep(2 * time.Second)
+	// }
+	// unsubscribe from subTopic("/a1Zd7n5yTt8/deng/user/get")
+	// if token := c.Unsubscribe(subTopic); token.Wait() && token.Error() != nil {
+	// 	fmt.Println(token.Error())
+	// 	os.Exit(1)
+	// }
+
+	// c.Disconnect(250)
+	return c, pubTopic
+}
+
+func NewTLSConfig() *tls.Config {
+	// Import trusted certificates from CAfile.pem.
+	// Alternatively, manually add CA certificates to default openssl CA bundle.
+	certpool := x509.NewCertPool()
+	pemCerts, err := ioutil.ReadFile("./x509/root.pem")
+	if err != nil {
+		fmt.Println("0. read file error, game over!!")
+
+	}
+
+	certpool.AppendCertsFromPEM(pemCerts)
+
+	// Create tls.Config with desired tls properties
+	return &tls.Config{
+		// RootCAs = certs used to verify server cert.
+		RootCAs: certpool,
+		// ClientAuth = whether to request cert from server.
+		// Since the server is set up for SSL, this happens
+		// anyways.
+		ClientAuth: tls.NoClientCert,
+		// ClientCAs = certs used to validate client cert.
+		ClientCAs: nil,
+		// InsecureSkipVerify = verify that cert contents
+		// match server. IP matches what is in cert etc.
+		InsecureSkipVerify: false,
+		// Certificates = list of certs client sends to server.
+		// Certificates: []tls.Certificate{cert},
+	}
+}
+
+// define a function for the default message handler
+var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
+	fmt.Printf("TOPIC: %s\n", msg.Topic())
+	fmt.Printf("MSG: %s\n", msg.Payload())
+}
+
+type AuthInfo struct {
+	password, username, mqttClientId string
+}
+
+func calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp string) AuthInfo {
+	var raw_passwd bytes.Buffer
+	raw_passwd.WriteString("clientId" + clientId)
+	raw_passwd.WriteString("deviceName")
+	raw_passwd.WriteString(deviceName)
+	raw_passwd.WriteString("productKey")
+	raw_passwd.WriteString(productKey)
+	raw_passwd.WriteString("timestamp")
+	raw_passwd.WriteString(timeStamp)
+	fmt.Println(raw_passwd.String())
+
+	// hmac, use sha1
+	mac := hmac.New(sha1.New, []byte(deviceSecret))
+	mac.Write([]byte(raw_passwd.String()))
+	password := fmt.Sprintf("%02x", mac.Sum(nil))
+	fmt.Println(password)
+	username := deviceName + "&" + productKey
+
+	var MQTTClientId bytes.Buffer
+	MQTTClientId.WriteString(clientId)
+	// hmac, use sha1; securemode=2 means TLS connection
+	MQTTClientId.WriteString("|securemode=2,_v=paho-go-1.0.0,signmethod=hmacsha1,timestamp=")
+	MQTTClientId.WriteString(timeStamp)
+	MQTTClientId.WriteString("|")
+
+	auth := AuthInfo{password: password, username: username, mqttClientId: MQTTClientId.String()}
+	return auth
+}
+
+func feedtempletPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`select f.id  as recipeId , f.tname recipeName,ft.id ingId,ft.fname ingName,ft.fweight  afQty,
+	ft.sort mixNo,fd.allowratio allowableError ,fd.fclass ingType, ft.fweight * ( fd.dry /100 )  dmQty,null recipeCost 
+	 from feedtemplet  f   join ftdetail ft  on ft.ftid = f.id  join feed fd on fd.id = ft.fid	
+	`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData", 
+		"param": {
+		"farmId": %s, 
+				  "method":"getfeedtempletinfo",
+				  "rowCount": "1",
+		"resultData":%s
+		 }
+	}`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, string(b))
+		// c.Publish(pubTopic, 2, false, pushStr)
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+func stirPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`SELECT
+	d.mydate dropDate,
+	d.projname tmrNo,
+	d.times loadShift,
+	d.tempid recipeId,
+	d.templetname recipeName,
+	f.feedcode ingId,
+	d1.fname ingName,
+	f.fclass ingType,
+	f.dry dmPct,
+	d1.sort mixNo,
+	d1.feedallowratio allowableError,
+	d1.lweight expWeight,
+	d1.actualweightminus actualWeight,
+	d1.begintime startTime,
+	d1.intime endTime 
+FROM
+	downloadedplan d
+	JOIN downloadplandtl1 d1 ON d1.pid = d.id
+	JOIN feed f ON f.feedcode = d1.feedcode 
+	AND f.pastureid = d.pastureid 
+WHERE
+	DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = DATE_FORMAT(subdate(now(),1) ,'%Y-%m-%d' )`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData", 
+	   "param": {
+	   "farmId": %s, 
+				 "method":"uploadadddata",
+				"rowCount": "1",
+	   "resultData":%s
+		}
+	   }`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, string(b))
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+// 撒料信息
+func dustingPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`SELECT
+	d.mydate dropDate,
+	d.projname tmrNo,
+	d.times loadShift,
+  d2.fbarid  penId,
+  b.bcode penName,
+	d2.cowcount cowCount,
+	d2.sort feedingNo,
+	d2.lweight expWeight,
+	d2.actualweightminus actualWeight,
+	d2.begintime startTime,
+	d2.intime endTime
+FROM
+	downloadedplan d
+	JOIN downloadplandtl2 d2 ON d2.pid = d.id
+	JOIN bar b ON b.id = d2.fbarid 
+WHERE
+	DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = DATE_FORMAT(subdate(now(),1) ,'%Y-%m-%d' )`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData", 
+		"param": {
+		"farmId": %s, 
+				  "method":"uploaddiliverdata",
+				  "rowCount": "1",
+		"resultData":%s
+		 }
+		}`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, string(b))
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+//设备心跳
+func deviceHeartbeat(c MQTT.Client, pubTopic string) {
+	pushStr := fmt.Sprintf(`{"data_collect_number":%s,"status":true,"model_type":"heartbeat"}`, setting.YynserverSetting.HeartBeat)
+
+	token := c.Publish(pubTopic, 2, false, pushStr)
+	fmt.Println("publish msg: ", pushStr, token.Error())
+	// token.Wait()
+	// go func() {
+	duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
+	duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
+	spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
+	// for {
+	device := cron.New()
+	device.AddFunc(spec1, func() {
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+	})
+	// }
+	device.Start()
+	// }()
+}
+
+// 准确率
+func equipmentAccuracyPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`select t.tname tname,1-abs(sum(d1.actualweightminus)- sum(d1.lweight))/sum(d1.lweight) rate ,d.mydate rateDate  from downloadedplan d join downloadplandtl1 d1 on d1.pid = d.id  join tmr t on t.datacaptureno = d.datacaptureno 
+	where DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = DATE_FORMAT(subdate(now(),1) ,'%Y-%m-%d' )
+	 group by d.datacaptureno`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData",
+		"param": {
+			"resultData": %s,
+			"farmId": %s,         
+			"method": "uploadrate",          
+			"rowCount": %d                  
+		}
+	}`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId, len(dataList))
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+// 完成重量
+func finishedWeightPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`select  sum(d1.actualweightminus) CompleteWeught,sum(d1.lweight) planWeight,d.mydate weightDate 
+	 from downloadedplan d join downloadplandtl1 d1 on d1.pid = d.id  join tmr t on t.datacaptureno = d.datacaptureno 
+	where DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = DATE_FORMAT(subdate(now(),1),'%Y-%m-%d' )`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData",
+		"param": {
+			"resultData": %s,
+			"farmId": %s,          
+			"method": "uploadweight",
+			"rowCount": "1"                 
+		}
+	}`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId)
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+// 完成车次
+func CompletedTrainNumberPush(c MQTT.Client, pubTopic string) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`select (select count(1) from downloadedplan  where  DATE_FORMAT(mydate ,'%Y-%m-%d' ) =  DATE_FORMAT(subdate(now(),1),'%Y-%m-%d' )  )  planCar, 
+	(select count(1) from downloadedplan  where  DATE_FORMAT(mydate ,'%Y-%m-%d' ) =  DATE_FORMAT(subdate(now(),1),'%Y-%m-%d' ) and iscompleted = 1 ) CompleteCar ,
+	DATE_FORMAT(subdate(now(),1),'%Y-%m-%d' ) carDate
+	`).Query().List()
+	if err != nil {
+		logs.Error("feedtempletPush-error-1:", err)
+		return
+	}
+
+	pushStr := `{
+		"apiId": "getKPTData",
+		"param": {
+			"resultData": %s,
+			"farmId": %s,       
+			"method": "uploadcarnumber",
+			"rowCount": "1"             
+		}
+	}`
+	if len(dataList) > 0 {
+		b, _ := json.Marshal(dataList)
+		pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId)
+		token := c.Publish(pubTopic, 2, false, pushStr)
+		fmt.Println("publish msg: ", pushStr, token.Error())
+		// token.Wait()
+		// time.Sleep(2 * time.Second)
+	}
+}
+
+func feedHeatwatch(client MQTT.Client, msg MQTT.Message) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	data := make(map[string]interface{})
+	json.Unmarshal(msg.Payload(), &data)
+	if _, ok := data["feedData"]; ok {
+
+		for _, item := range data["feedData"].([]map[string]interface{}) {
+			tx.SQL(` insert into feed(pastureid,feedcode,fname)values((SELECT column_default INTO pastureidTem FROM information_schema.COLUMNS 
+			WHERE table_name = 'recweight' AND table_schema = 'tmrwatch3' AND column_name = 'pastureid'),?,?)
+			 ON DUPLICATE KEY UPDATE feedcode = ?,fname = ? `, item["feedCode"], item["feedName"], item["feedCode"], item["feedName"]).Execute()
+		}
+	} else if _, ok := data["barData"]; ok {
+		for _, item := range data["barData"].([]map[string]interface{}) {
+			tx.SQL(` insert into bar(pastureid,bcode,bname)values((SELECT column_default INTO pastureidTem FROM information_schema.COLUMNS 
+				WHERE table_name = 'recweight' AND table_schema = 'tmrwatch3' AND column_name = 'pastureid'),?,?)
+				 ON DUPLICATE KEY UPDATE bcode = ?,bname = ? `, item["barCode"], item["barName"], item["barCode"], item["barName"]).Execute()
+		}
+	}
+}

+ 11 - 7
routers/api/scheduled.go

@@ -27,6 +27,7 @@ import (
 )
 
 func CronScheduled(ctx context.Context) {
+
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
 
@@ -63,8 +64,6 @@ func CronScheduled(ctx context.Context) {
 
 	})
 	c.Start()
-	//自动同步前天有进行中的任务
-	manualUdData(pastureinfo)
 
 	//消息提醒
 	duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
@@ -127,6 +126,9 @@ func CronScheduled(ctx context.Context) {
 		}
 	})
 	dayCron.Start()
+
+	// //圣牧自动同步前天有进行中的任务
+	// manualUdData(pastureinfo)
 }
 
 type ScheduledInfo struct {
@@ -357,7 +359,7 @@ func SynchronizeNow(c *gin.Context) {
 		return
 	}
 
-	dataList, err := tx.SQL(`select id from downloadedplan_log where date = date_format(?,'%Y-%m-%d') `, date).Query().List()
+	dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
 	if err != nil {
 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 		return
@@ -426,10 +428,10 @@ func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []strin
 						continue
 					}
 					var method string
-					if item.Datatype == 4 {
-						continue
-						// method = "uploadnewdiliverdata"
-					}
+					// if item.Datatype == 4 {
+					// 	continue
+					// method = "uploadnewdiliverdata"
+					// }
 					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
 				}
 				if len(idList) > 0 {
@@ -806,6 +808,7 @@ func UDPostPush1(data, method string) {
 	defer resp.Body.Close()
 	body, _ := ioutil.ReadAll(resp.Body)
 	fmt.Println("response Body:", string(body))
+	logging.Info("response Body:", string(body))
 }
 
 func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
@@ -988,6 +991,7 @@ func manualUdData(pastureinfo *udPastureInfo) {
 		tx := restful.Engine.NewSession()
 		defer tx.Close()
 		now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
+		// now := "2023-02-22"
 		dataList, err := tx.SQL(" select id  from downloadedplan where mydate = ? ", now).QueryString()
 		if err != nil {
 			logs.Error("manualUdData-error-1:", err)

+ 16 - 3
routers/api/spillage.go

@@ -2084,7 +2084,6 @@ func UpdateLpplandtlSort(c *gin.Context) {
 	upcount := int64(len(tmrLpplandList))
 	if oldsort > sort {
 		for _, lppland := range lpplandList {
-
 			if lppland.Sort >= sort && lppland.Tmrid != tmrid {
 				lppland.Sort += upcount
 				tmrLpplandList = append(tmrLpplandList, lppland)
@@ -2115,9 +2114,23 @@ func UpdateLpplandtlSort(c *gin.Context) {
 	}
 
 	tmrLpplandList = append(tmrLpplandList, updateLpplandList...)
-
+	// tmrLpplandMap := make(map[int64]bool)
+	// for _, item := range tmrLpplandList {
+	// 	tmrLpplandMap[item.Sort] = false
+	// }
+	for _, item := range tmrLpplandList {
+		exist := false
+		for _, item1 := range tmrLpplandList {
+			if item.Sort == item1.Sort && item.Id != item1.Id {
+				exist = true
+			}
+		}
+		if exist {
+			appG.Response(http.StatusOK, e.ERROR, "顺序调整有误,请重新调整!!!")
+			return
+		}
+	}
 	tx.Begin()
-	// _, err = tx.Table("lpplandtl1").Update(&tmrLpplandList)
 
 	var wg sync.WaitGroup
 	for _, lppland := range tmrLpplandList {

+ 60 - 39
routers/api/upload.go

@@ -14,6 +14,7 @@ import (
 	"net/http"
 	"os"
 	"path"
+	"path/filepath"
 	"strconv"
 	"strings"
 
@@ -792,53 +793,73 @@ func GetBarfeedremainExcel(c *gin.Context) {
 	_ = file.Write(c.Writer)
 }
 
-// func UploadFile1(c *gin.Context) {
-// 	appG := app.Gin{C: c}
-// 	businessid := c.PostForm("businessid")
-// 	file, err := appG.C.FormFile("file")
-// 	if err != nil {
-// 		logs.Error(err)
-// 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
-// 		return
-// 	}
+func UploadFile1(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pid := c.PostForm("pid")
+	sort := c.PostForm("sort")
+	isStart := c.PostForm("isStart")
 
-// 	tx := restful.Engine.NewSession()
-// 	defer tx.Close()
+	file, err := appG.C.FormFile("file")
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
 
-// 	fileInfoList, err := tx.SQL(` select path from file  where businessid = ? `, businessid).Query().List()
-// 	if err != nil {
-// 		logs.Error(err)
-// 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
-// 		return
-// 	}
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
 
-// 	if len(fileInfoList) > 0 {
-// 		filepath := ""
-// 		for _, fileinfo := range fileInfoList {
-// 			filepath = fileinfo["path"].(string)
-// 		}
-// 		os.Remove(filepath)
+	fileInfoList, err := tx.SQL(` select startpicture,endpicture from downloadplandtl1_exec  where pid  = ? and sort = ?  `, pid, sort).Query().List()
+	if err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
 
-// 	}
+	if len(fileInfoList) > 0 {
+		filepath := ""
+		for _, fileinfo := range fileInfoList {
+			if isStart == "1" {
+				if _, ok := fileinfo["startpicture"]; ok {
+					filepath = fileinfo["startpicture"].(string)
+				}
+			} else {
+				if _, ok := fileinfo["endpicture"]; ok {
+					filepath = fileinfo["endpicture"].(string)
+				}
+			}
 
-// 	basePath := "./"
-// 	filename := basePath + filepath.Base(file.Filename)
-// 	if err := appG.C.SaveUploadedFile(file, filename); err != nil {
-// 		logs.Error(err)
-// 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
-// 		return
-// 	}
+		}
+		os.Remove(filepath)
+	}
 
-// 	_, err = tx.SQL(` insert into file(filename,path,uploaddate,businessid)values(?,?,now(),?)  ON DUPLICATE KEY UPDATE  filename = ? ,path = ?,uploaddate = now() `, file.Filename, filename, businessid, file.Filename, filename).Execute()
-// 	if err != nil {
-// 		logs.Error(err)
-// 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
-// 		return
-// 	}
+	basePath := "uploads/image/"
+	filename := basePath + filepath.Base(file.Filename)
+	if err := appG.C.SaveUploadedFile(file, filename); err != nil {
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
 
-// 	c.String(http.StatusOK, fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
+	// filename = basePath + filepath.Base(file.Filename)
+	if isStart == "1" {
+		_, err = tx.SQL(` update downloadplandtl1_exec  set startpicture = ? where  pid  = ? and sort = ?  `, filename, pid, sort).Execute()
+		if err != nil {
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+	} else {
+		_, err = tx.SQL(` update downloadplandtl1_exec  set endpicture = ? where  pid  = ? and sort = ?  `, filename, pid, sort).Execute()
+		if err != nil {
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+	}
 
-// }
+	appG.Response(http.StatusOK, e.SUCCESS, fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
+}
 
 // func DownloadFile1(c *gin.Context) {
 // 	appG := app.Gin{C: c}

+ 342 - 0
routers/api/zc/zc.go

@@ -0,0 +1,342 @@
+package zc
+
+import (
+	"fmt"
+	"net/http"
+	"strconv"
+	"strings"
+	"time"
+
+	"../../../pkg/app"
+	"../../../pkg/e"
+	"../../../routers/restful"
+	"github.com/astaxie/beego/logs"
+	"github.com/gin-gonic/gin"
+	"github.com/robfig/cron"
+)
+
+func SyncZC() {
+
+	duetimecst, _ := time.ParseInLocation("15:04:05", "00:00:15", time.Local)
+	duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
+	spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
+
+	c := cron.New()
+	c.AddFunc(spec, func() {
+		updateTmrStatus()
+		// count1, err := restful.SqlServerEngine.Table("PFGL").QueryString()
+		// fmt.Println(err, count1)
+	})
+	c.Start()
+}
+
+// 同步配方到正诚
+func SyncSCJH(c *gin.Context) {
+	appG := app.Gin{C: c}
+	count1, err := restful.SqlServerEngine.Table("COMM").Where(` Status = 1 `).Count()
+	fmt.Println(err)
+	if count1 == 0 {
+		appG.Response(http.StatusOK, e.SUCCESS, "本都生产状态,禁止更新生产计划与配方!")
+		return
+	}
+
+	now := time.Now().Format("2006-01-02 15:04:05")
+	feedtempletList := GetFeedtempletList(time.Now().Format("2006-01-02"))
+	feedtempletMapList := make(map[string][]map[string]string)
+
+	for _, ft := range feedtempletList {
+		feedtempletMapList[ft["tname"]] = append(feedtempletMapList[ft["tname"]], ft)
+	}
+
+	// n := 0
+	restful.SqlServerEngine.SQL(`  delete from PFGL`).Execute()
+	for k, ftList := range feedtempletMapList {
+		// count, _ := restful.SqlServerEngine.Table("PFGL").Where(` PFMC = ? `, k).Count()
+
+		// n++
+		// if count > 0 {
+		// 	var wlmcstr []string
+		// 	var wlmc []interface{}
+		// 	wlmc = append(wlmc, now, ftList[0]["tcode"])
+		// 	var i, n int
+		// 	for _, ft := range ftList {
+		// 		if strings.Index(ft["fclass"], "小料") > -1 {
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d", 40+n+1))
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d", 40+n+1))
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d", 40+n+1))
+		// 			n++
+		// 		} else {
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d", i+1))
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d", i+1))
+		// 			wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d", i+1))
+		// 			i++
+		// 		}
+
+		// 		// wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d = ? ", i+1))
+		// 		// wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d = ? ", i+1))
+		// 		// wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d = ?", i+1))
+
+		// 		if _, ok := ft["fname"]; ok {
+		// 			wlmc = append(wlmc, ft["fname"])
+		// 		} else {
+		// 			wlmc = append(wlmc, "")
+		// 		}
+
+		// 		if _, ok := ft["fweight"]; ok {
+		// 			wlmc = append(wlmc, ft["fweight"])
+		// 		} else {
+		// 			wlmc = append(wlmc, "0")
+		// 		}
+		// 		wlmc = append(wlmc, i)
+		// 	}
+
+		// 	for i := len(ftList); i < 50; i++ {
+		// 		wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d = ? ", i+1))
+		// 		wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d = ? ", i+1))
+		// 		wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d = ?", i+1))
+		// 		wlmc = append(wlmc, "", "0", "0")
+		// 	}
+		// 	wlmc = append(wlmc, k)
+		// 	_, err := restful.SqlServerEngine.SQL(fmt.Sprintf("update PFGL set XGRQ = ?,PFBM = ? ,%s where PFMC = ? ", strings.Join(wlmcstr, ",")), wlmc...).Execute()
+		// 	fmt.Println(err, wlmc)
+		// } else {
+		// 	// PFBM := ""
+		var vlues, wlmcstr []string
+		var wlmc []interface{}
+		wlmc = append(wlmc, k, now, ftList[0]["tcode"])
+		vlues = append(vlues, "?", "?", "?")
+
+		var i, n int
+		for _, ft := range ftList {
+			if strings.Index(ft["fclass"], "小料") > -1 {
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d", 40+n+1))
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d", 40+n+1))
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d", 40+n+1))
+				n++
+			} else {
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLMC_%d", i+1))
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLZL_%d", i+1))
+				wlmcstr = append(wlmcstr, fmt.Sprintf("WLSX_%d", i+1))
+				i++
+			}
+			if _, ok := ft["fname"]; ok {
+				wlmc = append(wlmc, ft["fname"])
+			} else {
+				wlmc = append(wlmc, "")
+			}
+
+			if _, ok := ft["fweight"]; ok {
+				wlmc = append(wlmc, ft["fweight"])
+			} else {
+				wlmc = append(wlmc, "0")
+			}
+			if strings.Index(ft["fclass"], "小料") > -1 {
+				wlmc = append(wlmc, n)
+			} else {
+				wlmc = append(wlmc, i)
+			}
+
+			vlues = append(vlues, "?", "?", "?")
+		}
+		restful.SqlServerEngine.SQL(fmt.Sprintf("insert into PFGL(PFMC,XGRQ,PFBM,%s)values(%s)", strings.Join(wlmcstr, ","),
+			strings.Join(vlues, ",")), wlmc...).Execute()
+	}
+
+	downloadedplanList, err := restful.Engine.SQL(`  
+select t.* from 
+(select d.id,d.datacaptureno,d.tmrtname,d2.havebuttom,d.iscompleted,d2.fname,d2.lweight,d.lweight allweight,d.projname,d.sort,d2.sort barsort,d.templetname,d2.intime , 
+	round((d2.lweight/d.lweight*100),0)PFBL,f.ccount
+  from downloadedplan d 
+join downloadplandtl2 d2 on d2.pid = d.id
+join feedp f on f.barid = d2.fbarid 
+  where d.mydate = ? and d.enable = 1 and d.lpplantype= 0 and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0  
+UNION  all 
+select d.id, d.datacaptureno,d.tmrtname,d2.havebuttom,d.iscompleted,d2.fname,d2.lweight,d.lweight allweight,d.projname,d.sort,d2.sort barsort,d.templetname,d2.intime , 
+round((d2.lweight/d.lweight*100),0)PFBL  ,f.ccount
+from downloadedplan d  
+join downloadplandtl2 d2 on d2.pid = (select id from downloadedplan  where pid = d.pid  and mydate = d.mydate and  lpplantype= 2)
+join feedp f on f.barid = d2.fbarid 
+where d.mydate = ? and d.enable = 1 and d.lpplantype= 1  and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0    ) t 
+order by t.sort,t.barsort `, time.Now().Format("2006-01-02"), time.Now().Format("2006-01-02")).QueryString()
+	if err != nil {
+		appG.Response(http.StatusOK, e.SUCCESS, "计划查询失败!!!")
+		return
+	}
+
+	var list []string
+	//把推送过的计划id保存到列表中
+	zcpushList, _ := restful.Engine.SQL(`select * from zcpush where  date_format(date ,'%Y-%m-%d') = ?   `, time.Now().Format("2006-01-02")).QueryString()
+	for _, item := range zcpushList {
+		list = append(list, item["downloadedplan"])
+	}
+	if len(list) > 0 {
+		noWxz, _ := restful.SqlServerEngine.Table("SCJH").Where(`  Replace(WCZT,' ','')  != N'未选择' `).Count()
+		if noWxz == 0 {
+			restful.Engine.SQL(`delete from zcpush where  date_format(date ,'%Y-%m-%d') = ?   `, time.Now().Format("2006-01-02")).Execute()
+		} else if noWxz > 0 {
+			appG.Response(http.StatusOK, e.SUCCESS, "上传成功!")
+			return
+		}
+	} else {
+		restful.SqlServerEngine.SQL(` delete from SCJH  `).Execute()
+	}
+	restful.SqlServerEngine.SQL(` delete from SCJH  where Replace(WCZT,' ','')  = N'未选择' `).Execute()
+
+	num := make(map[string]int, 0)
+	tmrmap := make(map[string]string, 0)
+	for _, item := range downloadedplanList {
+		num[item["id"]] = 0
+	}
+
+	for _, item := range downloadedplanList {
+
+		exist := false
+		for _, id := range list {
+			if id == item["id"] {
+				exist = true
+				break
+			}
+		}
+		//如果已经推送过直接返回
+		if exist {
+			continue
+		}
+		//执行完成的直接返回
+		if item["iscompleted"] == "1" {
+			continue
+		}
+
+		if _, ok := tmrmap[item["datacaptureno"]]; ok {
+			//判断同tmr车是否已经有计划推送过
+			if tmrmap[item["datacaptureno"]] != item["id"] {
+				continue
+			}
+		} else {
+			// 首次推送
+			tmrmap[item["datacaptureno"]] = item["id"]
+			restful.Engine.SQL(` insert into zcpush(downloadedplan,sort,date,datacaptureno)values(?,?,now(),?)`, item["id"], item["sort"], item["datacaptureno"]).Execute()
+		}
+
+		num[item["id"]]++
+
+		restful.SqlServerEngine.SQL(`insert SCJH(SXCH,PFMC,LSMC,LSTS,PFBL,WCZT,TMRS)values(?,?,?,?,?,?,?)`, item["sort"], item["templetname"], item["fname"],
+			item["ccount"], item["PFBL"], "未完成", item["datacaptureno"]).Execute()
+
+	}
+
+	restful.SqlServerEngine.SQL(` update COMM set int_1 = 1 `).Execute()
+	appG.Response(http.StatusOK, e.SUCCESS, "上传成功!")
+}
+
+//获取当天精料配方
+func GetFeedtempletList(now string) []map[string]string {
+	feedtempletList, err := restful.Engine.SQL(`select fd.fclass,f.tname,(select tcode from feedtemplet where id = f.id) tcode,ft.fname,ft.fweight,ft.sort  from feedtempletdate f join ftdetail ft on ft.ftid = f.id  
+	join feed fd on fd.id = ft.fid   where fd.smtmrid >0  and date = ?   order by f.sort,ft.sort`, now).QueryString()
+	if err != nil {
+		logs.Error(err)
+	}
+	return feedtempletList
+}
+
+func updateTmrStatus() {
+	commList, err := restful.SqlServerEngine.Table("COMM").QueryString()
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+
+	comm := commList[0]
+	restful.Engine.SQL(` update zccomm set  int_2 = ?  where id = 1 `, comm["Int_2"]).Execute()
+	if comm["Status"] == "1" {
+		now := time.Now().Format("2006-01-02")
+		count, _ := restful.Engine.Table("downloadedplan").Where(` mydate = ?`, now).Where(`lpplantype in(0,1)`).Count()
+		// total, _ := restful.Engine.Table("downloadedplan").Where(` mydate = ?`, now).Where(`lpplantype in(0,1)`).Where(`havebutton = 1 `).Count()
+		havebuttontotal, _ := restful.Engine.Table("downloadedplan").Where(` mydate = ?`, now).Where(`lpplantype in(0,1,2)`).Where(`havebutton = 1 `).Count()
+		iscompletedtotal, _ := restful.Engine.Table("downloadedplan").Where(` mydate = ?`, now).Where(`lpplantype in(0,1,2)`).Where(`iscompleted = 1 `).Count()
+
+		if count == 0 {
+			restful.SqlServerEngine.SQL(` update COMM set  int_1 = ? `, 0).Execute()
+		} else if havebuttontotal != iscompletedtotal {
+			restful.SqlServerEngine.SQL(` update COMM set  int_1 = ? `, 2).Execute()
+		} else if havebuttontotal > 0 && iscompletedtotal > 0 {
+			restful.SqlServerEngine.SQL(` update COMM set int_1 = ? `, 4).Execute()
+		} else {
+			restful.SqlServerEngine.SQL(` update COMM set int_1 = ? `, 1).Execute()
+		}
+
+		downloadedplanList, err := restful.Engine.SQL(`
+	select t.* from
+	(select  d.id,d.havebutton,d.sort,datacaptureno   from downloadedplan d
+	  where d.mydate = ? and d.enable = 1 and d.lpplantype= 0 and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0  
+	UNION  all
+	select d.id,d.havebutton,d.sort,datacaptureno from downloadedplan d
+	where d.mydate = ? and d.enable = 1 and d.lpplantype= 1  and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0   ) t
+	order by t.sort `, now, now).QueryString()
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+
+		tmrMap := make(map[string][]map[string]string, 0)
+		for _, item := range downloadedplanList {
+			tmrMap[item["datacaptureno"]] = append(tmrMap[item["datacaptureno"]], item)
+		}
+
+		for datacaptureno, tmrList := range tmrMap {
+			zcpushList, _ := restful.Engine.SQL(`select * from zcpush where  date_format(date ,'%Y-%m-%d') = ? and datacaptureno = ? order by date desc limit 1  `, now, datacaptureno).QueryString()
+
+			zcpush := make(map[string]string)
+			if len(zcpushList) == 0 {
+				continue
+			} else {
+				zcpush = zcpushList[0]
+			}
+
+			data := make(map[string]string, 0)
+			exist := true
+			for _, item := range tmrList {
+				itemsort, _ := strconv.Atoi(item["sort"])
+				zcsort, _ := strconv.Atoi(zcpush["sort"])
+
+				//按顺序下推相同tmr如果还没有开始发料 就不更新下一个
+				if zcpush["downloadedplan"] == item["id"] && item["havebutton"] == "0" {
+					break
+				} else if zcsort < itemsort {
+					data = item
+					exist = false
+					break
+				}
+			}
+			if !exist {
+				restful.Engine.SQL(` insert into zcpush(downloadedplan,sort,date,datacaptureno)values(?,?,now(),?)`, data["id"], data["sort"], data["datacaptureno"]).Execute()
+
+				list, err := restful.Engine.SQL(`
+				select t.* from 
+				(select d.id,d.datacaptureno,d.tmrtname,d2.havebuttom,d.iscompleted,d2.fname,d2.lweight,d.lweight allweight,d.projname,d.sort,d2.sort barsort,d.templetname,d2.intime , 
+					round((d2.lweight/d.lweight*100),0)PFBL,f.ccount
+				  from downloadedplan d 
+				join downloadplandtl2 d2 on d2.pid = d.id
+				join feedp f on f.barid = d2.fbarid 
+				  where d.id = ? and d.enable = 1 and d.lpplantype= 0 and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0  
+				UNION  all 
+				select d.id, d.datacaptureno,d.tmrtname,d2.havebuttom,d.iscompleted,d2.fname,d2.lweight,d.lweight allweight,d.projname,d.sort,d2.sort barsort,d.templetname,d2.intime , 
+				round((d2.lweight/d.lweight*100),0)PFBL  ,f.ccount
+				from downloadedplan d  
+				join downloadplandtl2 d2 on d2.pid = (select id from downloadedplan  where pid = d.pid  and mydate = d.mydate and  lpplantype= 2)
+				join feedp f on f.barid = d2.fbarid 
+				where d.id = ? and d.enable = 1 and d.lpplantype= 1  and (select count(1) from downloadplandtl1  where pid = d.id  and type = 1) >0    ) t 
+				order by t.sort,t.barsort  `, data["id"], data["id"]).QueryString()
+				if err != nil {
+					logs.Error(err)
+					return
+				}
+
+				for _, arg := range list {
+					restful.SqlServerEngine.SQL(`insert SCJH(SXCH,PFMC,LSMC,LSTS,PFBL,WCZT,TMRS)values(?,?,?,?,?,?,?)`, arg["sort"], arg["templetname"], arg["fname"],
+						arg["ccount"], arg["PFBL"], "未完成", arg["datacaptureno"]).Execute()
+				}
+				restful.SqlServerEngine.SQL(` update COMM set int_1 = 1 `).Execute()
+			}
+		}
+	}
+}

+ 28 - 2
routers/restful/sql_utils.go

@@ -11,6 +11,7 @@ import (
 	"unsafe"
 
 	"../../pkg/setting"
+	_ "github.com/denisenkom/go-mssqldb"
 	_ "github.com/go-sql-driver/mysql"
 	"github.com/patrickmn/go-cache"
 	"github.com/tealeg/xlsx"
@@ -18,8 +19,9 @@ import (
 )
 
 var (
-	Engine       *xorm.Engine
-	Apisql_cache *cache.Cache
+	Engine          *xorm.Engine
+	SqlServerEngine *xorm.Engine
+	Apisql_cache    *cache.Cache
 )
 
 func SQLT() *xorm.Session {
@@ -49,6 +51,30 @@ func SQLInit(driverName, dataSourceName string, maxOpenConns, maxIdleConns int,
 		Apisql_cache = cache.New(600*time.Second, 10*time.Second)
 		SetCacheSql()
 	}
+
+	if SqlServerEngine == nil && setting.SQlserverSetting.Host != "" {
+		// setting.SQlserverSetting.Host = "server=192.168.1.152\\MYSQL;user id=sa;password=1;database=SysData;encrypt=disable"
+		sqlserverSourceName := fmt.Sprintf("server=%s;user id=%s;password=%s;database=%s;encrypt=disable", setting.SQlserverSetting.Host,
+			setting.SQlserverSetting.User, setting.SQlserverSetting.Password, setting.SQlserverSetting.Name)
+		var err error
+		fmt.Println(1, sqlserverSourceName)
+		SqlServerEngine, err = xorm.NewEngine("mssql", sqlserverSourceName)
+		if err != nil {
+			fmt.Println(err, 3, sqlserverSourceName)
+			return err
+		}
+		if err = SqlServerEngine.Ping(); err != nil {
+			panic(err)
+		}
+		fmt.Println(2, sqlserverSourceName)
+		if showlog {
+			SqlServerEngine.ShowSQL(true)
+		}
+		SqlServerEngine.SetMaxIdleConns(maxIdleConns)
+		SqlServerEngine.SetMaxOpenConns(maxOpenConns)
+		// count1, err := SqlServerEngine.Table("PFGL").QueryString()
+		// fmt.Println(err, 4, count1)
+	}
 	return nil
 }
 

+ 7 - 3
routers/router.go

@@ -15,6 +15,7 @@ import (
 	"../routers/api"
 
 	"../routers/api/sap"
+	"../routers/api/zc"
 	"github.com/gin-contrib/gzip"
 	"github.com/gin-gonic/gin"
 	ginSwagger "github.com/swaggo/gin-swagger"
@@ -23,8 +24,11 @@ import (
 
 func InitRouter() *gin.Engine {
 	r := gin.New()
+	// api.InitMqttClient()
 	go api.CronScheduled(context.TODO())
 	// go sap.SyncSapFeed(context.TODO())
+	//正诚配方生产计划同步
+	// go zc.SyncZC()
 
 	r.Use(func(c *gin.Context) {
 		fmt.Println(c.Request.URL)
@@ -74,8 +78,6 @@ func InitRouter() *gin.Engine {
 
 	r.POST("/userwxopenid/binding", api.UserWXOpenIDBinding)
 
-	// r.POST("/SyncSapBar", sap.SyncSapBar)
-
 	apiV1 := r.Group("/authdata")
 	apiV1.Use(jwt.JWT()) // token 验证
 	{
@@ -221,6 +223,9 @@ func InitRouter() *gin.Engine {
 		//sap原料上传
 		apiV1.POST("/material/sap/upload", sap.MaterialOutbound)
 
+		apiV1.POST("/downloadplandtl1/image/upload", api.UploadFile1)
+
+		apiV1.POST("/syncSCJH", zc.SyncSCJH)
 	}
 
 	//不需要登录验证的接口
@@ -274,4 +279,3 @@ func Cors() gin.HandlerFunc {
 		// 处理请求
 		c.Next() //  处理请求
 	}
-}

File diff suppressed because it is too large
+ 287 - 40
shengji.sql


File diff suppressed because it is too large
+ 2 - 161
update.sql


BIN
uploads/image/abstract.png


BIN
uploads/image/default.jpg


Some files were not shown because too many files changed in this diff