Browse Source

tmr 数据同步,消息推送

bsj 2 years ago
parent
commit
d10520f7f9
100 changed files with 2439 additions and 172 deletions
  1. BIN
      KPTAdmin64.exe
  2. BIN
      KPTAdmin64.zip
  3. BIN
      __debug_bin.exe
  4. 5 0
      a.txt
  5. 9 6
      conf/app.ini
  6. BIN
      dist(10)/dist/favicon.ico
  7. 0 0
      dist(10)/dist/index.html
  8. 0 0
      dist(10)/dist/static/css/app.5e481942.css
  9. 0 0
      dist(10)/dist/static/css/chunk-elementUI.5dea96f6.css
  10. 0 0
      dist(10)/dist/static/css/chunk-libs.1664ae71.css
  11. BIN
      dist(10)/dist/static/fonts/element-icons.535877f5.woff
  12. BIN
      dist(10)/dist/static/fonts/element-icons.732389de.ttf
  13. BIN
      dist(10)/dist/static/img/404.a57b6f31.png
  14. BIN
      dist(10)/dist/static/img/404_cloud.0f4bc32b.png
  15. 28 0
      dist(10)/dist/static/img/iconfont.7d9f8392.svg
  16. BIN
      dist(10)/dist/static/img/logo.afed751a.png
  17. BIN
      dist(10)/dist/static/img/logo1.0121925c.png
  18. BIN
      dist(10)/dist/static/img/logo_u3.3c77f543.png
  19. BIN
      dist(10)/dist/static/img/nlogin-bg1.77301f56.jpg
  20. BIN
      dist(10)/dist/static/img/row-bg3.b3be7548.png
  21. BIN
      dist(10)/dist/static/img/topBg.69ecd1e1.png
  22. 0 0
      dist(10)/dist/static/js/app.c2cc0a93.js
  23. 0 0
      dist(10)/dist/static/js/chunk-52ecc0ac.98e5f964.js
  24. 0 0
      dist(10)/dist/static/js/chunk-5c4dc4a9.eb511b2a.js
  25. 0 0
      dist(10)/dist/static/js/chunk-b702d234.0ec8f519.js
  26. 0 0
      dist(10)/dist/static/js/chunk-cf83d4b8.b3f7b120.js
  27. 0 0
      dist(10)/dist/static/js/chunk-elementUI.a8f15e3f.js
  28. 0 0
      dist(10)/dist/static/js/chunk-libs.9fe09263.js
  29. BIN
      dist(20).zip
  30. BIN
      dist.zip
  31. 0 0
      dist/index.html
  32. 0 0
      dist/static/css/app.04e9f829.css
  33. 0 0
      dist/static/css/app.81241f16.css
  34. BIN
      dist/static/img/nlogin-bg.e6414ecd.png
  35. BIN
      dist/static/img/nlogin-bg1.77301f56.jpg
  36. 0 0
      dist/static/js/app.4e24d177.js
  37. 0 0
      dist/static/js/app.54c20a1e.js
  38. 0 0
      dist/static/js/chunk-52ecc0ac.98e5f964.js
  39. 0 0
      dist/static/js/chunk-5c4dc4a9.eb511b2a.js
  40. 0 0
      dist/static/js/chunk-91b31c64.ea39e792.js
  41. 0 0
      dist/static/js/chunk-b702d234.0ec8f519.js
  42. 0 0
      dist/static/js/chunk-cf83d4b8.b3f7b120.js
  43. 0 0
      dist/static/js/chunk-libs.baae466d.js
  44. BIN
      dist1/favicon.ico
  45. 0 0
      dist1/index.html
  46. 0 0
      dist1/static/css/app.04e9f829.css
  47. 0 0
      dist1/static/css/chunk-elementUI.5dea96f6.css
  48. 0 0
      dist1/static/css/chunk-libs.1664ae71.css
  49. BIN
      dist1/static/fonts/element-icons.535877f5.woff
  50. BIN
      dist1/static/fonts/element-icons.732389de.ttf
  51. BIN
      dist1/static/img/404.a57b6f31.png
  52. BIN
      dist1/static/img/404_cloud.0f4bc32b.png
  53. 28 0
      dist1/static/img/iconfont.7d9f8392.svg
  54. BIN
      dist1/static/img/logo.afed751a.png
  55. BIN
      dist1/static/img/logo1.0121925c.png
  56. BIN
      dist1/static/img/logo_u3.3c77f543.png
  57. BIN
      dist1/static/img/nlogin-bg1.77301f56.jpg
  58. BIN
      dist1/static/img/row-bg3.b3be7548.png
  59. BIN
      dist1/static/img/topBg.69ecd1e1.png
  60. 0 0
      dist1/static/js/app.4e24d177.js
  61. 0 0
      dist1/static/js/chunk-52ecc0ac.98e5f964.js
  62. 0 0
      dist1/static/js/chunk-5c4dc4a9.eb511b2a.js
  63. 0 0
      dist1/static/js/chunk-b702d234.0ec8f519.js
  64. 0 0
      dist1/static/js/chunk-cf83d4b8.b3f7b120.js
  65. 0 0
      dist1/static/js/chunk-elementUI.a8f15e3f.js
  66. 0 0
      dist1/static/js/chunk-libs.baae466d.js
  67. BIN
      dist2/favicon.ico
  68. 0 0
      dist2/index.html
  69. 0 0
      dist2/static/css/app.2bb19a25.css
  70. 0 0
      dist2/static/css/chunk-elementUI.5dea96f6.css
  71. 0 0
      dist2/static/css/chunk-libs.1664ae71.css
  72. BIN
      dist2/static/fonts/element-icons.535877f5.woff
  73. BIN
      dist2/static/fonts/element-icons.732389de.ttf
  74. BIN
      dist2/static/img/404.a57b6f31.png
  75. BIN
      dist2/static/img/404_cloud.0f4bc32b.png
  76. 28 0
      dist2/static/img/iconfont.7d9f8392.svg
  77. BIN
      dist2/static/img/logo.afed751a.png
  78. BIN
      dist2/static/img/logo1.0121925c.png
  79. BIN
      dist2/static/img/logo_u3.3c77f543.png
  80. BIN
      dist2/static/img/nlogin-bg1.77301f56.jpg
  81. BIN
      dist2/static/img/row-bg3.b3be7548.png
  82. BIN
      dist2/static/img/topBg.69ecd1e1.png
  83. 0 0
      dist2/static/js/app.90fd41f8.js
  84. 0 0
      dist2/static/js/chunk-52ecc0ac.98e5f964.js
  85. 0 0
      dist2/static/js/chunk-5c4dc4a9.eb511b2a.js
  86. 0 0
      dist2/static/js/chunk-b702d234.0ec8f519.js
  87. 0 0
      dist2/static/js/chunk-cf83d4b8.b3f7b120.js
  88. 0 0
      dist2/static/js/chunk-elementUI.a8f15e3f.js
  89. 0 0
      dist2/static/js/chunk-libs.baae466d.js
  90. 1 0
      main.go
  91. 1 1
      models/models.go
  92. 709 6
      routers/api/db.go
  93. 907 0
      routers/api/scheduled.go
  94. 5 0
      routers/api/scheduled_test.go
  95. 637 121
      routers/api/spillage.go
  96. 29 20
      routers/api/udsync.go
  97. 40 16
      routers/api/user.go
  98. 1 1
      routers/restful/sql_utils.go
  99. 11 1
      routers/router.go
  100. BIN
      tmrgo

BIN
KPTAdmin64.exe


BIN
KPTAdmin64.zip


BIN
__debug_bin.exe


File diff suppressed because it is too large
+ 5 - 0
a.txt


+ 9 - 6
conf/app.ini

@@ -46,28 +46,31 @@ GRFDURL = http://120.48.30.31:88
 Type = mysql
 User = root
 #Password = root
-#Host = 127.0.0.1:3326
-Password = root
+Host = 127.0.0.1:3309
+Name = tmrwatch
+Password = 123456
 #Password = root
 #Password = kptzhu@163.com
 #Host = 192.168.1.50:3326
 #Password = root123456
 #Password = keep
-#Password = kepaiteng!QAZ
+
 #Password = kptzhu@163.com
 #Password = root
 #Password = kepaiteng!QAZ
 #Host = 47.92.52.73:3306
 #Host = 127.0.0.1:3306
 #Host = 210.16.186.252:3326
-#Host = 222.73.129.15:31306
+
 #Host = 210.16.186.252:3326
-Host = 127.0.0.1:3316
+#Host = 127.0.0.1:3309
 #Name = equipment
 #Name = eqdev
 #Name = eq0422
 #Name = tmrgo
-Name = tmrwatch2
+#Password = kepaiteng!QAZ
+#Host = 222.73.129.15:31306
+#Name = helanshan
 TablePrefix =
 
 ShowXormlog = false

BIN
dist(10)/dist/favicon.ico


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


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/css/app.5e481942.css


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/css/chunk-elementUI.5dea96f6.css


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/css/chunk-libs.1664ae71.css


BIN
dist(10)/dist/static/fonts/element-icons.535877f5.woff


BIN
dist(10)/dist/static/fonts/element-icons.732389de.ttf


BIN
dist(10)/dist/static/img/404.a57b6f31.png


BIN
dist(10)/dist/static/img/404_cloud.0f4bc32b.png


File diff suppressed because it is too large
+ 28 - 0
dist(10)/dist/static/img/iconfont.7d9f8392.svg


BIN
dist(10)/dist/static/img/logo.afed751a.png


BIN
dist(10)/dist/static/img/logo1.0121925c.png


BIN
dist(10)/dist/static/img/logo_u3.3c77f543.png


BIN
dist(10)/dist/static/img/nlogin-bg1.77301f56.jpg


BIN
dist(10)/dist/static/img/row-bg3.b3be7548.png


BIN
dist(10)/dist/static/img/topBg.69ecd1e1.png


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/js/app.c2cc0a93.js


+ 0 - 0
dist/static/js/chunk-52ecc0ac.235d809e.js → dist(10)/dist/static/js/chunk-52ecc0ac.98e5f964.js


+ 0 - 0
dist/static/js/chunk-5c4dc4a9.b70975ce.js → dist(10)/dist/static/js/chunk-5c4dc4a9.eb511b2a.js


+ 0 - 0
dist/static/js/chunk-b702d234.9b5e87a0.js → dist(10)/dist/static/js/chunk-b702d234.0ec8f519.js


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/js/chunk-cf83d4b8.b3f7b120.js


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/js/chunk-elementUI.a8f15e3f.js


File diff suppressed because it is too large
+ 0 - 0
dist(10)/dist/static/js/chunk-libs.9fe09263.js


BIN
dist(20).zip


BIN
dist.zip


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.04e9f829.css


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


BIN
dist/static/img/nlogin-bg.e6414ecd.png


BIN
dist/static/img/nlogin-bg1.77301f56.jpg


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


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


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-52ecc0ac.98e5f964.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-5c4dc4a9.eb511b2a.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-91b31c64.ea39e792.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-b702d234.0ec8f519.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-cf83d4b8.b3f7b120.js


File diff suppressed because it is too large
+ 0 - 0
dist/static/js/chunk-libs.baae466d.js


BIN
dist1/favicon.ico


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


File diff suppressed because it is too large
+ 0 - 0
dist1/static/css/app.04e9f829.css


File diff suppressed because it is too large
+ 0 - 0
dist1/static/css/chunk-elementUI.5dea96f6.css


File diff suppressed because it is too large
+ 0 - 0
dist1/static/css/chunk-libs.1664ae71.css


BIN
dist1/static/fonts/element-icons.535877f5.woff


BIN
dist1/static/fonts/element-icons.732389de.ttf


BIN
dist1/static/img/404.a57b6f31.png


BIN
dist1/static/img/404_cloud.0f4bc32b.png


File diff suppressed because it is too large
+ 28 - 0
dist1/static/img/iconfont.7d9f8392.svg


BIN
dist1/static/img/logo.afed751a.png


BIN
dist1/static/img/logo1.0121925c.png


BIN
dist1/static/img/logo_u3.3c77f543.png


BIN
dist1/static/img/nlogin-bg1.77301f56.jpg


BIN
dist1/static/img/row-bg3.b3be7548.png


BIN
dist1/static/img/topBg.69ecd1e1.png


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/app.4e24d177.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-52ecc0ac.98e5f964.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-5c4dc4a9.eb511b2a.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-b702d234.0ec8f519.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-cf83d4b8.b3f7b120.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-elementUI.a8f15e3f.js


File diff suppressed because it is too large
+ 0 - 0
dist1/static/js/chunk-libs.baae466d.js


BIN
dist2/favicon.ico


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


File diff suppressed because it is too large
+ 0 - 0
dist2/static/css/app.2bb19a25.css


File diff suppressed because it is too large
+ 0 - 0
dist2/static/css/chunk-elementUI.5dea96f6.css


File diff suppressed because it is too large
+ 0 - 0
dist2/static/css/chunk-libs.1664ae71.css


BIN
dist2/static/fonts/element-icons.535877f5.woff


BIN
dist2/static/fonts/element-icons.732389de.ttf


BIN
dist2/static/img/404.a57b6f31.png


BIN
dist2/static/img/404_cloud.0f4bc32b.png


File diff suppressed because it is too large
+ 28 - 0
dist2/static/img/iconfont.7d9f8392.svg


BIN
dist2/static/img/logo.afed751a.png


BIN
dist2/static/img/logo1.0121925c.png


BIN
dist2/static/img/logo_u3.3c77f543.png


BIN
dist2/static/img/nlogin-bg1.77301f56.jpg


BIN
dist2/static/img/row-bg3.b3be7548.png


BIN
dist2/static/img/topBg.69ecd1e1.png


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/app.90fd41f8.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-52ecc0ac.98e5f964.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-5c4dc4a9.eb511b2a.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-b702d234.0ec8f519.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-cf83d4b8.b3f7b120.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-elementUI.a8f15e3f.js


File diff suppressed because it is too large
+ 0 - 0
dist2/static/js/chunk-libs.baae466d.js


+ 1 - 0
main.go

@@ -38,6 +38,7 @@ func main() {
 		Name:        setting.ServerSetting.ServerName,  //服务显示名称
 		DisplayName: setting.ServerSetting.DisplayName, //服务名称
 		Description: setting.ServerSetting.Description, //服务描述
+		// Dependencies: []string{"TMRWatchDB"},
 	}
 	prg := &program{}
 	s, err := service.New(prg, svcConfig)

+ 1 - 1
models/models.go

@@ -30,7 +30,7 @@ func Setup() {
 		log.Fatalf("models.Setup err: %v", err)
 	}
 	Engine.SetConnMaxLifetime(time.Second * 30)
-	// Engine.ShowSQL(true)
+	Engine.ShowSQL(true)
 	if err = Engine.Ping(); err != nil {
 		logs.Error(err)
 		panic(err)

+ 709 - 6
routers/api/db.go

@@ -3087,14 +3087,13 @@ func UpdateFTdetail(c *gin.Context) {
 				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
 				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
 				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
-				),0) +fp.supplyweight
+				),0) +ifnull(fp.supplyweight,0)
 				WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
 
 			_, err = tx.SQL(`UPDATE fpdetail fpd
 		INNER JOIN feedp fp
 		ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
-		SET fpd.weight = fp.feedweight*fpd.tratio/100,
-		ptsrate=fp.supplyweight/(fp.feedweight)
+		SET fpd.weight = fp.feedweight*fpd.tratio/100
 		WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
 
 		} else {
@@ -3110,14 +3109,13 @@ func UpdateFTdetail(c *gin.Context) {
 					IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
 					IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
 					IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
-					),0) +fp.supplyweight
+					),0) +ifnull(fp.supplyweight,0)
 					WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
 
 			_, err = tx.SQL(`UPDATE fpdetail fpd
 				INNER JOIN feedp fp
 				ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
-				SET fpd.weight = fp.feedweight*fpd.tratio/100,
-				ptsrate=fp.supplyweight/(fp.feedweight)
+				SET fpd.weight = fp.feedweight*fpd.tratio/100
 				WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
 		}
 
@@ -3889,3 +3887,708 @@ func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{},
 	}
 	return nil
 }
+
+func FpdImportExcel(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	inputdata := ""
+	c.Request.ParseForm()
+
+	params := c.Request.Form
+	file, _, err := c.Request.FormFile("file")
+	if err != nil {
+		appG.Response(http.StatusOK, e.ERROR, err)
+		return
+	}
+	sqlnamestrs := params.Get("name")
+	sheetname := params.Get("sheetname")
+	pastureid := params.Get("pastureid")
+	// importParams := params.Get("importParams")
+	logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
+
+	// 必输项参数 (字符串格式 "field1,field2,field3")
+	requiredParams := params.Get("requiredParams")
+	// 日期参数
+	dateParams := params.Get("dateParams")
+	// 数字参数
+	numParams := params.Get("numParams")
+	//将字符串分割开
+	dateParamslist := strings.Split(dateParams, ",")
+	requiredParamslist := strings.Split(requiredParams, ",")
+	numParamslist := strings.Split(numParams, ",")
+	queryData := make([]interface{}, 0)
+	sqlslist := strings.Split(sqlnamestrs, ",")
+	xlsx1, err := excelize.OpenReader(file)
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	ok := 0
+	error := 0
+	isdone := true
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	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
+	 join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+	for _, item := range oldFpdList {
+		fmt.Println(item)
+	}
+	rows, _ := xlsx1.GetRows(sheetname)
+	// 限制10000条,多余的截取掉
+	if len(rows) > 10000 {
+		rows = rows[:10000]
+	}
+
+	for i, row := range rows {
+		if i > 0 {
+
+			entry := make(map[string]interface{})
+			outentry := make(map[string]interface{})
+			for j, colCell := range rows[0] {
+				for k, colCell1 := range row {
+					if j == k {
+						outentry[colCell] = colCell1
+						entry[colCell] = colCell1
+					}
+				}
+			}
+			inputdata = ""
+			a := ""
+			// fmt.Println(outentry, entry, "aaaaaaaaaaa")
+			//校验日期格式
+			for _, v := range dateParamslist {
+				if v == "" {
+					continue
+				}
+				if d, ok := outentry[strings.Trim(v, " ")]; ok {
+					dtime, err := TransfTime(d.(string))
+					if err != nil {
+						a = strings.Trim(v, " ")
+						break
+					}
+					outentry[strings.Trim(v, " ")] = dtime
+				}
+			}
+			if a != "" {
+				outentry["error_msg"] = a + " 格式错误"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+			a = ""
+			//校验必填格式
+			for _, v := range requiredParamslist {
+				if v == "" {
+					continue
+				}
+
+				if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
+					a = strings.Trim(v, " ")
+					break
+				}
+			}
+			if a != "" {
+				outentry["error_msg"] = a + " 未填或格式错误"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+			a = ""
+			//校验数字格式
+			for _, v := range numParamslist {
+				if v == "" {
+					continue
+				}
+				d, ok := outentry[strings.Trim(v, " ")]
+				if !ok || d == "" {
+					outentry[strings.Trim(v, " ")] = 0
+				} else {
+					var fl float64
+					switch d.(type) {
+					case string:
+						fl, err = strconv.ParseFloat(d.(string), 64)
+					}
+					if err != nil || fl < 0 {
+						a = strings.Trim(v, " ")
+						break
+					}
+				}
+			}
+			if a != "" {
+				outentry["error_msg"] = a + " 为数值类型且不可为负数"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+
+			errExist := false
+			for _, sqlnamestr := range sqlslist {
+				sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
+				paramslist := strings.Split(paramslists, ",")
+				if len(paramslist) > 0 {
+					s_params := make([]interface{}, 0)
+
+					for _, value := range paramslist {
+						if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+							if tempv, exists := c.Get("jwt_username"); exists {
+								s_params = append(s_params, tempv.(string))
+							} else {
+								s_params = append(s_params, "")
+							}
+						} else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
+							s_params = append(s_params, pastureid)
+
+						} else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
+							ids, err := setting.SnowIds.NextId()
+							if err != nil {
+								ids = time.Now().UnixNano()
+								logging.Info("create SnowIds err", err)
+							}
+							s_params = append(s_params, ids)
+						} else {
+							if outentry[strings.Trim(value, " ")] == nil {
+								s_params = append(s_params, "")
+							} else {
+
+								s_params = append(s_params, outentry[strings.Trim(value, " ")])
+							}
+
+						}
+					}
+
+					outentry["input"] = inputdata
+					returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
+
+					if err != nil {
+						errExist = true
+						// if tx != nil {
+						// 	tx.Rollback()
+						// }
+						// if tx != nil {
+						// 	tx.Close()
+						// }
+
+						msg := geterrmsg(err.Error())
+						outentry["error_msg"] = msg
+						error++
+						queryData = append(queryData, outentry)
+						isdone = true
+
+						break
+					} else {
+						if len(returnmsgmap1) > 0 {
+							if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
+								// if tx != nil {
+								// 	tx.Rollback()
+								// }
+								// if tx != nil {
+								// 	tx.Close()
+								// }
+								msg := geterrmsg(va.(string))
+								outentry["error_msg"] = msg
+								error++
+								queryData = append(queryData, outentry)
+								isdone = true
+								break
+							}
+						}
+						isdone = false
+					}
+				}
+			}
+			if !errExist {
+
+				dataexcel := make(map[string]interface{}, 0)
+				if _, ok := outentry["栏舍名称"]; ok {
+					dataexcel["barname"] = outentry["栏舍名称"]
+				}
+				if _, ok := outentry["实际牛头数"]; ok {
+					dataexcel["ccount"] = outentry["实际牛头数"]
+				}
+				if _, ok := outentry["系数(%)"]; ok {
+					dataexcel["ratio"] = outentry["系数(%)"]
+				}
+				if _, ok := outentry["配方模板"]; ok {
+					dataexcel["ftname"] = outentry["配方模板"]
+				}
+				if _, ok := outentry["补料配方"]; ok {
+					dataexcel["ptsfname"] = outentry["补料配方"]
+				}
+				if _, ok := outentry["第一班比例(%)"]; ok {
+					dataexcel["1"] = outentry["第一班比例(%)"]
+				}
+				if _, ok := outentry["第二班比例(%)"]; ok {
+					dataexcel["2"] = outentry["第二班比例(%)"]
+				}
+
+				if _, ok := outentry["第三班比例(%)"]; ok {
+					dataexcel["3"] = outentry["第三班比例(%)"]
+				}
+				if _, ok := outentry["第四班比例(%)"]; ok {
+					dataexcel["4"] = outentry["第四班比例(%)"]
+				}
+
+				exist, err := tx.SQL(` select id from  feedp where barname = ?  and pastureid = ?  `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist {
+					_, err := tx.SQL(` insert into  feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,?) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+				}
+
+				var feedpargs []interface{}
+				upFeedpSql := `update  feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01)  `
+				feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
+				if _, ok := dataexcel["ftname"]; ok {
+					feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
+					upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
+
+					upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail 
+				where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01)) `
+					feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
+				} else {
+					upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
+				}
+
+				if _, ok := dataexcel["ptsfname"]; ok {
+					feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
+					upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
+
+					upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail 
+				where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))`
+					feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
+				} else {
+					upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0  `
+				}
+				upFeedpSql += " where barname = ?  and pastureid = ?  "
+				feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
+				_, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+
+				exist1, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ?  `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist1 {
+					_, 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) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+
+					_, 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) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+
+					_, 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) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+
+					_, 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) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+				}
+
+				upFpdSql := ` update fpdetail set  tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail 
+				where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))) ,cowcount = ? ,
+				ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? )   where barname = ?
+				and pastureid = ? and times = ?`
+				var fpdargs1 []interface{}
+				fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
+				_, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				// upFpdSql := ` update fpdetail set  tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
+				// where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))) ,cowcount = ? ,
+				// ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? )   where barname = ?
+				//   and pastureid = ? and times = ?`
+				var fpdargs2 []interface{}
+				fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
+				_, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				var fpdargs3 []interface{}
+				fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
+				_, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				var fpdargs4 []interface{}
+				fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
+				_, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				// _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ?  and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
+
+				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()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				// oldFpdList, err := tx.SQL(` select  fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight  from fpdetail fpd
+				// join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
+				upFpdetailList := make([]*upFpdetail, 0)
+				for _, newfpd := range newList {
+					for _, oldfpd := range oldFpdList {
+						if oldfpd["id"].(int64) == newfpd["id"].(int64) {
+							var oldweight, newweight float64
+							if oldfpd["weight"] != nil {
+								oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
+							}
+							if newfpd["weight"] != nil {
+								newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
+							}
+							fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
+							upFpdetailList = append(upFpdetailList, &upFpdetail{
+								Old:     oldweight,
+								New:     newweight,
+								Times:   newfpd["times"].(int64),
+								Ptid:    newfpd["ptid"].(int64),
+								Fweight: fweight,
+								Id:      oldfpd["id"].(int64),
+							})
+							break
+						}
+					}
+				}
+
+				updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
+
+			}
+
+		}
+		if !isdone {
+			ok++
+			isdone = true
+		}
+	}
+	data := make(map[string]interface{})
+	data["result"] = queryData
+	data["success"] = ok
+	data["err_count"] = error
+	appG.Response(http.StatusOK, e.SUCCESS, data)
+}
+
+type upFpdetail struct {
+	Old     float64
+	New     float64
+	Times   int64
+	Ptid    int64
+	Fweight float64
+	Id      int64
+	// Ptsid string
+}
+
+func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	tx.Begin()
+	for _, data := range dataList {
+
+		// 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
+		// fpdDataList, err := tx.SQL(` select * from (
+		// 	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, data.Times).Query().List()
+		// if err != nil {
+		// 	tx.Rollback()
+		// 	logs.Error(err)
+		// }
+
+		// for _, fpd := range fpdDataList {
+
+		// ptid, err := strconv.ParseInt(fpd["ptid"].(string), 10, 64)
+		// if fpd["times"].(int64) == data.Times && (ptid == data.Ptid) {
+		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
+		}
+		// if weight < oldweight {
+		// 	if weight >= 0 {
+		// 		return
+		// 	}
+		// 	w = weight
+		// 	status = 0
+		// } else {
+		// 	if oldweight > 0 {
+		// 		return
+		// 	}
+		// 	w = weight
+		// 	status = 1
+		// }
+
+		// for _, lppland := range lpplandtl1List {
+		// 	lweight += lppland.Lweight
+		// }
+
+		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()
+		return err
+	}
+	return nil
+}
+
+func DeleteFTdetail(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	parammaps := fsion.Get("parammaps")
+	pastureid := parammaps.Get("pastureid").ValueStr()
+	ftid := parammaps.Get("ftid").ValueStr()
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	tx.Begin()
+	_, err := tx.SQL(`delete from ftdetail where ftid = ? and  pastureid = ? `, ftid, pastureid).Execute()
+	if err != nil {
+		tx.Rollback()
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+	if parammaps.Get("type").ValueStr() == "1" {
+
+		_, err := tx.SQL(`UPDATE feedp fp
+			set
+			fp.ftweight= IFNULL(IF(
+			(SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
+			),0),fp.feedweight = IFNULL(IF(
+			(SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
+			IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
+			),0) +ifnull(fp.supplyweight,0)
+			WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+		// UPDATE fpdetail SET ptuse=0 ,weight = 0
+		_, err = tx.SQL(`
+		UPDATE fpdetail fpd
+		INNER JOIN feedp fp
+		ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
+		SET fpd.weight = fp.feedweight*fpd.tratio/100,
+		ptuse= 0
+		WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+
+	} else {
+		_, err := tx.SQL(`UPDATE feedp fp
+				SET
+				fp.supplyweight= IFNULL(IF(
+				(SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
+				),0),fp.feedweight = IFNULL(IF(
+				(SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
+				IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
+				),0) + ifnull(fp.supplyweight,0)
+				WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+		// ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
+		_, err = tx.SQL(`
+			UPDATE fpdetail fpd
+			INNER JOIN feedp fp
+			ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
+			SET fpd.weight = fp.feedweight*fpd.tratio/100,
+			ptsrate = 0
+			WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error(err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			return
+		}
+	}
+	_, err = tx.SQL(` update lpplandtl1 set lweight = 0  where lppid in(select id  from  lpplan where ftid  = ? and pastureid = ? )`, ftid, pastureid).Execute()
+	if err != nil {
+		tx.Rollback()
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+	err = tx.Commit()
+	if err != nil {
+		tx.Rollback()
+		logs.Error(err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		return
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}

+ 907 - 0
routers/api/scheduled.go

@@ -0,0 +1,907 @@
+package api
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"log"
+	"net/http"
+	"os"
+	"reflect"
+	"strconv"
+	"strings"
+	"time"
+
+	"../../pkg/app"
+	"../../pkg/e"
+	"../../pkg/logging"
+	"../../pkg/setting"
+	"../../routers/restful"
+	"github.com/Anderson-Lu/gofasion/gofasion"
+	"github.com/astaxie/beego/logs"
+	"github.com/gin-gonic/gin"
+	"github.com/robfig/cron"
+	"github.com/xormplus/xorm"
+)
+
+func CronScheduled(ctx context.Context) {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	pastureinfo := new(udPastureInfo)
+	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS 
+	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+
+	duetimecst, _ := time.ParseInLocation("15:04:05", "00:01:00", 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() {
+		tx1 := restful.Engine.NewSession()
+		defer tx1.Close()
+		exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
+		if err != nil {
+			logs.Error("CronScheduled-error-1:", err)
+			return
+		}
+
+		fmt.Println(exist)
+		if exist {
+			_, err := tx.SQL(`update notice set status = 0  where content =  ? `, "downloadedplan_log").Execute()
+			if err != nil {
+				logs.Error("CronScheduled-error-2:", err)
+				return
+			}
+			Scheduled(ctx, tx1, pastureinfo)
+		}
+
+	})
+	c.Start()
+
+	// duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:01", time.Local)
+	// duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
+	// spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
+
+	// downloadplandtl1 := cron.New()
+	// downloadplandtl1.AddFunc(spec1, func() {
+	// 	tx2 := restful.Engine.NewSession()
+	// 	defer tx2.Close()
+
+	// 	exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
+	// 	if err != nil {
+	// 		logs.Error("CronScheduled-error-4:", err)
+	// 		return
+	// 	}
+	// 	fmt.Println(exist)
+	// 	if exist {
+	// 		_, err := tx2.SQL(`update notice set status = 0  where content =  ? `, "downloadplandtl1").Execute()
+	// 		if err != nil {
+	// 			logs.Error("CronScheduled-error-5:", err)
+	// 			return
+	// 		}
+
+	// 		dataList, err := tx2.SQL("select * from downloadplandtl1_log  where date = date_format(now(),'%Y-%m-%d') ").Query().List()
+	// 		if err != nil {
+	// 			logs.Error("CronScheduled-error-6:", err)
+	// 			return
+	// 		}
+	// 		plandtl1SlIdMap := make(map[string][]int64, 0)
+	// 		// plandtl1HlIdMap := make(map[string][]string, 0)
+	// 		for _, data := range dataList {
+	// 			if data["type"].(int64) == 0 && data["plandtl1"] != nil {
+	// 				plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
+	// 			}
+
+	// 		}
+
+	// 		for _, data := range dataList {
+	// 			if data["type"].(int64) == 0 {
+	// 				plandtl1List, err := tx2.SQL(`select d1.fname,d.tmrtname,d1.intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
+	// 				if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy  from
+	// 				downloadplandtl1 d1
+	// 				join downloadedplan d on d.id = d1.pid
+	// 				where d1.pid = ?  and d1.sort = ?  and  d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
+	// 					data["planid"], data["sort"], data["pastureid"]).Query().List()
+
+	// 				if err != nil {
+	// 					logs.Error("CronScheduled-error-7:", err)
+	// 					return
+	// 				}
+	// 				idexist := false
+	// 				for _, plandtl1 := range plandtl1List {
+	// 					//防止同顺序饲料多次推送
+	// 					for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
+	// 						if plandtl1Id == plandtl1["id"].(int64) {
+	// 							idexist = true
+	// 							break
+	// 						}
+
+	// 					}
+	// 					if idexist {
+	// 						continue
+	// 					}
+
+	// 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
+	// 					if plandtl1["feedallowratio"].(float64) < errorvalue {
+	// 						// if plandtl1["feedallowratio"].(float64) < plandtl1["errorvalue"].(float64) {
+	// 						fmt.Println(plandtl1, "推送")
+	// 						target := []string{"13916925233"}
+	// 						var sendList []interface{}
+	// 						sendStr := fmt.Sprintf("tmr名称:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
+	// 							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+	// 						// content = append(content, "混料", plandtl1["begintime"], "kpt", sendStr, "搅拌预警")
+
+	// 						sendMap1 := make(map[string]interface{}, 0)
+	// 						sendMap1["value"] = "搅拌"
+	// 						sendMap1["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap1)
+	// 						sendMap2 := make(map[string]interface{}, 0)
+	// 						sendMap2["value"] = plandtl1["intime"]
+	// 						sendMap2["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap2)
+	// 						sendMap3 := make(map[string]interface{}, 0)
+	// 						sendMap3["value"] = "kpt"
+	// 						sendMap3["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap3)
+	// 						sendMap4 := make(map[string]interface{}, 0)
+	// 						sendMap4["value"] = sendStr
+	// 						sendMap4["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap4)
+
+	// 						sendMap5 := make(map[string]interface{}, 0)
+	// 						sendMap5["value"] = "搅拌预警"
+	// 						sendMap5["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap5)
+	// 						wxPush(target, sendList)
+	// 					}
+
+	// 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
+	// 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ?  and type =  0 ", plandtl1["id"], data["id"]).Execute()
+	// 					if err != nil {
+	// 						logs.Error("CronScheduled-error-8:", err)
+	// 						return
+	// 					}
+
+	// 				}
+	// 			} else {
+	// 				plandtl1List, err := tx2.SQL(`select  d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,d2.intime,d2.actualweightminus,d2.lweight,
+	// 				if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
+	// 			 from 	downloadplandtl2 d2
+	// 				join downloadedplan d on d.id = d2.pid
+	// 				where d2.pid = ?  and d2.sort = ?  and  d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
+	// 					data["planid"], data["sort"], data["pastureid"]).Query().List()
+	// 				// Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
+	// 				if err != nil {
+	// 					logs.Error("CronScheduled-error-7:", err)
+	// 					return
+	// 				}
+	// 				for _, plandtl1 := range plandtl1List {
+	// 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
+	// 					if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
+	// 						fmt.Println(plandtl1, "推送")
+	// 						target := []string{"13916925233"}
+	// 						// var content []interface{}
+
+	// 						var sendList []interface{}
+	// 						sendStr := fmt.Sprintf("tmr名称:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率:%v",
+	// 							plandtl1["tmrtname"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+	// 						sendMap1 := make(map[string]interface{}, 0)
+	// 						sendMap1["value"] = "撒料"
+	// 						sendMap1["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap1)
+	// 						sendMap2 := make(map[string]interface{}, 0)
+	// 						sendMap2["value"] = plandtl1["intime"]
+	// 						sendMap2["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap2)
+	// 						sendMap3 := make(map[string]interface{}, 0)
+	// 						sendMap3["value"] = "kpt"
+	// 						sendMap3["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap3)
+	// 						sendMap4 := make(map[string]interface{}, 0)
+	// 						sendMap4["value"] = sendStr
+	// 						sendMap4["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap4)
+
+	// 						sendMap5 := make(map[string]interface{}, 0)
+	// 						sendMap5["value"] = "撒料预警"
+	// 						sendMap5["color"] = "#173177"
+	// 						sendList = append(sendList, sendMap5)
+
+	// 						wxPush(target, sendList)
+	// 					}
+
+	// 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
+	// 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
+	// 					if err != nil {
+	// 						logs.Error("CronScheduled-error-8:", err)
+	// 						return
+	// 					}
+
+	// 				}
+	// 			}
+	// 		}
+	// 	}
+	// })
+
+	// downloadplandtl1.Start()
+}
+
+type ScheduledInfo struct {
+	Id      int64  `xorm:"id"`
+	Sname   string `xorm:"sname"`
+	Action  int64  `xorm:"action"`
+	Childid int64  `xorm:"childid"`
+	Times   string `xorm:"times"`
+	Enable  string `xorm:"enable"`
+}
+type ScheduledUpInfo struct {
+	Id         int64  `xorm:"id"`
+	Company    string `xorm:"company"`
+	Addres     string `xorm:"addres"`
+	Datatype   int64  `xorm:"datatype"`
+	Package    string `xorm:"Package"`
+	Datasql    string `xorm:"datasql"`
+	Automatic  int64  `xorm:"automatic"`
+	Manual     int64  `xorm:"manual"`
+	Targetdata string `xorm:"targetdata"`
+}
+
+type ScheduledDownInfo struct {
+	Id          int64  `xorm:"id"`
+	Datatype    int64  `xorm:"datatype"`
+	Addres      string `xorm:"addres"`
+	Adressparam string `xorm:"adressparam"`
+	Targetdata  string `xorm:"targetdata"`
+	Manual      int64  `xorm:"manual"`
+	Methods     string `xorm:"methods"`
+}
+
+type ScheduledDownChildInfo struct {
+	Id        int64  `xorm:"id"`
+	Parentid  int64  `xorm:"parentid"`
+	Fieldname string `xorm:"fieldname"`
+	Checksql  string `xorm:"checksql"`
+	Dosql     string `xorm:"dosql"`
+}
+
+func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
+	times := new(ScheduledInfo)
+	err := tx.SQL("  select  times  from  scheduled  where  action = 0 group by times").GetFirst(times).Error
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+	if times.Times == "0" {
+		downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') `).Query().List()
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+		ids := []string{}
+		for _, item := range downloadedplanLogList {
+			ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
+		}
+		fmt.Println(ids, time.Now())
+		err = UpdatePush(ctx, tx, true, ids, pastureinfo, "")
+		if err != nil {
+			return
+		}
+
+	} else if times.Times == "1" {
+		downloadedplanLogList, err := tx.SQL(` select times from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') and status = 0  group by times`).Query().List()
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+		for _, item := range downloadedplanLogList {
+			count, err := tx.SQL(`  select  count(1)  from  downloadedplan  where  pastureid = ? and mydate = date_format(now(),'%Y-%m-%d') 
+			and iscompleted = 0 and times  = ? and enable = 1 `,
+				pastureinfo.Pastureid, item["times"]).Count()
+			if err != nil {
+				logs.Error(err)
+				return
+			}
+			if count == 0 {
+				//推送
+				downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d')
+				 and times  = ? `, item["times"]).Query().List()
+				if err != nil {
+					logs.Error(err)
+					return
+				}
+				ids := []string{}
+				for _, item := range downloadedplanLogList {
+					ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
+				}
+				err = UpdatePush(ctx, tx, true, ids, pastureinfo, "")
+				if err != nil {
+					return
+				}
+			}
+		}
+
+	} else if times.Times == "2" {
+		count, err := tx.SQL("  select  count(1)  from  downloadedplan  where  pastureid = ? and mydate = date_format(now(),'%Y-%m-%d') and iscompleted = 0  and enable = 1 ",
+			pastureinfo.Pastureid).Count()
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+		if count == 0 {
+			//推送
+			downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') `).Query().List()
+			if err != nil {
+				logs.Error(err)
+				return
+			}
+			ids := []string{}
+			for _, item := range downloadedplanLogList {
+				ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
+			}
+			err = UpdatePush(ctx, tx, true, ids, pastureinfo, "")
+			if err != nil {
+				return
+			}
+		}
+	}
+
+}
+
+func UpdateScheduledStatus(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+
+	idList := fsion.Get("id").Array()
+	automatic := fsion.Get("automatic").ValueStr()
+	manual := fsion.Get("manual").ValueStr()
+	company := fsion.Get("company").ValueStr()
+	//type 0 上传,1 下载
+	typee := fsion.Get("type").ValueStr()
+
+	ids := []string{}
+	for _, item := range idList {
+		ids = append(ids, item.ValueStr())
+	}
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	tx.Begin()
+
+	sqlstr := ""
+	sqlstr1 := ""
+	// var args []interface{}
+	if typee == "0" {
+		if len(ids) > 0 {
+			sqlstr = `update scheduled s  join scheduled_up su on su.id = s.childid set `
+			sqlstr1 = `update scheduled s  join scheduled_up su on su.id = s.childid set `
+			if automatic != "" {
+				sqlstr += " su.automatic = 1 "
+				sqlstr1 += " su.automatic = 0 "
+			} else if manual != "" {
+				sqlstr += " su.manual = 1 "
+				sqlstr1 += " su.manual = 0 "
+			}
+			id := strings.Join(ids, ",")
+			sqlstr += fmt.Sprintf(" where s.id in (%s)  and s.action = 0 and su.company = '%s' ", id, company)
+			sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
+		} else {
+			sqlstr = `update scheduled s  join scheduled_up su on su.id = s.childid set `
+			if automatic != "" {
+				sqlstr += " su.automatic = 0 "
+			} else if manual != "" {
+				sqlstr += " su.manual = 0 "
+			}
+			sqlstr += fmt.Sprintf(" where  s.action = 0 and su.company = '%s' ", company)
+		}
+	} else {
+		if len(ids) > 0 {
+			sqlstr = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
+			sqlstr1 = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
+			sqlstr += " sd.manual = 1 "
+			sqlstr1 += " sd.manual = 0 "
+
+			id := strings.Join(ids, ",")
+			sqlstr += fmt.Sprintf(" where s.id in (%s)  and s.action = 1 and sd.company = '%s' ", id, company)
+			sqlstr1 += fmt.Sprintf(" where s.id not in (%s)  and s.action = 1  and sd.company = '%s' ", id, company)
+		} else {
+			sqlstr = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
+			sqlstr += " sd.manual = 0 "
+			sqlstr += fmt.Sprintf(" where  s.action = 1 and sd.company = '%s' ", company)
+		}
+	}
+
+	_, err := tx.SQL(sqlstr).Execute()
+	if err != nil {
+		log.Println("UpdateScheduledStatus-error-1: ", err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		tx.Rollback()
+	}
+	if len(sqlstr1) > 0 {
+		_, err = tx.SQL(sqlstr1).Execute()
+		if err != nil {
+			log.Println("UpdateScheduledStatus-error-2: ", err)
+			appG.Response(http.StatusInternalServerError, e.ERROR, err)
+			tx.Rollback()
+		}
+	}
+
+	err = tx.Commit()
+	if err != nil {
+		log.Println("UpdateScheduledStatus-error-3: ", err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, err)
+		tx.Rollback()
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}
+
+func SynchronizeNow(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	company := fsion.Get("company").ValueStr()
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	pastureinfo := new(udPastureInfo)
+	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS 
+	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+
+	dataList, err := tx.SQL(`select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+	var idList []string
+	for _, data := range dataList {
+		idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
+	}
+
+	err = UpdatePush(c, tx, false, idList, pastureinfo, company)
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+
+	UpdateDown(c, tx, nil, pastureinfo, company)
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}
+
+func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company string) error {
+	upList := make([]*ScheduledUpInfo, 0)
+	up := tx.Table("scheduled_up")
+	if company != "" {
+		up.Where("company = ? ", company)
+	}
+	if auto {
+		up.Where("automatic = 1")
+	} else {
+		up.Where("manual = 1")
+	}
+	err := up.Find(&upList)
+	if err != nil {
+		log.Println("UpdataPush-error-1: ", err)
+		return err
+	}
+
+	for _, item := range upList {
+		if item.Datasql != "" {
+			if item.Datatype == 3 || item.Datatype == 4 {
+				targetdataList := strings.Split(item.Targetdata, ",")
+				var args []interface{}
+				for _, targetdata := range targetdataList {
+					if targetdata == "pastureid" {
+						args = append(args, pastureinfo.Pastureid)
+					} else if targetdata == "idlist" {
+						// args = append(args, strings.Join(idList, ","))
+						item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
+					}
+				}
+
+				data, err := tx.SQL(item.Datasql, args...).Query().List()
+				if err != nil {
+					log.Println("UpdataPush-error-2: ", err)
+					return err
+				}
+				if len(data) > 0 {
+					databyte, err := json.Marshal(data)
+					if err != nil {
+						log.Println("UpdataPush-error-3: ", err)
+						return err
+					}
+					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)))
+				}
+				if len(idList) > 0 {
+					_, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1  where id in (%s)", strings.Join(idList, ","))).Execute()
+					if err != nil {
+						log.Println("UpdataPush-error-4: ", err)
+						return err
+					}
+				}
+			} else {
+				targetdataList := strings.Split(item.Targetdata, ",")
+				var args []interface{}
+				for _, targetdata := range targetdataList {
+					if targetdata == "pastureid" {
+						args = append(args, pastureinfo.Pastureid)
+					} else if targetdata == "idlist" {
+						// args = append(args, strings.Join(idList, ","))
+						item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
+					}
+				}
+
+				data, err := tx.SQL(item.Datasql, args...).Query().List()
+				if err != nil {
+					log.Println("UpdataPush-error-5: ", err)
+					return err
+				}
+				if len(data) > 0 {
+					databyte, err := json.Marshal(data)
+					if err != nil {
+						log.Println("UpdataPush-error-6: ", err)
+						return err
+					}
+					// d, err := OpenFile("a.txt")
+					// d.WriteString()
+					// UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
+					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)))
+				}
+			}
+		}
+	}
+
+	return nil
+}
+
+// OpenFile 判断文件是否存在  存在则OpenFile 不存在则Create
+func OpenFile(filename string) (*os.File, error) {
+	if _, err := os.Stat(filename); os.IsNotExist(err) {
+		fmt.Println("文件不存在")
+		return os.Create(filename) //创建文件
+	}
+	fmt.Println("文件存在")
+	return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
+}
+
+func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
+
+	downList := make([]*ScheduledDownInfo, 0)
+	down := tx.Table("scheduled_down")
+	if company != "" {
+		down.Where("company = ? ", company)
+	}
+
+	down.Where("manual = 1")
+	err := down.Find(&downList)
+	if err != nil {
+		log.Println("UpdateDown-error-1: ", err)
+		return err
+	}
+
+	for _, item := range downList {
+		list := httpGetMC(item.Addres, item.Targetdata)
+		if item.Methods != "" {
+			s := ScheduledDown{}
+			value := reflect.ValueOf(&s)
+			f := value.MethodByName(item.Methods)
+			f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
+
+			// value := reflect.ValueOf(&s)
+			// f := value.MethodByName("Ccaa")
+			// f.Call([]reflect.Value{reflect.ValueOf(list)})
+
+		} else {
+			childList := make([]*ScheduledDownChildInfo, 0)
+			child := tx.Table("scheduled_down")
+			child.Where("parentid = ? ", item.Id)
+			err = child.Find(&childList)
+			if err != nil {
+				log.Println("UpdateDown-error-2: ", err)
+				return err
+			}
+
+			if len(childList) > 0 {
+				tx.Begin()
+				for _, c := range childList {
+					fieldnames := strings.Split(c.Fieldname, ",")
+					for _, data := range list {
+						var args []interface{}
+						dataMap := data.(map[string]interface{})
+						for _, fieldname := range fieldnames {
+							args = append(args, dataMap[fieldname])
+						}
+						_, err = tx.SQL(c.Dosql, args...).Execute()
+						if err != nil {
+							tx.Rollback()
+							log.Println("UpdateDown-error-3: ", err)
+							return err
+						}
+					}
+				}
+				err := tx.Commit()
+				if err != nil {
+					tx.Rollback()
+					log.Println("UpdateDown-error-4: ", err)
+					return err
+				}
+			}
+		}
+
+	}
+	return nil
+}
+
+func httpGetMC(url, targetdata string) []interface{} {
+	// url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
+	res, err := http.Get(url)
+	if err != nil {
+		return nil
+	}
+	robots, err := ioutil.ReadAll(res.Body)
+	res.Body.Close()
+	if err != nil {
+		return nil
+	}
+	var data map[string][]interface{}
+	json.Unmarshal(robots, &data)
+	return data[targetdata]
+}
+
+type ScheduledDown struct {
+}
+
+func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	err := tx.Begin()
+	if err != nil {
+		tx.Rollback()
+		logs.Error("syncFeed-error-1:", err)
+		return
+	}
+	for _, f := range feedList {
+		feed := f.(map[string]interface{})
+
+		var feedcode, fname, fclass, fclassid, dry interface{}
+
+		if _, ok := feed["feedcode"]; ok {
+			feedcode = feed["feedcode"]
+		}
+		if _, ok := feed["feedname"]; ok {
+			fname = feed["feedname"]
+		}
+		if _, ok := feed["feedclass"]; ok {
+			fclass = feed["feedclass"]
+		}
+		if _, ok := feed["drymatter"]; ok {
+			dry = feed["drymatter"]
+		}
+
+		fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
+		if err != nil {
+			tx.Rollback()
+			logs.Error("syncFeed-error-2:", err)
+			return
+		}
+		if fclassExist {
+			fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeed-error-3:", err)
+				return
+			}
+			for _, fclassData := range fclassDataList {
+				fclassid = fclassData["id"]
+			}
+		} else {
+			ids, err := setting.SnowIds.NextId()
+			if err != nil {
+				ids = time.Now().UnixNano()
+				logging.Info("create SnowIds err", err)
+			}
+			_, err = tx.SQL("insert into feedclass(id,pastureid,fccode,fcname,bigfeedclassname,bigfeedclassid,sort)VALUES(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from feedclass f  where f.pastureid =? ))",
+				ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeed-error-4:", err)
+				return
+			}
+
+			fclassid = ids
+		}
+
+		ids, err := setting.SnowIds.NextId()
+		if err != nil {
+			ids = time.Now().UnixNano()
+			logging.Info("create SnowIds err", err)
+		}
+		insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?) 
+		ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
+		_, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error("syncFeed-error-5:", err)
+			return
+		}
+	}
+
+	err = tx.Commit()
+	if err != nil {
+		tx.Rollback()
+		logs.Error("syncFeed-error-6:", err)
+		return
+	}
+	return
+}
+
+func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	err := tx.Begin()
+	if err != nil {
+		logs.Error("syncFeedp-error-1:", err)
+		return err
+	}
+
+	for _, f := range feedpList {
+		feedp := f.(map[string]interface{})
+		var barName, barCode, feedtempletCode, barId interface{}
+		var ftId, tname interface{}
+		var cowCount interface{}
+		if _, ok := feedp["barname"]; ok {
+			barName = feedp["barname"]
+		}
+		if _, ok := feedp["barcode"]; ok {
+			barCode = feedp["barcode"]
+		}
+		if _, ok := feedp["cowcount"]; ok {
+			cowCount = feedp["cowcount"]
+		}
+		if _, ok := feedp["feedtempletcode"]; ok {
+			feedtempletCode = feedp["feedtempletCode"]
+		}
+
+		barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
+		if err != nil {
+			tx.Rollback()
+			logs.Error("syncFeedp-error-2:", err)
+			return err
+		}
+		if barCount > 0 {
+			barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeedp-error-3:", err)
+				return err
+			}
+			for _, barData := range barDataList {
+				barId = barData["id"]
+			}
+		} else {
+			barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeedp-error-4:", err)
+				return err
+			}
+			id, err := barReq.LastInsertId()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeedp-error-5:", err)
+				return err
+			}
+
+			barId = strconv.FormatInt(id, 10)
+		}
+
+		if feedtempletCode != "" {
+			feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
+			if err != nil {
+				tx.Rollback()
+				logs.Error("syncFeedp-error-6:", err)
+				return err
+			}
+			for _, feedtemplet := range feedtempletDataList {
+				ftId = feedtemplet
+				tname = feedtemplet
+			}
+		}
+
+		insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?) 
+		ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
+		_, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
+		if err != nil {
+			tx.Rollback()
+			logs.Error("syncFeedp-error-7:", err)
+			return err
+		}
+	}
+
+	err = tx.Commit()
+	if err != nil {
+		tx.Rollback()
+		logs.Error("syncFeedp-error-8:", err)
+		return err
+	}
+
+	return nil
+}
+
+func wxPush(target []string, content []interface{}) {
+	url := "http://tmrwatch.cn/notice/message"
+
+	dataStr := `{
+		"sys_name": "tmrwatch",
+		"remind_type": "1",
+		"template_id": "BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
+		"target": %s,
+		"miniprogram": {
+			"appid": "xiaochengxuappid12345",
+			"pagepath": "index?foo=bar"
+		},
+		"keys": [
+			"first",
+			"keyword1",
+			"keyword2",
+			"keyword3",
+			"remark"
+		],
+		"content":%s
+	}`
+
+	targetStr, _ := json.Marshal(target)
+	contentStr, _ := json.Marshal(content)
+	dataStr = fmt.Sprintf(dataStr, string(targetStr), string(contentStr))
+	var jsonStr = []byte(dataStr)
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
+
+	req.Header.Set("Content-Type", "application/json")
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		panic(err)
+	}
+
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println("response Body:", string(body))
+}
+
+func UDPostPush1(data string) {
+	url := "https://wdc.unidairy.cn/copartner_uploads/"
+	// 超时时间:5秒
+	fmt.Println(data)
+	var jsonStr = []byte(data)
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
+
+	req.Header.Set("Content-Type", "application/json")
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		panic(err)
+	}
+
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println("response Body:", string(body))
+}

+ 5 - 0
routers/api/scheduled_test.go

@@ -0,0 +1,5 @@
+package api_test
+
+func TestAdd(t *testing.T) {
+
+}

+ 637 - 121
routers/api/spillage.go

@@ -7,6 +7,7 @@ import (
 	"io/ioutil"
 	"log"
 	"net/http"
+	"sort"
 	"strconv"
 	"strings"
 	"sync"
@@ -1414,6 +1415,208 @@ GROUP BY fpd.ptsid`
 	appG.Response(http.StatusOK, e.SUCCESS, data)
 }
 
+// func AddLpplandtl(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	parammaps := fsion.Get("parammaps")
+
+// 	tx := restful.Engine.NewSession()
+// 	defer tx.Close()
+
+// 	exist := false
+// 	var err error
+
+// 	lpplandList := make([]*lpplandtl1, 0)
+// 	err = tx.Table("lpplandtl1").Select("id,pastureid,sort,barid,tmrid").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
+// 		OrderBy("sort").Find(&lpplandList)
+// 	if err != nil {
+// 		log.Println("AddLpplandtl-error-1: ", err)
+// 		appG.Response(http.StatusOK, e.ERROR, err)
+// 		return
+// 	}
+
+// 	if parammaps.Get("id").ValueStr() != "" || parammaps.Get("id").ValueStr() != "0" {
+// 		for _, lppand := range lpplandList {
+// 			if lppand.Id == parammaps.Get("id").ValueInt64() {
+// 				if lppand.Tmrid == parammaps.Get("tmrid").ValueInt64() {
+// 					appG.Response(http.StatusOK, e.SUCCESS, true)
+// 					return
+// 				}
+// 				exist = true
+// 				break
+// 			}
+// 		}
+// 	}
+
+// 	tmrid := parammaps.Get("tmrid").ValueInt64()
+// 	var sort int64 = -1
+// 	if !exist {
+// 		for _, lppand := range lpplandList {
+// 			if lppand.Barid == parammaps.Get("barid").ValueInt64() {
+// 				_, err := tx.SQL(" update lpplandtl1 set lweight =lweight +  ?  where id = ?  and pastureid = ? ", parammaps.Get("lweight").ValueStr(), lppand.Id, parammaps.Get("pastureid").ValueStr()).Execute()
+// 				if err != nil {
+// 					log.Println("AddLpplandtl-error-2: ", err)
+// 					appG.Response(http.StatusOK, e.ERROR, err)
+// 					return
+// 				}
+// 				appG.Response(http.StatusOK, e.SUCCESS, true)
+// 				return
+// 			}
+// 		}
+// 		for i, lppand := range lpplandList {
+// 			lppand.Sort = int64(i) + 1
+// 		}
+// 		updateLpplandList := make([]*lpplandtl1, 0)
+// 		for i, lppand := range lpplandList {
+// 			n := i + 1
+// 			if lppand.Tmrid == tmrid {
+// 				sort = int64(n) + 1
+// 				lppand.Sort = int64(n)
+// 				updateLpplandList = append(updateLpplandList, lppand)
+// 			} else if sort > 0 {
+// 				lppand.Sort = int64(n) + 2
+// 				updateLpplandList = append(updateLpplandList, lppand)
+// 			}
+// 		}
+
+// 		tx.Begin()
+// 		for _, lppand := range updateLpplandList {
+// 			_, err := tx.SQL(" update lpplandtl1 set sort = ? where id = ?  and pastureid = ? ", lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
+// 			if err != nil {
+// 				tx.Rollback()
+// 				log.Println("AddLpplandtl-error-2: ", err)
+// 				appG.Response(http.StatusOK, e.ERROR, err)
+// 				return
+// 			}
+// 		}
+
+// 		if sort < 0 && len(lpplandList) > 0 {
+// 			sort = int64(len(lpplandList) + 2)
+// 		} else if len(lpplandList) == 0 {
+// 			sort = 1
+// 		}
+
+// 		_, err = tx.SQL(`INSERT INTO lpplandtl1(pastureid,lppid,barid,barname,fpdid,lweight,sort,tmrid,tmrname,fttype,background,cowcount,ccountradio)
+// 	VALUES (?,?,?,?,?,?,?,?,?,
+// 	?,?,IF(?='',0,?),IF(?='',0,?))`,
+// 			parammaps.Get("pastureid").ValueStr(),
+// 			parammaps.Get("lppid").ValueStr(),
+// 			parammaps.Get("barid").ValueStr(),
+// 			parammaps.Get("barname").ValueStr(),
+// 			parammaps.Get("fpdid").ValueStr(),
+// 			parammaps.Get("lweight").ValueStr(),
+// 			sort,
+// 			parammaps.Get("tmrid").ValueStr(),
+// 			parammaps.Get("tmrname").ValueStr(),
+// 			parammaps.Get("fttype").ValueStr(),
+// 			parammaps.Get("background").ValueStr(),
+// 			parammaps.Get("cowcount").ValueStr(),
+// 			parammaps.Get("cowcount").ValueStr(),
+// 			parammaps.Get("ccountradio").ValueStr(),
+// 			parammaps.Get("ccountradio").ValueStr()).Execute()
+// 		if err != nil {
+// 			tx.Rollback()
+// 			log.Println("AddLpplandtl-error-3: ", err)
+// 			appG.Response(http.StatusOK, e.ERROR, err)
+// 			return
+// 		}
+
+// 		err = tx.Commit()
+// 		if err != nil {
+// 			tx.Rollback()
+// 			log.Println("AddLpplandtl-error-6: ", err)
+// 			appG.Response(http.StatusOK, e.ERROR, err)
+// 			return
+// 		}
+// 	} else {
+// 		lpplandid := parammaps.Get("id").ValueInt64()
+// 		updateLpplandList := make([]*lpplandtl1, 0)
+// 		var oldsort int64
+// 		for i, lppand := range lpplandList {
+// 			lppand.Sort = int64(i) + 1
+// 		}
+// 		for _, lppand := range lpplandList {
+// 			if lppand.Id == lpplandid {
+// 				oldsort = lppand.Sort
+// 				break
+// 			}
+// 		}
+
+// 		for _, lppand := range lpplandList {
+
+// 			if lppand.Tmrid == tmrid && lppand.Id != lpplandid && sort < 0 {
+// 				sort = lppand.Sort
+// 				break
+// 			}
+// 		}
+
+// 		if sort == -1 {
+// 			sort = 1
+// 		}
+
+// 		if oldsort < sort {
+// 			for _, lppand := range lpplandList {
+// 				if lppand.Id != lpplandid && lppand.Sort > oldsort && lppand.Sort < sort {
+// 					lppand.Sort--
+// 					updateLpplandList = append(updateLpplandList, lppand)
+// 				} else if lppand.Sort > sort && lppand.Id != lpplandid {
+// 					lppand.Sort++
+// 					updateLpplandList = append(updateLpplandList, lppand)
+// 				}
+// 			}
+// 			sort--
+// 		} else {
+// 			for _, lppand := range lpplandList {
+// 				if lppand.Sort < oldsort && lppand.Sort >= sort && lppand.Id != lpplandid {
+// 					lppand.Sort++
+// 					updateLpplandList = append(updateLpplandList, lppand)
+// 				}
+// 			}
+// 		}
+
+// 		var tmrlpplandList []*lpplandtl1
+// 		for _, lppand := range lpplandList {
+// 			exist := false
+// 			for _, lppand1 := range updateLpplandList {
+// 				if lppand.Id == lppand1.Id {
+// 					exist = true
+// 					break
+// 				}
+// 			}
+// 			if !exist {
+// 				tmrlpplandList = append(tmrlpplandList, lppand)
+// 			}
+// 		}
+
+// 		updateLpplandList = append(updateLpplandList, tmrlpplandList...)
+// 		if len(updateLpplandList) > 0 {
+// 			tx.Begin()
+// 			for _, lppand := range updateLpplandList {
+// 				_, err := tx.SQL(" update lpplandtl1 set sort = ? where id = ?  and pastureid = ? ", lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
+// 				if err != nil {
+// 					tx.Rollback()
+// 					log.Println("AddLpplandtl-error-2: ", err)
+// 					appG.Response(http.StatusOK, e.ERROR, err)
+// 					return
+// 				}
+// 			}
+
+// 			_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?,sort = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), sort, lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+// 			if err != nil {
+// 				tx.Rollback()
+// 				log.Println("AddLpplandtl-error-2: ", err)
+// 				appG.Response(http.StatusOK, e.ERROR, err)
+// 				return
+// 			}
+
+// 			tx.Commit()
+// 		}
+
+// 	}
+// 	appG.Response(http.StatusOK, e.SUCCESS, true)
+// }
+
 func AddLpplandtl(c *gin.Context) {
 	appG := app.Gin{C: c}
 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
@@ -1427,7 +1630,7 @@ func AddLpplandtl(c *gin.Context) {
 	var err error
 
 	lpplandList := make([]*lpplandtl1, 0)
-	err = tx.Table("lpplandtl1").Select("id,pastureid,sort,barid,tmrid").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
+	err = tx.Table("lpplandtl1").Select("id,pastureid,sort,barid,tmrid,tmrname").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
 		OrderBy("sort").Find(&lpplandList)
 	if err != nil {
 		log.Println("AddLpplandtl-error-1: ", err)
@@ -1449,8 +1652,8 @@ func AddLpplandtl(c *gin.Context) {
 	}
 
 	tmrid := parammaps.Get("tmrid").ValueInt64()
-	var sort int64 = -1
 	if !exist {
+		var sort int64 = -1
 		for _, lppand := range lpplandList {
 			if lppand.Barid == parammaps.Get("barid").ValueInt64() {
 				_, err := tx.SQL(" update lpplandtl1 set lweight =lweight +  ?  where id = ?  and pastureid = ? ", parammaps.Get("lweight").ValueStr(), lppand.Id, parammaps.Get("pastureid").ValueStr()).Execute()
@@ -1470,11 +1673,11 @@ func AddLpplandtl(c *gin.Context) {
 		for i, lppand := range lpplandList {
 			n := i + 1
 			if lppand.Tmrid == tmrid {
-				sort = int64(n)
-				lppand.Sort = int64(n) + 1
+				sort = int64(n) + 1
+				lppand.Sort = int64(n)
 				updateLpplandList = append(updateLpplandList, lppand)
 			} else if sort > 0 {
-				lppand.Sort = int64(n) + 1
+				lppand.Sort = int64(n) + 2
 				updateLpplandList = append(updateLpplandList, lppand)
 			}
 		}
@@ -1491,7 +1694,7 @@ func AddLpplandtl(c *gin.Context) {
 		}
 
 		if sort < 0 && len(lpplandList) > 0 {
-			sort = int64(len(lpplandList) + 1)
+			sort = int64(len(lpplandList) + 2)
 		} else if len(lpplandList) == 0 {
 			sort = 1
 		}
@@ -1530,69 +1733,164 @@ func AddLpplandtl(c *gin.Context) {
 		}
 	} else {
 		lpplandid := parammaps.Get("id").ValueInt64()
-		updateLpplandList := make([]*lpplandtl1, 0)
+		// updateLpplandList := make([]*lpplandtl1, 0)
 		var oldsort int64
 		for i, lppand := range lpplandList {
 			lppand.Sort = int64(i) + 1
 		}
-		for _, lppand := range lpplandList {
+
+		noup := false
+		for i, lppand := range lpplandList {
 			if lppand.Id == lpplandid {
 				oldsort = lppand.Sort
-				break
-			}
-		}
+				b := false
+				for _, lppand := range lpplandList {
+					if lppand.Tmrid == tmrid {
+						noup = false
+						b = true
+						break
+					}
+				}
 
-		for _, lppand := range lpplandList {
+				if !b {
+					if i == 0 || i == len(lpplandList)-1 {
+						noup = true
+					}
+					if i != 0 && i < len(lpplandList)-1 {
+						if lpplandList[i-1].Tmrid != lppand.Tmrid || lpplandList[i+1].Tmrid != lppand.Tmrid {
+							noup = true
+						}
+					}
 
-			if lppand.Tmrid == tmrid && lppand.Id != lpplandid && sort < 0 {
-				sort = lppand.Sort
+					// if lpplandList[i+1].Tmrid == tmrid {
+					// 	_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+					// 	if err != nil {
+					// 		tx.Rollback()
+					// 		log.Println("AddLpplandtl-error-2: ", err)
+					// 		appG.Response(http.StatusOK, e.ERROR, err)
+					// 		return
+					// 	}
+					// 	tx.Commit()
+					// 	appG.Response(http.StatusOK, e.SUCCESS, true)
+					// 	return
+					// }
+					// }
+					// break
+					// 	}
+					// }
+				}
 				break
 			}
 		}
 
-		if sort == -1 {
-			sort = 1
-		}
+		if noup {
+			_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+			if err != nil {
+				tx.Rollback()
+				log.Println("AddLpplandtl-error-2: ", err)
+				appG.Response(http.StatusOK, e.ERROR, err)
+				return
+			}
+		} else {
 
-		if oldsort < sort {
-			for _, lppand := range lpplandList {
-				if lppand.Id != lpplandid && lppand.Sort > oldsort && lppand.Sort < sort {
-					lppand.Sort--
-					updateLpplandList = append(updateLpplandList, lppand)
-				} else if lppand.Sort > sort && lppand.Id != lpplandid {
-					lppand.Sort++
-					updateLpplandList = append(updateLpplandList, lppand)
+			for i, lppand := range lpplandList {
+				if lppand.Id == lpplandid {
+					if i != 0 {
+						if lpplandList[i-1].Tmrid == tmrid {
+							_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+							if err != nil {
+								tx.Rollback()
+								log.Println("AddLpplandtl-error-2: ", err)
+								appG.Response(http.StatusOK, e.ERROR, err)
+								return
+							}
+							tx.Commit()
+							appG.Response(http.StatusOK, e.SUCCESS, true)
+							return
+						}
+					}
+					if i < len(lpplandList)-1 {
+						if lpplandList[i+1].Tmrid == tmrid {
+							_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+							if err != nil {
+								tx.Rollback()
+								log.Println("AddLpplandtl-error-2: ", err)
+								appG.Response(http.StatusOK, e.ERROR, err)
+								return
+							}
+							tx.Commit()
+							appG.Response(http.StatusOK, e.SUCCESS, true)
+							return
+						}
+					}
+					break
 				}
 			}
-			sort--
-		} else {
+			exist := false
+			sort1 := 0
+			a := false
 			for _, lppand := range lpplandList {
-				if lppand.Sort < oldsort && lppand.Sort >= sort && lppand.Id != lpplandid {
-					lppand.Sort++
-					updateLpplandList = append(updateLpplandList, lppand)
+				if lppand.Tmrid == tmrid && lppand.Id != lpplandid {
+					sort1 = int(lppand.Sort)
+					if !a {
+						for _, lppand1 := range lpplandList {
+							if lppand1.Id == lpplandid {
+								lppand1.Tmrid = tmrid
+								lppand1.Tmrname = lppand.Tmrname
+								a = true
+								// lppand1.Sort = lppand.Sort
+								break
+							}
+						}
+					}
+					exist = true
 				}
 			}
-		}
 
-		var tmrlpplandList []*lpplandtl1
-		for _, lppand := range lpplandList {
-			exist := false
-			for _, lppand1 := range updateLpplandList {
-				if lppand.Id == lppand1.Id {
-					exist = true
-					break
+			if exist {
+				if oldsort > int64(sort1) {
+					for _, lppand := range lpplandList {
+						if lppand.Id == lpplandid {
+							lppand.Sort = int64(sort1) + 1
+							continue
+						}
+						if lppand.Sort >= int64(sort1)+1 {
+							lppand.Sort++
+						}
+					}
+				} else {
+					for _, lppand := range lpplandList {
+						if lppand.Id == lpplandid {
+							lppand.Sort = int64(sort1) + 1
+							continue
+						}
+						if lppand.Sort > oldsort && lppand.Sort < int64(sort1)+1 {
+							lppand.Sort--
+						} else if lppand.Sort <= int64(sort1)+1 {
+							lppand.Sort++
+						}
+					}
+				}
+			} else {
+				for _, lppand := range lpplandList {
+					if lppand.Id == lpplandid {
+						lppand.Sort = int64(len(lpplandList)) + 1
+						lppand.Tmrid = tmrid
+						lppand.Tmrname = parammaps.Get("tmrname").ValueStr()
+						break
+					}
 				}
 			}
-			if !exist {
-				tmrlpplandList = append(tmrlpplandList, lppand)
+
+			sort.Slice(lpplandList, func(i, j int) bool {
+				return lpplandList[i].Sort < lpplandList[j].Sort // 升序
+			})
+			for i, lppand := range lpplandList {
+				lppand.Sort = int64(i) + 1
 			}
-		}
 
-		updateLpplandList = append(updateLpplandList, tmrlpplandList...)
-		if len(updateLpplandList) > 0 {
-			tx.Begin()
-			for _, lppand := range updateLpplandList {
-				_, err := tx.SQL(" update lpplandtl1 set sort = ? where id = ?  and pastureid = ? ", lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
+			for _, lppand := range lpplandList {
+				_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?,sort = ?   where id = ?  and pastureid = ? ", lppand.Tmrid, lppand.Tmrname, lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
 				if err != nil {
 					tx.Rollback()
 					log.Println("AddLpplandtl-error-2: ", err)
@@ -1600,17 +1898,8 @@ func AddLpplandtl(c *gin.Context) {
 					return
 				}
 			}
-
-			_, err := tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ?,sort = ?   where id = ?  and pastureid = ? ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), sort, lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
-			if err != nil {
-				tx.Rollback()
-				log.Println("AddLpplandtl-error-2: ", err)
-				appG.Response(http.StatusOK, e.ERROR, err)
-				return
-			}
-
-			tx.Commit()
 		}
+		tx.Commit()
 
 	}
 	appG.Response(http.StatusOK, e.SUCCESS, true)
@@ -1635,9 +1924,11 @@ func UpdateLpplandtlSort(c *gin.Context) {
 		appG.Response(http.StatusOK, e.ERROR, err)
 		return
 	}
-	var oldsort int64
+	var oldsort, lpplandtlsort int64
 	tmrid := parammaps.Get("tmrid").ValueInt64()
 	sort := parammaps.Get("sort").ValueInt64()
+	lpplandtlid := parammaps.Get("id").ValueInt64()
+	sort1 := parammaps.Get("sort").ValueInt64()
 
 	for i, lppland := range lpplandList {
 		lppland.Sort = int64(i) + 1
@@ -1673,11 +1964,43 @@ func UpdateLpplandtlSort(c *gin.Context) {
 	for _, lppland := range lpplandList {
 		if lppland.Tmrid == tmrid {
 			tmrLpplandList = append(tmrLpplandList, lppland)
+			if lppland.Id == lpplandtlid {
+				lpplandtlsort = lppland.Sort
+			}
+		}
+	}
+	exist := false
+	for _, tmrLppland := range tmrLpplandList {
+		if sort1 == tmrLppland.Sort {
+			exist = true
+			break
 		}
 	}
 
-	for i, tmrLppland := range tmrLpplandList {
-		tmrLppland.Sort = sort + int64(i)
+	if exist {
+		for _, tmrLppland := range tmrLpplandList {
+			if sort1 <= tmrLppland.Sort && lpplandtlsort > tmrLppland.Sort {
+				tmrLppland.Sort++
+			} else if sort1 >= tmrLppland.Sort && lpplandtlsort <= tmrLppland.Sort {
+				tmrLppland.Sort--
+			}
+		}
+		for _, tmrLppland := range tmrLpplandList {
+			if tmrLppland.Id == lpplandtlid {
+				tmrLppland.Sort = sort1
+				break
+			}
+		}
+	} else {
+		if oldsort < sort && len(tmrLpplandList) > 1 {
+			for i, tmrLppland := range tmrLpplandList {
+				tmrLppland.Sort = sort + int64(i) - 1
+			}
+		} else {
+			for i, tmrLppland := range tmrLpplandList {
+				tmrLppland.Sort = sort + int64(i)
+			}
+		}
 	}
 
 	if oldsort > sort {
@@ -1691,7 +2014,7 @@ func UpdateLpplandtlSort(c *gin.Context) {
 	} else {
 		var uptmrid int64
 		for _, lppland := range lpplandList {
-			if lppland.Sort == sort {
+			if lppland.Sort == sort && lppland.Tmrid != tmrid {
 				uptmrid = lppland.Tmrid
 				sort = lppland.Sort
 			} else if uptmrid != 0 && uptmrid == lppland.Tmrid {
@@ -1802,8 +2125,8 @@ func AddLpplandtlDate(c *gin.Context) {
 	}
 
 	tmrid := parammaps.Get("tmrid").ValueInt64()
-	var sort int64 = -1
 	if !exist {
+		var sort int64 = -1
 		for _, lppand := range lpplandList {
 			if lppand.Barid == parammaps.Get("barid").ValueInt64() {
 				_, err := tx.SQL(" update lpplandtl1date set lweight =lweight + ?  where id = ?  and pastureid = ? ", parammaps.Get("lweight").ValueStr(), lppand.Id, parammaps.Get("pastureid").ValueStr()).Execute()
@@ -1823,11 +2146,11 @@ func AddLpplandtlDate(c *gin.Context) {
 		for i, lppand := range lpplandList {
 			n := i + 1
 			if lppand.Tmrid == tmrid {
-				sort = int64(n)
-				lppand.Sort = int64(n) + 1
+				sort = int64(n) + 1
+				lppand.Sort = int64(n)
 				updateLpplandList = append(updateLpplandList, lppand)
 			} else if sort > 0 {
-				lppand.Sort = int64(n) + 1
+				lppand.Sort = int64(n) + 2
 				updateLpplandList = append(updateLpplandList, lppand)
 			}
 		}
@@ -1883,70 +2206,154 @@ func AddLpplandtlDate(c *gin.Context) {
 		}
 	} else {
 		lpplandid := parammaps.Get("id").ValueInt64()
-		updateLpplandList := make([]*lpplandtl1, 0)
+		// updateLpplandList := make([]*lpplandtl1, 0)
 		var oldsort int64
 		for i, lppand := range lpplandList {
 			lppand.Sort = int64(i) + 1
 		}
 
-		for _, lppand := range lpplandList {
+		noup := false
+		for i, lppand := range lpplandList {
 			if lppand.Id == lpplandid {
 				oldsort = lppand.Sort
-				break
-			}
-		}
-
-		for _, lppand := range lpplandList {
+				b := false
+				for _, lppand := range lpplandList {
+					if lppand.Tmrid == tmrid {
+						noup = false
+						b = true
+						break
+					}
+				}
 
-			if lppand.Tmrid == tmrid && lppand.Id != lpplandid && sort < 0 {
-				sort = lppand.Sort
+				if !b {
+					if i == 0 || i == len(lpplandList)-1 {
+						noup = true
+					}
+					if i != 0 && i < len(lpplandList)-1 {
+						if lpplandList[i-1].Tmrid != lppand.Tmrid || lpplandList[i+1].Tmrid != lppand.Tmrid {
+							noup = true
+						}
+					}
+				}
 				break
 			}
 		}
 
-		if sort == -1 {
-			sort = 1
-		}
+		if noup {
+			_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ? and date = ? ",
+				parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr(), parammaps.Get("date").ValueStr()).Execute()
+			if err != nil {
+				tx.Rollback()
+				log.Println("AddLpplandtl-error-2: ", err)
+				appG.Response(http.StatusOK, e.ERROR, err)
+				return
+			}
+		} else {
 
-		if oldsort < sort {
-			for _, lppand := range lpplandList {
-				if lppand.Id != lpplandid && lppand.Sort > oldsort && lppand.Sort < sort {
-					lppand.Sort--
-					updateLpplandList = append(updateLpplandList, lppand)
-				} else if lppand.Sort > sort && lppand.Id != lpplandid {
-					lppand.Sort++
-					updateLpplandList = append(updateLpplandList, lppand)
+			for i, lppand := range lpplandList {
+				if lppand.Id == lpplandid {
+					if i != 0 {
+						if lpplandList[i-1].Tmrid == tmrid {
+							_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ?  and date = ?  ",
+								parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr(), parammaps.Get("date").ValueStr()).Execute()
+							if err != nil {
+								tx.Rollback()
+								log.Println("AddLpplandtl-error-2: ", err)
+								appG.Response(http.StatusOK, e.ERROR, err)
+								return
+							}
+							tx.Commit()
+							appG.Response(http.StatusOK, e.SUCCESS, true)
+							return
+						}
+					}
+					if i < len(lpplandList)-1 {
+						if lpplandList[i+1].Tmrid == tmrid {
+							_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?   where id = ?  and pastureid = ?  and date = ? ", parammaps.Get("tmrid").ValueStr(),
+								parammaps.Get("tmrname").ValueStr(), lpplandid, parammaps.Get("pastureid").ValueStr(), parammaps.Get("date").ValueStr()).Execute()
+							if err != nil {
+								tx.Rollback()
+								log.Println("AddLpplandtl-error-2: ", err)
+								appG.Response(http.StatusOK, e.ERROR, err)
+								return
+							}
+							tx.Commit()
+							appG.Response(http.StatusOK, e.SUCCESS, true)
+							return
+						}
+					}
+					break
 				}
 			}
-			sort--
-		} else {
+			exist := false
+			sort1 := 0
+			a := false
 			for _, lppand := range lpplandList {
-				if lppand.Sort < oldsort && lppand.Sort >= sort && lppand.Id != lpplandid {
-					lppand.Sort++
-					updateLpplandList = append(updateLpplandList, lppand)
+				if lppand.Tmrid == tmrid && lppand.Id != lpplandid {
+					sort1 = int(lppand.Sort)
+					if !a {
+						for _, lppand1 := range lpplandList {
+							if lppand1.Id == lpplandid {
+								lppand1.Tmrid = tmrid
+								lppand1.Tmrname = lppand.Tmrname
+								a = true
+								// lppand1.Sort = lppand.Sort
+								break
+							}
+						}
+					}
+					exist = true
 				}
 			}
-		}
 
-		var tmrlpplandList []*lpplandtl1
-		for _, lppand := range lpplandList {
-			exist := false
-			for _, lppand1 := range updateLpplandList {
-				if lppand.Id == lppand1.Id {
-					exist = true
-					break
+			if exist {
+				if oldsort > int64(sort1) {
+					for _, lppand := range lpplandList {
+						if lppand.Id == lpplandid {
+							lppand.Sort = int64(sort1) + 1
+							continue
+						}
+						if lppand.Sort >= int64(sort1)+1 {
+							lppand.Sort++
+						}
+					}
+				} else {
+					for _, lppand := range lpplandList {
+						if lppand.Id == lpplandid {
+							lppand.Sort = int64(sort1) + 1
+							continue
+						}
+						// if lppand.Sort > oldsort {
+						// 	lppand.Sort--
+						// }
+						if lppand.Sort > oldsort && lppand.Sort < int64(sort1)+1 {
+							lppand.Sort--
+						} else if lppand.Sort <= int64(sort1)+1 {
+							lppand.Sort++
+						}
+					}
+				}
+			} else {
+				for _, lppand := range lpplandList {
+					if lppand.Id == lpplandid {
+						lppand.Sort = int64(len(lpplandList)) + 1
+						lppand.Tmrid = tmrid
+						lppand.Tmrname = parammaps.Get("tmrname").ValueStr()
+						break
+					}
 				}
 			}
-			if !exist {
-				tmrlpplandList = append(tmrlpplandList, lppand)
+
+			sort.Slice(lpplandList, func(i, j int) bool {
+				return lpplandList[i].Sort < lpplandList[j].Sort // 升序
+			})
+			for i, lppand := range lpplandList {
+				lppand.Sort = int64(i) + 1
 			}
-		}
 
-		updateLpplandList = append(updateLpplandList, tmrlpplandList...)
-		if len(updateLpplandList) > 0 {
-			tx.Begin()
-			for _, lppand := range updateLpplandList {
-				_, err := tx.SQL(" update lpplandtl1date set sort = ? where id = ?  and pastureid = ?  ", lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
+			for _, lppand := range lpplandList {
+				_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?,sort = ?   where id = ?  and pastureid = ?  and date = ? ",
+					lppand.Tmrid, lppand.Tmrname, lppand.Sort, lppand.Id, lppand.Pastureid, parammaps.Get("date").ValueStr()).Execute()
 				if err != nil {
 					tx.Rollback()
 					log.Println("AddLpplandtl-error-2: ", err)
@@ -1954,17 +2361,91 @@ func AddLpplandtlDate(c *gin.Context) {
 					return
 				}
 			}
-
-			_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?,sort = ?  where id = ?  and pastureid = ?  ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), sort, lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
-			if err != nil {
-				tx.Rollback()
-				log.Println("AddLpplandtl-error-2: ", err)
-				appG.Response(http.StatusOK, e.ERROR, err)
-				return
-			}
-
-			tx.Commit()
 		}
+		tx.Commit()
+		// lpplandid := parammaps.Get("id").ValueInt64()
+		// updateLpplandList := make([]*lpplandtl1, 0)
+		// var oldsort int64
+		// for i, lppand := range lpplandList {
+		// 	lppand.Sort = int64(i) + 1
+		// }
+
+		// for _, lppand := range lpplandList {
+		// 	if lppand.Id == lpplandid {
+		// 		oldsort = lppand.Sort
+		// 		break
+		// 	}
+		// }
+
+		// for _, lppand := range lpplandList {
+
+		// 	if lppand.Tmrid == tmrid && lppand.Id != lpplandid && sort < 0 {
+		// 		sort = lppand.Sort
+		// 		break
+		// 	}
+		// }
+
+		// if sort == -1 {
+		// 	sort = 1
+		// }
+
+		// if oldsort < sort {
+		// 	for _, lppand := range lpplandList {
+		// 		if lppand.Id != lpplandid && lppand.Sort > oldsort && lppand.Sort < sort {
+		// 			lppand.Sort--
+		// 			updateLpplandList = append(updateLpplandList, lppand)
+		// 		} else if lppand.Sort > sort && lppand.Id != lpplandid {
+		// 			lppand.Sort++
+		// 			updateLpplandList = append(updateLpplandList, lppand)
+		// 		}
+		// 	}
+		// 	sort--
+		// } else {
+		// 	for _, lppand := range lpplandList {
+		// 		if lppand.Sort < oldsort && lppand.Sort >= sort && lppand.Id != lpplandid {
+		// 			lppand.Sort++
+		// 			updateLpplandList = append(updateLpplandList, lppand)
+		// 		}
+		// 	}
+		// }
+
+		// var tmrlpplandList []*lpplandtl1
+		// for _, lppand := range lpplandList {
+		// 	exist := false
+		// 	for _, lppand1 := range updateLpplandList {
+		// 		if lppand.Id == lppand1.Id {
+		// 			exist = true
+		// 			break
+		// 		}
+		// 	}
+		// 	if !exist {
+		// 		tmrlpplandList = append(tmrlpplandList, lppand)
+		// 	}
+		// }
+
+		// updateLpplandList = append(updateLpplandList, tmrlpplandList...)
+		// if len(updateLpplandList) > 0 {
+		// 	tx.Begin()
+		// 	for _, lppand := range updateLpplandList {
+		// 		_, err := tx.SQL(" update lpplandtl1date set sort = ? where id = ?  and pastureid = ?  ", lppand.Sort, lppand.Id, lppand.Pastureid).Execute()
+		// 		if err != nil {
+		// 			tx.Rollback()
+		// 			log.Println("AddLpplandtl-error-2: ", err)
+		// 			appG.Response(http.StatusOK, e.ERROR, err)
+		// 			return
+		// 		}
+		// 	}
+
+		// 	_, err := tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ?,sort = ?  where id = ?  and pastureid = ?  ", parammaps.Get("tmrid").ValueStr(), parammaps.Get("tmrname").ValueStr(), sort, lpplandid, parammaps.Get("pastureid").ValueStr()).Execute()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		log.Println("AddLpplandtl-error-2: ", err)
+		// 		appG.Response(http.StatusOK, e.ERROR, err)
+		// 		return
+		// 	}
+
+		// 	tx.Commit()
+		// }
 
 	}
 	appG.Response(http.StatusOK, e.SUCCESS, true)
@@ -1975,6 +2456,7 @@ func UpdateLpplandtlDateSort(c *gin.Context) {
 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 	fsion := gofasion.NewFasion(string(dataByte))
 	parammaps := fsion.Get("parammaps")
+	date := parammaps.Get("date").ValueStr()
 
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
@@ -1983,15 +2465,17 @@ func UpdateLpplandtlDateSort(c *gin.Context) {
 
 	lpplandList := make([]*lpplandtl1, 0)
 	err = tx.Table("lpplandtl1date").Select("id,pastureid,sort,tmrid").Where("lppid = ? ", parammaps.Get("lppid").ValueStr()).And("pastureid = ?", parammaps.Get("pastureid").ValueStr()).
-		And("date = ? ", parammaps.Get("date").ValueStr()).OrderBy("sort").Find(&lpplandList)
+		And("date = ? ", date).OrderBy("sort").Find(&lpplandList)
 	if err != nil {
 		log.Println("UpdateLpplandtlSort-error-1: ", err)
 		appG.Response(http.StatusOK, e.ERROR, err)
 		return
 	}
-	var oldsort int64
+	var oldsort, lpplandtlsort int64
 	tmrid := parammaps.Get("tmrid").ValueInt64()
 	sort := parammaps.Get("sort").ValueInt64()
+	lpplandtlid := parammaps.Get("id").ValueInt64()
+	sort1 := parammaps.Get("sort").ValueInt64()
 
 	for i, lppland := range lpplandList {
 		lppland.Sort = int64(i) + 1
@@ -2027,11 +2511,43 @@ func UpdateLpplandtlDateSort(c *gin.Context) {
 	for _, lppland := range lpplandList {
 		if lppland.Tmrid == tmrid {
 			tmrLpplandList = append(tmrLpplandList, lppland)
+			if lppland.Id == lpplandtlid {
+				lpplandtlsort = lppland.Sort
+			}
+		}
+	}
+	exist := false
+	for _, tmrLppland := range tmrLpplandList {
+		if sort1 == tmrLppland.Sort {
+			exist = true
+			break
 		}
 	}
 
-	for i, tmrLppland := range tmrLpplandList {
-		tmrLppland.Sort = sort + int64(i)
+	if exist {
+		for _, tmrLppland := range tmrLpplandList {
+			if sort1 <= tmrLppland.Sort && lpplandtlsort > tmrLppland.Sort {
+				tmrLppland.Sort++
+			} else if sort1 >= tmrLppland.Sort && lpplandtlsort <= tmrLppland.Sort {
+				tmrLppland.Sort--
+			}
+		}
+		for _, tmrLppland := range tmrLpplandList {
+			if tmrLppland.Id == lpplandtlid {
+				tmrLppland.Sort = sort1
+				break
+			}
+		}
+	} else {
+		if oldsort < sort && len(tmrLpplandList) > 1 {
+			for i, tmrLppland := range tmrLpplandList {
+				tmrLppland.Sort = sort + int64(i) - 1
+			}
+		} else {
+			for i, tmrLppland := range tmrLpplandList {
+				tmrLppland.Sort = sort + int64(i)
+			}
+		}
 	}
 
 	if oldsort > sort {
@@ -2045,7 +2561,7 @@ func UpdateLpplandtlDateSort(c *gin.Context) {
 	} else {
 		var uptmrid int64
 		for _, lppland := range lpplandList {
-			if lppland.Sort == sort {
+			if lppland.Sort == sort && lppland.Tmrid != tmrid {
 				uptmrid = lppland.Tmrid
 				sort = lppland.Sort
 			} else if uptmrid != 0 && uptmrid == lppland.Tmrid {
@@ -2097,7 +2613,7 @@ func UpdateLpplandtlDateSort(c *gin.Context) {
 		wg.Add(1)
 		go func(lppland *lpplandtl1) {
 			defer wg.Done()
-			_, err = tx.SQL(`update  lpplandtl1date set sort = ?  where id = ? and pastureid = ? `, lppland.Sort, lppland.Id, lppland.Pastureid).Execute()
+			_, err = tx.SQL(`update  lpplandtl1date set sort = ?  where id = ? and pastureid = ? and date = ? `, lppland.Sort, lppland.Id, lppland.Pastureid, date).Execute()
 			if err != nil {
 				log.Println("UpdateLpplandtlSort-error-2: ", err)
 				tx.Rollback()

+ 29 - 20
routers/api/udsync.go

@@ -32,16 +32,6 @@ func UDSync() {
 	}
 	log.Println("Starting Cron...")
 	// UDFeedtempletinfo(pastureinfo.Token, pastureinfo.Pastureid)
-	// UDUploadadddata(pastureinfo.Token, pastureinfo.Pastureid)
-	// UDUploaddiliverdata(pastureinfo.Token, pastureinfo.Pastureid)
-	// UDUploadoverplusdata(pastureinfo.Token, pastureinfo.Pastureid)
-	// // 同步栏舍
-	// resFeedp := httpGet(pastureinfo.Token, "downloadpen")
-	// syncFeedp(pastureinfo.Pastureid, resFeedp)
-
-	// //  同步饲料
-	// resFeed := httpGet(pastureinfo.Token, "downloadmaterial")
-	// syncFeed(pastureinfo.Pastureid, resFeed)
 
 	defer func() {
 		if err := recover(); err != nil {
@@ -49,13 +39,15 @@ func UDSync() {
 			logging.Error("panic recover err ", err)
 		}
 	}()
+
 	log.Println("Starting Cron...")
 	c := cron.New()
+	// UDuploadnewdiliverdata(pastureinfo.Token, pastureinfo.Pastureid)
 	_, err = c.AddFunc("30 21 * * *", func() {
 		log.Println("UDSync", time.Now())
 		UDFeedtempletinfo(pastureinfo.Token, pastureinfo.Pastureid)
 		UDUploadadddata(pastureinfo.Token, pastureinfo.Pastureid)
-		UDUploaddiliverdata(pastureinfo.Token, pastureinfo.Pastureid)
+		UDuploadnewdiliverdata(pastureinfo.Token, pastureinfo.Pastureid)
 		UDUploadoverplusdata(pastureinfo.Token, pastureinfo.Pastureid)
 		// // 同步栏舍
 		// resFeedp := httpGet(pastureinfo.Token, "downloadpen")
@@ -472,7 +464,7 @@ ORDER BY tmrno`
 
 	data, err := tx.SQL(sqlstr, pastureid, pastureid).Query().List()
 	if err != nil {
-		logs.Error("syncBar-error-5:", err)
+		logs.Error("UDUploadadddata-error-5:", err)
 		return
 	}
 	req := make(map[string]interface{})
@@ -488,7 +480,7 @@ ORDER BY tmrno`
 
 }
 
-func UDUploaddiliverdata(token, pastureid string) {
+func UDuploadnewdiliverdata(token, pastureid string) {
 
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
@@ -497,36 +489,41 @@ func UDUploaddiliverdata(token, pastureid string) {
 	d.id,IFNULL(ft.id,d2.feedtempletid ) recipeId, 
 	IFNULL(d.templetName,d2.feedtempletName ) recipeName, 
 	date_format(d.mydate,'%Y-%m-%d') as dropDate,ifnull((select sort from downloadedplan where pid=d.pid and lpplanType !=d.lpplanType and mydate=d.mydate),d.sort) as tmrNo,
-	d.Times as dropShift,b.bcode as penId,d2.Fname as penName,fp.CCOUNT as cowCount, d2.SORT as feedingNo, d2.LWEIGHT as expWeight,
+	d.Times as dropShift,b.bcode as penId,d2.Fname as penName,fp.CCOUNT as cowCount, d2.SORT as feedingNo, 
+ROUND(d2.lweight * (dd.actualweightminus/ (select sum(actualweightminus) from downloadplandtl1 where pid = dd.pid and type = 0) ),2) as expWeight,
 	d2.ActualWeightMinus as actualWeight, ifnull(date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s'),"") as startTime,
 	date_format(d2.InTime,'%Y-%m-%d %H:%i:%s') as endTime,ifnull((SELECT dr.driver FROM dutyrecord dr 
 WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid AND dr.times= d.times  AND dr.operatetime <=d.mydate 
-ORDER BY dr.operatetime DESC LIMIT 1),"") as tmrName ,d.tmrtname equipmentId , dd.fname,ROUND((d2.actualweightminus / ( select sum(actualweightminus) from downloadplandtl2  where pid = d.id ) * (dd.actualweightminus/ (select sum(actualweightminus) from downloadplandtl1 where pid = dd.pid and type = 0) * ( select sum(actualweightminus) from downloadplandtl2  where pid = d.id ))),2) as feedWeight
+ORDER BY dr.operatetime DESC LIMIT 1),"") as tmrName ,d.tmrtname equipmentId ,
+dd.fname,
+ROUND(d2.actualweightminus * (dd.actualweightminus/ (select sum(actualweightminus) from downloadplandtl1 where pid = dd.pid and type = 0) ),2) feedWeight
 	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(NOW(),'%Y-%m-%d') and dd.IsCompleted=1 and dd.lpplanType =1 ) dd on dd.lppid = d.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(now(),'%Y-%m-%d') and dd.IsCompleted=1 and dd.lpplanType =1 ) dd on dd.lppid = d.pid
 	
 	LEFT JOIN feedp fp on d2.FBarID=fp.id 
 	left join bar b on fp.barid = b.id and d.pastureid = b.pastureid
 	left JOIN feedtemplet ft on d.templetName=ft.TNAME 
-	where d.mydate= date_format(NOW(),'%Y-%m-%d') and d.IsCompleted=1 and d.lpplanType!=1 and d.pastureid = ?  order by tmrno `
+	where d.mydate= date_format(now(),'%Y-%m-%d') and d.IsCompleted=1 and d.lpplanType!=1 and d.pastureid = ?  order by tmrno  `
 
 	data, err := tx.SQL(sqlstr, pastureid).Query().List()
 	if err != nil {
-		logs.Error("syncBar-error-5:", err)
+		logs.Error("UDuploadnewdiliverdata-error-1:", err)
 		return
 	}
 	req := make(map[string]interface{})
 	req["farmId"] = token
 	req["rowCount"] = len(data)
-	req["method"] = "uploaddiliverdata"
+	req["method"] = "uploadnewdiliverdata"
+	// req["method"] = "uploaddiliverdata"
 	req["resultData"] = data
 
 	res := new(UDUploadoverplusdataReq)
 	res.ApiId = "getKPTData"
 	res.Param = req
-	UDPostPush(res, "application/json")
 
+	UDPostPush(res, "application/json")
 }
 
 type UDUploadoverplusdataReq struct {
@@ -608,3 +605,15 @@ func getPastureInfo() ([]map[string]interface{}, error) {
 
 	return data, nil
 }
+
+type SyncInfo struct {
+	ApiId string    `json:"apiId"`
+	Param ParamInfo `json:"param"`
+}
+
+type ParamInfo struct {
+	FarmId     string                 `json:"farmId"`
+	RowCount   string                 `json:"rowCount"`
+	Method     string                 `json:"method"`
+	ResultData map[string]interface{} `json:"resultData"`
+}

+ 40 - 16
routers/api/user.go

@@ -1,27 +1,32 @@
 package api
 
 import (
+	"fmt"
+	"io/ioutil"
+	"net/http"
+
 	"../../pkg/app"
 	"../../pkg/e"
 	"../../pkg/util"
 	"../../routers/restful"
 	"../../service/user_service"
-	"fmt"
+	"github.com/Anderson-Lu/gofasion/gofasion"
+	"github.com/astaxie/beego/logs"
 	"github.com/astaxie/beego/validation"
 	"github.com/gin-gonic/gin"
-	"net/http"
 )
 
 type auth struct {
-	Id       int    `json:"id"`
-	Username string `json:"username"`
-	Password string `json:"password"`
+	Id         int    `json:"id"`
+	Username   string `json:"username"`
+	Password   string `json:"password"`
 	CaptchaKey string `json:"CaptchaKey"`
-	Role     int    `json:"role_id"`
-	Imei string	`json:"imei"`
-	PastureId string `json:"pastureid"`
-	TypeIn int `json:"typein"`
+	Role       int    `json:"role_id"`
+	Imei       string `json:"imei"`
+	PastureId  string `json:"pastureid"`
+	TypeIn     int    `json:"typein"`
 }
+
 // @Summary   获取登录token 信息
 // @Tags auth
 // @Accept json
@@ -76,7 +81,6 @@ func Auth(c *gin.Context) {
 	})
 }
 
-
 // @Summary   获取登录token 信息
 // @Tags auth
 // @Accept json
@@ -92,7 +96,7 @@ func AuthLogin(c *gin.Context) {
 	appG := app.Gin{C: c}
 	var reqInfo auth
 	err := c.BindJSON(&reqInfo)
-	fmt.Println("++++++++++++++++",reqInfo)
+	fmt.Println("++++++++++++++++", reqInfo)
 
 	valid := validation.Validation{}
 	valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
@@ -102,7 +106,7 @@ func AuthLogin(c *gin.Context) {
 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors)
 		return
 	}
-	err =restful.CheckUserFace(reqInfo.Username,reqInfo.Imei,reqInfo.TypeIn)
+	err = restful.CheckUserFace(reqInfo.Username, reqInfo.Imei, reqInfo.TypeIn)
 	if err != nil {
 		appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err.Error())
 		return
@@ -128,7 +132,7 @@ func AuthLogin(c *gin.Context) {
 func UserLogout(c *gin.Context) {
 	appG := app.Gin{C: c}
 	data := make(map[string]interface{})
-	data["name"] =""
+	data["name"] = ""
 	data["avatar"] = ""
 	data["introduction"] = ""
 	appG.Response(http.StatusOK, e.SUCCESS, data)
@@ -147,18 +151,38 @@ func GetUserinfo(c *gin.Context) {
 	appG.Response(http.StatusOK, e.SUCCESS, data)
 }
 
-
 func GetOpenID(c *gin.Context) {
 	code := c.Param("code")
 	appG := app.Gin{C: c}
 	openid, err := util.SendWxAuthAPI(code)
 	if err != nil {
 		appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
-			"err": "openid 获取失败 :"+err.Error(),
+			"err": "openid 获取失败 :" + err.Error(),
 		})
 		return
 	}
 	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
 		"openid": openid,
 	})
-}
+}
+
+func UserWXOpenIDBinding(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	openid := fsion.Get("openid").ValueStr()
+	pastureid := fsion.Get("pastureid").ValueStr()
+	userid := fsion.Get("userid").ValueStr()
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	_, err := tx.SQL(` replace into user_wx(userid,pastureid,openid) VALUES (?,?,?)`, userid, pastureid, openid).Execute()
+	if err != nil {
+		logs.Error("UserWXOpenIDBinding-error1:", err)
+		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+		return
+	}
+
+	fmt.Println(pastureid, userid, openid)
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}

+ 1 - 1
routers/restful/sql_utils.go

@@ -919,7 +919,7 @@ func ExecQueryT(sqlstr string, params []interface{}, tx *xorm.Session) (interfac
 		return nil, err
 	}
 
-	LastInsertId, _ := rows.LastInsertId()
+	LastInsertId, err := rows.LastInsertId()
 	idPointer := (*int)(unsafe.Pointer(&LastInsertId))
 	idd16 := *idPointer
 	data := make(map[string]interface{})

+ 11 - 1
routers/router.go

@@ -1,6 +1,7 @@
 package routers
 
 import (
+	"context"
 	"fmt"
 
 	"../comm"
@@ -20,8 +21,8 @@ import (
 
 func InitRouter() *gin.Engine {
 	r := gin.New()
-
 	// go api.UDSync()
+	go api.CronScheduled(context.TODO())
 
 	r.Use(func(c *gin.Context) {
 		fmt.Println(c.Request.URL)
@@ -65,6 +66,8 @@ func InitRouter() *gin.Engine {
 	eqm := r.Group("/manage/api")
 	eqm.POST("/login", api.Auth)
 
+	r.POST("/userwxopenid/binding", api.UserWXOpenIDBinding)
+
 	apiV1 := r.Group("/authdata")
 	apiV1.Use(jwt.JWT()) // token 验证
 	{
@@ -154,6 +157,7 @@ func InitRouter() *gin.Engine {
 
 		apiV1.POST("/ftdetail/edit", api.UpdateFTdetail)
 		apiV1.POST("/fpdetail/edit", api.UpdateFpdetailBar)
+		apiV1.POST("/ftdetai/del", api.DeleteFTdetail)
 		apiV1.POST("/lpplandtl/add", api.AddLpplandtl)
 		apiV1.POST("/lpplandtl/edit/sort", api.UpdateLpplandtlSort)
 		apiV1.POST("/lpplandtl/date/add", api.AddLpplandtlDate)
@@ -166,6 +170,12 @@ func InitRouter() *gin.Engine {
 
 		apiV1.POST("/ftdry/add", api.AddFtdry)
 		apiV1.POST("/checkDates", api.CheckDates)
+		//编辑数据同步勾选状态
+		apiV1.POST("/scheduled/status/edit", api.UpdateScheduledStatus)
+		//	立即同步
+		apiV1.POST("/synchronizeNow", api.SynchronizeNow)
+
+		apiV1.POST("/fpdimportexcel", api.FpdImportExcel)
 
 	}
 

BIN
tmrgo


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