baishaojie 1 år sedan
förälder
incheckning
ff25393014
88 ändrade filer med 6467 tillägg och 507 borttagningar
  1. 10 2
      apiserver/config/config.go
  2. 2 3
      apiserver/model/bigpartpurchase.go
  3. 3 0
      apiserver/model/emp.go
  4. 11 0
      apiserver/model/ensiling.go
  5. 11 1
      apiserver/model/equipment.go
  6. 5 0
      apiserver/model/feedsum.go
  7. 5 0
      apiserver/model/feequery.go
  8. 7 3
      apiserver/model/home/home.go
  9. 8 5
      apiserver/model/http/asset.go
  10. 22 0
      apiserver/model/http/chart.go
  11. 30 0
      apiserver/model/http/equipment.go
  12. 3 2
      apiserver/model/http/feequery.go
  13. 9 6
      apiserver/model/http/http.go
  14. 37 0
      apiserver/model/http/oauth2token.go
  15. 6 1
      apiserver/model/http/order.go
  16. 8 0
      apiserver/model/http/sap.go
  17. 93 0
      apiserver/model/liugong/register.go
  18. 88 0
      apiserver/model/liugong/vehicle.go
  19. 57 17
      apiserver/model/partpurchase.go
  20. 23 26
      apiserver/model/pasture.go
  21. 9 0
      apiserver/model/sso.go
  22. 79 0
      apiserver/model/stock.go
  23. 13 0
      apiserver/model/user.go
  24. 5 1
      apiserver/routers/api/api.go
  25. 222 109
      apiserver/routers/api/db.go
  26. 2 0
      apiserver/routers/api/user.go
  27. 291 0
      apiserver/routers/chart.go
  28. 18 0
      apiserver/routers/diesel.go
  29. 132 0
      apiserver/routers/home.go
  30. 134 0
      apiserver/routers/liugong.go
  31. 13 0
      apiserver/routers/report.go
  32. 71 3
      apiserver/routers/router.go
  33. 24 0
      apiserver/routers/sap.go
  34. 65 0
      apiserver/routers/stock.go
  35. 41 9
      apiserver/service/asset.go
  36. 8 1
      apiserver/service/charge_off.go
  37. 1795 0
      apiserver/service/chart.go
  38. 541 48
      apiserver/service/contract.go
  39. 145 100
      apiserver/service/diesel.go
  40. 546 0
      apiserver/service/equipment.go
  41. 8 7
      apiserver/service/feequery.go
  42. 161 73
      apiserver/service/home.go
  43. 214 0
      apiserver/service/idaas.go
  44. 35 2
      apiserver/service/job.go
  45. 551 0
      apiserver/service/liugong.go
  46. 98 1
      apiserver/service/material.go
  47. 4 3
      apiserver/service/order.go
  48. 44 4
      apiserver/service/proof.go
  49. 32 1
      apiserver/service/purchase.go
  50. 122 16
      apiserver/service/report.go
  51. 0 1
      apiserver/service/sap.go
  52. 2 0
      apiserver/service/service.go
  53. 229 0
      apiserver/service/stock.go
  54. BIN
      cmd/sh/eqserver
  55. BIN
      dist.zip
  56. 0 0
      dist/datas/myMap.json
  57. BIN
      dist/favicon.ico
  58. 0 0
      dist/index.html
  59. 0 0
      dist/static/css/app.a70a2a2f.css
  60. 0 0
      dist/static/css/chunk-elementUI.45ab9bc1.css
  61. 0 0
      dist/static/css/chunk-libs.2e418612.css
  62. BIN
      dist/static/fonts/element-icons.535877f5.woff
  63. BIN
      dist/static/fonts/element-icons.732389de.ttf
  64. BIN
      dist/static/img/1.1ddf085a.png
  65. BIN
      dist/static/img/404.a57b6f31.png
  66. BIN
      dist/static/img/404_cloud.0f4bc32b.png
  67. BIN
      dist/static/img/cow.3495de2a.jpg
  68. BIN
      dist/static/img/login-bg.dfe7c90f.jpg
  69. BIN
      dist/static/img/login-bg1.1f1602f0.jpg
  70. BIN
      dist/static/img/login-bujian.8695940d.png
  71. BIN
      dist/static/img/logo.4a74cb8a.png
  72. BIN
      dist/static/img/logo1.d2343c0f.png
  73. BIN
      dist/static/img/logo_u3.34a9ffae.png
  74. 0 0
      dist/static/js/app.6e59e529.js
  75. 0 0
      dist/static/js/chunk-39889fb2.0f71ae7a.js
  76. 0 0
      dist/static/js/chunk-581b2547.c1efae40.js
  77. 0 0
      dist/static/js/chunk-d17f893e.56c4d12d.js
  78. 0 0
      dist/static/js/chunk-elementUI.1e8908f6.js
  79. 0 0
      dist/static/js/chunk-libs.f5a7c3c5.js
  80. 2 1
      go.mod
  81. 6 0
      go.sum
  82. 167 37
      middleware/jwt/jwt.go
  83. 6 0
      pkg/http/http.go
  84. 10 0
      pkg/setting/setting.go
  85. 37 22
      pkg/util/mail.go
  86. 83 0
      pkg/util/util.go
  87. 13 2
      pkg/util/wxwork.go
  88. 51 0
      sap.sql

+ 10 - 2
apiserver/config/config.go

@@ -21,9 +21,17 @@ type Http struct {
 	SrmPwd  string        `toml:"srmpwd"`
 	Routing string        `toml:"routing"`
 }
+
+type LiuGong struct {
+	UserName string `toml:"username"`
+	PassWord string `toml:"password"`
+	Routing  string `toml:"routing"`
+}
+
 type Config struct {
-	DB   *MySQLConfig `toml:"db"`
-	Http *Http        `toml:"http"`
+	DB      *MySQLConfig `toml:"db"`
+	Http    *Http        `toml:"http"`
+	LiuGong *LiuGong     `toml:"liugong"`
 }
 type MySQLConfig struct {
 	DSN         string        `toml:"dsn"`

+ 2 - 3
apiserver/model/bigpartpurchase.go

@@ -1,7 +1,6 @@
 package model
 
 import (
-	"fmt"
 	modernPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/xdmy"
 	"time"
 )
@@ -48,10 +47,10 @@ func NewBigPartPurchase(pastureId, departmentId, employeeId, providerId, funderI
 ) *BigPartPurchase {
 	var statue int32 = 2
 	if purchaseType == modernPb.PurchaseType_Complimentary_Item {
-		statue = 7
+		statue = 13
 	}
 
-	createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", createdTime), Location)
+	createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", createdTime, Location)
 	return &BigPartPurchase{
 		PastureId:      pastureId,
 		OrderNumber:    orderNumber,

+ 3 - 0
apiserver/model/emp.go

@@ -4,6 +4,9 @@ type Emp struct {
 	Id        int64  `gorm:"column:id"`
 	Empname   string `gorm:"column:empname"`
 	PastureId string `gorm:"column:pastureId"`
+	EmpCode   string `gorm:"column:empCode"`
+	//Enable    int    `gorm:"column:enable"`
+	Work int `gorm:"column:work"`
 }
 
 func (t Emp) TableName() string {

+ 11 - 0
apiserver/model/ensiling.go

@@ -1 +1,12 @@
 package model
+
+type Ensiling struct {
+	ID        int    `gorm:"column:id"  json:"id"`
+	Code      string `gorm:"column:code" json:"code"`
+	Describe  string `gorm:"column:describe" json:"describe"`
+	PastureId string `gorm:"column:pastureId" json:"pastureId"`
+}
+
+func (t Ensiling) TableName() string {
+	return "ensiling"
+}

+ 11 - 1
apiserver/model/equipment.go

@@ -66,5 +66,15 @@ type Equipment struct {
 	ProfitCenter string    `gorm:"column:profitCenter" json:"profitCenter"`
 	SonCode      string    `gorm:"column:sonCode" json:"sonCode"`
 
-	SapCode string `gorm:"column:sapCode" json:"sapCode"`
+	SapCode    string `gorm:"column:sapCode" json:"sapCode"`
+	License    string `gorm:"column:license" json:"license"`
+	Duration   int    `gorm:"column:duration" json:"duration"`
+	PushStatus int    `gorm:"column:pushStatus" json:"pushStatus"`
+	WorkClass  string `gorm:"column:work" json:"work"`
+}
+
+type EquipmentAndDepartment struct {
+	Equipment  `xorm:"extends"`
+	Department `xorm:"extends"`
+	EqClass    `xorm:"extends"`
 }

+ 5 - 0
apiserver/model/feedsum.go

@@ -12,3 +12,8 @@ type FeedSum struct {
 func (t *FeedSum) TableName() string {
 	return "feed_sum"
 }
+
+type FeedSumAndPasture struct {
+	FeedSum `xorm:"extends"`
+	Pasture `xorm:"extends"`
+}

+ 5 - 0
apiserver/model/feequery.go

@@ -15,3 +15,8 @@ type FeeQuery struct {
 func (t *FeeQuery) TableName() string {
 	return "feequery"
 }
+
+type FeeQueryAndPasture struct {
+	FeeQuery `xorm:"extends"`
+	Pasture  `xorm:"extends"`
+}

+ 7 - 3
apiserver/model/home/home.go

@@ -4,12 +4,16 @@ type MonthBudget struct {
 	MonthBudget float64 `gorm:"column:monthBudget"`
 	FeeType     string  `gorm:"column:feeType"`
 	Center      string  `gorm:"column:center"`
+	PastureId   int     `gorm:"column:pastureId"`
+	DeptId      int     `gorm:"column:deptId"`
 }
 
 type ThisYearActual struct {
-	SumPrice float64 `gorm:"column:sumPrice"`
-	FeeType  string  `gorm:"column:feeType"`
-	Center   string  `gorm:"column:center"`
+	SumPrice     float64 `gorm:"column:sumPrice"`
+	FeeType      string  `gorm:"column:feeType"`
+	Center       string  `gorm:"column:center"`
+	PastureId    int     `gorm:"column:pastureId"`
+	DepartmentId int     `gorm:"column:departmentId"`
 }
 
 type GetExpenseResp struct {

+ 8 - 5
apiserver/model/http/asset.go

@@ -8,16 +8,17 @@ type AssetRespData struct {
 	RespMsg SapRespMsg `json:"MSGER"`
 	Master  []Asset    `json:"TANLA"`
 }
+
 type Asset struct {
 	CompanyCode string `json:"BUKRS"` //公司代码
 	SonCode     string `json:"ANLN2"` //资产子编号  默认0
 	Quantity    string `json:"MENGE"` //数量
 
-	Name      string `json:"TXT50"` //资产名称
-	AssetCode string `json:"ANLN1"` //资产编码
-	Type      string `json:"ANLKL"` //资产类型
-	Model     string `json:"TXA50"` //资产规格
-	//CostCenter string `json:"KOSTL"` //成本中心
+	Name       string `json:"TXT50"`  //资产名称
+	AssetCode  string `json:"ANLN1"`  //资产编码
+	Type       string `json:"ANLKL"`  //资产类型
+	Model      string `json:"TXA50"`  //资产规格
+	KOSTL      string `json:"KOSTL"`  //成本中心
 	CostCenter string `json:"KOSTLV"` //责任成本中心
 
 	Unit             string `json:"MEINS"` //计量单位
@@ -37,6 +38,8 @@ type Asset struct {
 	Segment string `json:"SEGMENT"` //细分	段
 	ORD42   string `json:"ORD42"`   //资产变动方式	出售/购入/其他/其他减少/其他增加/调拨/在建工程转入
 	RAUMN   string `json:"RAUMN"`   //房间	存储资产的位置
+	ZUSAGE  string `json:"ZUSAGE"`  // 用途
+	ZSELFNB string `json:"ZSELFNB"` // 自编号
 }
 
 type AssetReq struct {

+ 22 - 0
apiserver/model/http/chart.go

@@ -1 +1,23 @@
 package http
+
+type StatementResp struct {
+	Pasture  []string  `json:"pasture"`
+	NowYear  []float64 `json:"nowYear"`
+	LastYear []float64 `json:"lastYear"`
+	All      float64   `json:"all"`
+	Line     float64   `json:"line"`
+}
+
+type GetWaterRateByPastureResp struct {
+	Pasture []string  `json:"pasture"`
+	Actual  []float64 `json:"actual"`
+	Line    float64   `json:"line"`
+}
+
+type GetWaterRateCompleteByPastureResp struct {
+	Pasture  []string  `json:"pasture"`
+	Actual   []float64 `json:"actual"`
+	Budget   []float64 `json:"budget"`
+	Complete []float64 `json:"complete"`
+	Line     float64   `json:"line"`
+}

+ 30 - 0
apiserver/model/http/equipment.go

@@ -1 +1,31 @@
 package http
+
+type EquipmentIndexResp struct {
+	EquipmentIndex         []*EquipmentIndex        `json:"equipmentList"`          //设备指标
+	ChooseMonthWX          []*EquipmentIndex        `json:"chooseMonthWX"`          //维修
+	ChooseWaterPrice       []*EquipmentIndex        `json:"chooseWaterPrice"`       //水
+	ChooseElectricityPrice []*EquipmentIndex        `json:"chooseElectricityPrice"` //电
+	ChooseMonthiolPrice    []*EquipmentIndex        `json:"chooseMonthiolPrice"`    //柴油
+	LgnitionChargePrice    []*EquipmentIndex        `json:"lgnitionChargePrice"`    //燃动费
+	DosageIndex            []map[string]interface{} `json:"dosageIndex"`            //水电柴油用量
+}
+
+type EquipmentIndex struct {
+	PastureName    string  `json:"pastureName"`
+	PastureId      int     `json:"pastureId"`
+	DeptName       string  `json:"deptname"`
+	Center         string  `json:"center"`
+	MonthBudget    float64 `json:"monthBudget"`    //预算
+	QmonthBudget   float64 `json:"qmonthBudget"`   //迄今预算
+	SumPrice       float64 `json:"sumPrice"`       //迄今实际
+	Asave          float64 `json:"asave"`          //实际节约
+	RealReason     string  `json:"realReason"`     //实际达成率
+	OneCowSumPrice float64 `json:"oneCowSumPrice"` //单头牛的迄今实际
+	CowSum         int64   `json:"cowSum"`         //饲养头数
+}
+
+type DosageIndex struct {
+	PastureName string  `gorm:"column:pastureName"`
+	PastureId   int     `gorm:"column:pastureId"`
+	SumPrice    float64 `gorm:"column:sumPrice"`
+}

+ 3 - 2
apiserver/model/http/feequery.go

@@ -23,16 +23,17 @@ type TFYLX struct {
 }
 
 type FeeQueryResp struct {
-	Dest Dest         `json:"DEST"`
+	Dest *Dest `json:"DEST"`
+	//Data *FeeQueryDate `json:"DATA"`
 	Data FeeQueryDate `json:"DATA"`
 }
 type FeeQueryDate struct {
 	Items []*SapITEMS `json:"ITEMS"`
 }
 type SapITEMS struct {
+	FYLX   string `json:"FYLX"`
 	RBUKRS string `json:"RBUKRS"`
 	WERKS  string `json:"WERKS"`
-	FYLX   string `json:"FYLX"`
 	GJAHR  string `json:"GJAHR"`
 	POPER  string `json:"POPER"`
 	HSL    string `json:"HSL"`

+ 9 - 6
apiserver/model/http/http.go

@@ -1,10 +1,13 @@
 package http
 
 type Response struct {
-	Success bool        `json:"success"`
-	
-	Code    int         `json:"code"`
-	Message string      `json:"message"`
-	Data    interface{} `json:"data"`
-	Msg     string      `json:"msg"`
+	Success bool `json:"success"`
+
+	Code      int         `json:"code"`
+	Message   string      `json:"message"`
+	Data      interface{} `json:"data"`
+	Msg       string      `json:"msg"`
+	Count     int64       `json:"count"`
+	Offset    int         `json:"offset"`
+	PageCount int         `json:"pageCount"`
 }

+ 37 - 0
apiserver/model/http/oauth2token.go

@@ -1 +1,38 @@
 package http
+
+type OAuth2TokenResp struct {
+	AccessToken  string `json:"access_token"`  // 授权令牌
+	ExpiresIn    int64  `json:"expires_in"`    // 授权令牌的有效期
+	RefreshToken string `json:"refresh_token"` // 刷新令牌
+	TokenType    string `json:"token_type"`    // 令牌类型
+	Scope        string `json:"scope"`         // 授权范围
+}
+
+type OAuth2AddUserReq struct {
+	Data      string `json:"data"`
+	EventType string `json:"eventType"`
+}
+
+type OAuth2AddUser struct {
+	Id       string `json:"id"`
+	Username string `json:"username"`
+	Name     string `json:"name"`
+	UserId   string `json:"userId"`
+	PassWord string `json:"password"`
+	Disabled bool   `json:"disabled"`
+	Pasture  string `json:"pasture"`
+	//	OrganizationId  string   `json:"organizationId"`
+	//	OrganizationIds []string `json:"organizationIds"`
+	//	Disabled        bool     `json:"disabled"`
+	//	Number          int      `json:"number"`
+	//	Switch          bool     `json:"switch"`
+	//	Text            string   `json:"text"`
+	//	MultivaluedText []string `json:"multivaluedText"`
+}
+
+//type T struct {
+//	Data      string `json:"data"`
+//	EventType string `json:"eventType"`
+//	Nonce     string `json:"nonce"`
+//	Timestamp int64  `json:"timestamp"`
+//}

+ 6 - 1
apiserver/model/http/order.go

@@ -115,5 +115,10 @@ type ManaulReq struct {
 
 type SapContractReq struct {
 	*Dest `json:"DEST"`
-	DATA  *ContractDataToASP `json:"DATA"`
+	DATA  []*ContractDataToASP `json:"DATA"`
+	//DATA *ContractDataToASP `json:"DATA"`
 }
+
+//type SapContractTtemReq struct {
+//	Item []*ContractDataToASP `json:"item"`
+//}

+ 8 - 0
apiserver/model/http/sap.go

@@ -30,6 +30,7 @@ type SapRespMsg struct {
 type SapContractResp struct {
 	Dest `json:"DEST"`
 	Data SapContractRespMsg `json:"DATA"`
+	//Data interface{} `json:"DATA"`
 }
 
 type SapContractRespMsg struct {
@@ -88,4 +89,11 @@ type ContractDataToASP struct {
 	MEINS        string `json:"MEINS"` // 订单价格单位
 	Code         string `json:"Code"`
 	PurchaseInfo string `json:"PurchaseInfo"`
+	RCKEY        string `json:"RCKEY"` //行号
+}
+
+type PostPushContractDataToSAPReq struct {
+	PastureId      int64   `json:"pastureId"`
+	ProviderId     int64   `json:"providerId"`
+	ContractIdList []int64 `json:"contractIdList"`
 }

+ 93 - 0
apiserver/model/liugong/register.go

@@ -1 +1,94 @@
 package liugong
+
+//
+//type RegisterLG struct {
+//	UserName string `json:"username"`
+//	PassWord string `json:"password"`
+//}
+//
+//type RegisterLGResp struct {
+//	Status string `json:"status"`
+//	Msg    string `json:"msg"`
+//	Token  string `json:"token"`
+//}
+//
+//type PushEquipmentInfoReq struct {
+//	EquipmentList []*PushEquipmentInfo `json:"equipmentList"`
+//}
+//
+//func (p PushEquipmentInfoReq) Validate() bool {
+//	return true
+//}
+//
+//type PushEquipmentInfo struct {
+//	License               string  `json:"license"`               //机号
+//	WorkHour              float64 `json:"workHour"`              //累计开机时间
+//	IdleHour              float64 `json:"idleHour"`              //累计怠速小时(H) -- 仅柴油装载机有值
+//	FuelConsumption       float64 `json:"fuelConsumption"`       //累计油耗(L)
+//	IdleFuel              float64 `json:"idleFuel"`              //累计怠速油耗(H) -- 仅柴油装载机有值
+//	HoursConsumption      float64 `json:"hoursConsumption"`      //平均油耗(L/H)
+//	Longitude             float64 `json:"longitude"`             //经度
+//	Latitude              float64 `json:"latitude"`              //纬度
+//	FuelLevel             float64 `json:"fuelLevel"`             //油位(%)
+//	Date                  string  `json:"dataTime"`              //时间
+//	PowerConsumption      float64 `json:"powerConsumption"`      //  累计耗电量(Kwh)- 电动设备数据
+//	HoursPowerConsumption float64 `json:"hoursPowerConsumption"` //  平均耗电量(Kwh/h)-电动设备数据
+//	ChargeCapacity        float64 `json:"chargeCapacity"`        //  累计充电量(Kwh)- 电动设备数据
+//	ChargeHour            float64 `json:"chargeHour"`            //  累计充电时长(H)- 电动设备数据
+//	ChargeStatus          string  `json:"chargeStatus"`          //  未充电/充电中/充电完成/充电错误(电动设备数据)
+//	BatteryPackSoc        float64 `json:"batteryPackSoc"`        //  电池包 SOC(%) - 电动设备数据
+//}
+//
+//type LiuGongToken struct {
+//	Token      string    `gorm:"column:token" json:"token"`
+//	UpdateDate time.Time `gorm:"column:updatedate" json:"updatedate"`
+//}
+//
+//func (b *LiuGongToken) TableName() string {
+//	return "liugong"
+//}
+
+//type Vehicle struct {
+//	Id int64 `gorm:"column:id" json:"id"`
+//	//EqId                    int64   `gorm:"column:eqId" json:"eqId"`
+//	//EqCode                  string  `gorm:"column:eqCode" json:"eqCode"`
+//	//PastureId               int     `gorm:"column:pastureId" json:"pastureId"`
+//	License                 string  `gorm:"column:license" json:"license"`                                 //机号
+//	WorkHour                float64 `gorm:"column:workHour" json:"workHour"`                               //累计开机时间
+//	IdleHour                float64 `gorm:"column:idleHour" json:"idleHour"`                               //累计怠速小时(H) -- 仅柴油装载机有值
+//	FuelConsumption         float64 `gorm:"column:fuelConsumption" json:"fuelConsumption"`                 //累计油耗(L)
+//	IdleFuel                float64 `gorm:"column:idleFuel" json:"idleFuel"`                               //累计怠速油耗(H) -- 仅柴油装载机有值
+//	HoursConsumption        float64 `gorm:"column:hoursConsumption" json:"hoursConsumption"`               //平均油耗(L/H)
+//	Longitude               float64 `gorm:"column:longitude" json:"longitude"`                             //经度
+//	Latitude                float64 `gorm:"column:latitude" json:"latitude"`                               //纬度
+//	FuelLevel               float64 `gorm:"column:fuelLevel" json:"fuelLevel"`                             //油位(%)
+//	Date                    string  `gorm:"column:dataTime" json:"dataTime"`                               //时间
+//	CurrentWorkHour         float64 `gorm:"column:currentWorkHour" json:"currentWorkHour"`                 //当前开机时间
+//	CurrentIdleHour         float64 `gorm:"column:currentIdleHour" json:"currentIdleHour"`                 //当前怠速小时(H) -- 仅柴油装载机有值
+//	CurrentFuelConsumption  float64 `gorm:"column:currentFuelConsumption" json:"currentFuelConsumption"`   //当前油耗(L)
+//	CurrentIdleFuel         float64 `gorm:"column:currentIdleFuel" json:"currentIdleFuel"`                 //当前怠速油耗(H) -- 仅柴油装载机有值
+//	PowerConsumption        float64 `gorm:"column:powerConsumption" json:"powerConsumption"`               //  累计耗电量(Kwh)- 电动设备数据
+//	HoursPowerConsumption   float64 `gorm:"column:hoursPowerConsumption" json:"hoursPowerConsumption"`     //  平均耗电量(Kwh/h)-电动设备数据
+//	ChargeCapacity          float64 `gorm:"column:chargeCapacity" json:"chargeCapacity"`                   //  累计充电量(Kwh)- 电动设备数据
+//	ChargeHour              float64 `gorm:"column:chargeHour" json:"chargeHour"`                           //  累计充电时长(H)- 电动设备数据
+//	ChargeStatus            string  `gorm:"column:chargeStatus" json:"chargeStatus"`                       //  未充电/充电中/充电完成/充电错误(电动设备数据)
+//	BatteryPackSoc          float64 `gorm:"column:batteryPackSoc" json:"batteryPackSoc"`                   //  电池包 SOC(%) - 电动设备数据
+//	CurrentPowerConsumption float64 `gorm:"column:currentPowerConsumption" json:"currentPowerConsumption"` //  当前耗电量(Kwh)- 电动设备数据
+//	CurrentChargeCapacity   float64 `gorm:"column:currentChargeCapacity" json:"currentChargeCapacity"`     //  当前充电量(Kwh)- 电动设备数据
+//	CurrentChargeHour       float64 `gorm:"column:currentChargeHour" json:"currentChargeHour"`             //  当前充电时长(H)- 电动设备数据
+//	//CurrentBatteryPackSoc   float64 `json:"currentBatteryPackSoc"`   //  电池包 SOC(%) - 电动设备数据
+//}
+
+//type GetVehicleListReq struct {
+//	PastureId string `json:"pastureId"`
+//	StartTime string `json:"startTime"`
+//	EndTime   string `json:"endTime"`
+//	Offset    int    `json:"offset"`
+//	PageCount int    `json:"pageCount"`
+//}
+//
+//type VehicleAndPasture struct {
+//	Vehicle         `xorm:"extends"`
+//	model.Pasture   `xorm:"extends"`
+//	model.Equipment `xorm:"extends"`
+//}

+ 88 - 0
apiserver/model/liugong/vehicle.go

@@ -1 +1,89 @@
 package liugong
+
+type VehicleInfo struct {
+	OperationName  string `json:"operateCenterCode"` //运营中心
+	AreaName       string `json:"areaCode"`          //大区
+	RancheName     string `json:"ranchCode"`         //牧场
+	VehicleType    string `json:"vehicleType"`       //设备类别
+	VehicleName    string `json:"vehicleName"`
+	VehicleLicense string `json:"vehicleLicense"` //设备内部编号
+	DeviceLicense  string `json:"deviceCode"`     //物联网编码
+	Specification  string `json:"specification"`  //规格
+	Brand          string `json:"vehicleBrand"`   //品牌
+	Usage          string `json:"vehicleUsage"`   //用途
+	DeptName       string `json:"ranchDeptName"`  //部门
+	PurchaseDate   string `json:"purchaseDate"`   //购置日期
+	EnterDate      string `json:"enterDate"`      //入场时间
+	ScrapDate      string `json:"scrapDate"`      //报废时间
+	StandardHour   int    `json:"standardHour"`   //标准工作时长
+	Status         int    `json:"vehicleStatus"`  //状态
+	WorkClass      string `json:"workClass"`      //工作类别
+}
+
+type Vehicle struct {
+	Id             int     `gorm:"column:id" json:"id"`
+	PastureId      int     `gorm:"column:pastureId" json:"pastureId"`
+	PastureName    string  `gorm:"column:pastureName" json:"pastureName"`
+	Date           string  `gorm:"column:date" json:"date"`
+	EqId           string  `gorm:"column:eqId" json:"eqId"`
+	EqCode         string  `gorm:"column:eqCode" json:"eqCode"`
+	Hour           string  `gorm:"column:hour" json:"hour"`
+	EqClass        string  `gorm:"column:eqClass" json:"eqClass"`
+	EqName         string  `gorm:"column:eqName" json:"eqName"`
+	License        string  `gorm:"column:license" json:"license"`
+	Specification  string  `gorm:"column:specification" json:"specification"`
+	Purpose        string  `gorm:"column:purpose" json:"purpose"`
+	PurchaseDate   string  `gorm:"column:purchaseDate" json:"purchaseDate"`
+	EntranceDate   string  `gorm:"column:entranceDate" json:"entranceDate"`
+	LeaveDate      string  `gorm:"column:leaveDate" json:"leaveDate"`
+	Duration       float64 `gorm:"column:duration" json:"duration"`
+	DepartmentName string  `gorm:"column:departmentName" json:"departmentName"`
+}
+
+func (b *Vehicle) TableName() string {
+	return "vehicle"
+}
+
+type EditVehicleReq struct {
+	RanchName      string `json:"ranchName"`
+	Date           string `json:"date"`
+	VehicleLicense string `json:"vehicleLicense"`
+	WorkHour       string `json:"workHour"`
+}
+
+type VientianeResp struct {
+	Code   int    `json:"code"`
+	Status int    `json:"status"`
+	Error  string `json:"error"`
+	Msg    string `json:"msg"`
+}
+
+type GetVehicleResp struct {
+	Count       int64          `json:"count"`
+	VehicleList []*VehicleResp `json:"vehicle"`
+	Offset      int            `json:"offset"`
+	PageCount   int            `json:"pagecount"`
+}
+
+type VehicleResp struct {
+	Id             int     `gorm:"column:id" json:"id"`
+	PastureId      int     `gorm:"column:pastureId" json:"pastureId"`
+	PastureName    string  `gorm:"column:pastureName" json:"pastureName"`
+	Date           string  `gorm:"column:date" json:"date"`
+	EqId           string  `gorm:"column:eqId" json:"eqId"`
+	EqCode         string  `gorm:"column:eqCode" json:"eqCode"`
+	Hour           string  `gorm:"column:hour" json:"hour"`
+	EqClass        string  `gorm:"column:eqClass" json:"eqClass"`
+	EqName         string  `gorm:"column:eqName" json:"eqName"`
+	Brand          string  `gorm:"column:brand" json:"brand"`
+	License        string  `gorm:"column:license" json:"license"`
+	Specification  string  `gorm:"column:specification" json:"specification"`
+	Purpose        string  `gorm:"column:purpose" json:"purpose"`
+	PurchaseDate   string  `gorm:"column:purchaseDate" json:"purchaseDate"`
+	EntranceDate   string  `gorm:"column:entranceDate" json:"entranceDate"`
+	LeaveDate      string  `gorm:"column:leaveDate" json:"leaveDate"`
+	Duration       float64 `gorm:"column:duration" json:"duration"`
+	DepartmentName string  `gorm:"column:departmentName" json:"departmentName"`
+	Region         string  `gorm:"column:region" json:"region"`
+	Center         string  `gorm:"column:center" json:"center"`
+}

+ 57 - 17
apiserver/model/partpurchase.go

@@ -1,22 +1,29 @@
 package model
 
 type PartPurchase struct {
-	Id            int64   `gorm:"column:id"`
-	BigId         int64   `gorm:"column:bigId"`
-	PastureId     int64   `gorm:"column:pastureId"`
-	PartId        int64   `gorm:"column:partId"`
-	PartName      string  `gorm:"column:partName"`
-	PartCode      string  `gorm:"column:partCode"`
-	Amount        int64   `gorm:"column:amount"`
-	Note          string  `gorm:"column:note"`
-	IsStorage     int32   `gorm:"column:isStorage"`
-	Specification string  `gorm:"column:specification"`
-	Purpose       string  `gorm:"column:purpose"`
-	Unit          string  `gorm:"column:unit"`
-	BrandId       int64   `gorm:"column:brandId"`
-	StorageAmount float64 `gorm:"column:storageAmount"`
-	Price         string  `gorm:"column:price"`
-	ContractId    string  `gorm:"column:contractId"`
+	Id                   int64   `gorm:"column:id"`
+	BigId                int64   `gorm:"column:bigId"`
+	PastureId            int64   `gorm:"column:pastureId"`
+	PartId               int64   `gorm:"column:partId"`
+	PartName             string  `gorm:"column:partName"`
+	PartCode             string  `gorm:"column:partCode"`
+	Amount               int64   `gorm:"column:amount"`
+	Note                 string  `gorm:"column:note"`
+	IsStorage            int32   `gorm:"column:isStorage"`
+	Specification        string  `gorm:"column:specification"`
+	Purpose              string  `gorm:"column:purpose"`
+	Unit                 string  `gorm:"column:unit"`
+	BrandId              int64   `gorm:"column:brandId"`
+	StorageAmount        float64 `gorm:"column:storageAmount"`
+	Price                string  `gorm:"column:price"`
+	ContractId           string  `gorm:"column:contractId"`
+	LifeCycle            string  `gorm:"column:lifeCycle"`
+	ContractVarianceItem string  `gorm:"column:contractVarianceItem"`
+	Reject               string  `gorm:"column:reject"`
+	DepartmentId         string  `gorm:"column:departmentId"`
+	Explain              string  `gorm:"column:explain"`
+	Date                 string  `gorm:"column:date"`
+	EmployeId            int64   `gorm:"column:employeId"`
 }
 
 func (p *PartPurchase) TableName() string {
@@ -26,7 +33,12 @@ func (p *PartPurchase) TableName() string {
 func NewPartPurchase(
 	bigId, pastureId, partId, brandId, amount int64,
 	contractId, partCode, partName, specification, unit, purpose, price string,
-	storageAmount float64,
+	storageAmount float64, departmentId, date string, employeId int64,
+
+	//func NewPartPurchase(
+	//	bigId, pastureId, partId, brandId, amount int64,
+	//	contractId, partCode, partName, specification, unit, purpose, price string,
+	//	storageAmount float64,
 ) *PartPurchase {
 	return &PartPurchase{
 		BigId:         bigId,
@@ -44,5 +56,33 @@ func NewPartPurchase(
 		StorageAmount: storageAmount,
 		Price:         price,
 		ContractId:    contractId,
+		Reject:        "0",
+		DepartmentId:  departmentId,
+		Date:          date,
+		EmployeId:     employeId,
 	}
 }
+
+type EditPartpurchaseReq struct {
+	Id                   int64   `json:"id"`
+	BigId                int64   `json:"bigId"`
+	PastureId            int64   `json:"pastureId"`
+	PartId               int64   `json:"partId"`
+	PartCode             string  `json:"partCode"`
+	PartName             string  `json:"partName"`
+	Specification        string  `json:"specification"`
+	Amount               int64   `json:"amount"`
+	Unit                 string  `json:"unit"`
+	BrandId              int64   `json:"brandId"`
+	Purpose              string  `json:"purpose"`
+	StorageAmount        float64 `json:"storageAmount"`
+	Price                string  `json:"price"`
+	ContractId           string  `json:"contractId"`
+	LifeCycle            string  `json:"lifeCycle"`
+	ContractVarianceItem string  `json:"contractVarianceItem"`
+	Reject               string  `json:"reject"`
+	DepartmentId         string  `json:"departmentId"`
+	Explain              string  `json:"explain"`
+	Date                 string  `json:"date"`
+	EmployeId            int64   `json:"employeId"`
+}

+ 23 - 26
apiserver/model/pasture.go

@@ -2,32 +2,29 @@ package model
 
 type Pasture struct {
 	// 牧场
-	ID         int    `gorm:"column:id" gorm:"column:id" `
-	Address    string `gorm:"column:address"`
-	Center     string `gorm:"column:center"`
-	CenterID   int    `gorm:"column:center_id"`
-	CenterSort int    `gorm:"column:center_sort"`
-
-	EmployeeID      int    `gorm:"column:employeeId"`
-	Enablesync      int    `gorm:"column:enablesync"`
-	IsDel           int    `gorm:"column:isDel"`
-	Latitude        string `gorm:"column:latitude"`
-	Longitude       string `gorm:"column:longitude"`
-	Name            string `gorm:"column:name"`
-	Note            string `gorm:"column:note"`
-	PastureNumber   string `gorm:"column:pastureNumber"`
-	Prcode          string `gorm:"column:prcode"`
-	Region          string `gorm:"column:region"`
-	RegionID        int    `gorm:"column:region_id"`
-	ShortName       string `gorm:"column:shortName"`
-	Sort            int    `gorm:"column:sort"`
-	PurchasingGroup string `gorm:"column:purchasing_group"`
-
-	CompanyCode string `gorm:"column:company_code"` //公司代码
-	CompanyName string `gorm:"column:company_name"` //公司代码
-	FactoryCode string `gorm:"column:factory_code"` //工厂
-	FactoryName string `gorm:"column:factory_name"` //工厂
-
+	ID                   int    `gorm:"column:id" gorm:"column:id" `
+	Address              string `gorm:"column:address"`
+	Center               string `gorm:"column:center"`
+	CenterID             int    `gorm:"column:center_id"`
+	CenterSort           int    `gorm:"column:center_sort"`
+	EmployeeID           int    `gorm:"column:employeeId"`
+	Enablesync           int    `gorm:"column:enablesync"`
+	IsDel                int    `gorm:"column:isDel"`
+	Latitude             string `gorm:"column:latitude"`
+	Longitude            string `gorm:"column:longitude"`
+	Name                 string `gorm:"column:name"`
+	Note                 string `gorm:"column:note"`
+	PastureNumber        string `gorm:"column:pastureNumber"`
+	Prcode               string `gorm:"column:prcode"`
+	Region               string `gorm:"column:region"`
+	RegionID             int    `gorm:"column:region_id"`
+	ShortName            string `gorm:"column:shortName"`
+	Sort                 int    `gorm:"column:sort"`
+	PurchasingGroup      string `gorm:"column:purchasing_group"`
+	CompanyCode          string `gorm:"column:company_code"` //公司代码
+	CompanyName          string `gorm:"column:company_name"` //公司代码
+	FactoryCode          string `gorm:"column:factory_code"` //工厂
+	FactoryName          string `gorm:"column:factory_name"` //工厂
 	ParchaseOrganization string `gorm:"column:parchase_organization"`
 	// PurchasingGroup      string `gorm:"column:purchasing_group"` //采购组
 	// CompanyName   string `gorm:"column:companyName"`

+ 9 - 0
apiserver/model/sso.go

@@ -1 +1,10 @@
 package model
+
+type Sso struct {
+	Code  string `gorm:"column:code" json:"code"`
+	Token string `gorm:"column:token" json:"token"`
+}
+
+func (Sso) TableName() string {
+	return "sso"
+}

+ 79 - 0
apiserver/model/stock.go

@@ -1 +1,80 @@
 package model
+
+//盘点
+type Stock struct {
+	ID            int    `gorm:"column:id" json:"id"`
+	PastureId     int    `gorm:"column:pastureId" json:"pastureId"`
+	DepartmentId  int    `gorm:"column:departmentId" json:"departmentId"`
+	EqId          int    `gorm:"column:eqId" json:"eqId"`
+	RzDate        string `gorm:"column:rzdate" json:"rzdate"`
+	Unit          string `gorm:"column:unit" json:"unit"`
+	Specification string `gorm:"column:specification" json:"specification"`
+	Quantity      string `gorm:"column:quantity" json:"quantity"`
+	Yuanzhi       string `gorm:"column:yuanzhi" json:"yuanzhi"`
+	Count         string `gorm:"column:count" json:"count"`
+	Profit        string `gorm:"column:profit" json:"profit"`
+	Tag           string `gorm:"column:tag" json:"tag"`
+	ImportDate    string `gorm:"column:importdate" json:"importdate"`
+	InventoryDate string `gorm:"column:inventorydate" json:"inventorydate"`
+	CheckTaker    string `gorm:"column:checktaker" json:"checktaker"`
+	Remark        string `gorm:"column:remark" json:"remark"`
+	CreateDate    string `gorm:"column:createdate" json:"createdate"`
+}
+
+func (Stock) TableName() string {
+	return "stock"
+}
+
+type StockAndPasture struct {
+	Stock      `xorm:"extends"`
+	Pasture    `xorm:"extends"`
+	Department `xorm:"extends"`
+	Equipment  `xorm:"extends"`
+	Emp        `xorm:"extends"`
+}
+
+type GetStockListReq struct {
+	PastureId    string `json:"pastureId"`
+	DepartmentId string `json:"departmentId"`
+	Offset       int    `json:"offset"`
+	Pagecount    int    `json:"pagecount"`
+	StartDate    string `json:"startdate"`
+	EndDate      string `json:"enddate"`
+}
+
+type GetStockListResp struct {
+	StockList []*StockInfo `json:"list"`
+	Count     int64        `json:"count"`
+	Offset    int          `json:"offset"`
+	Pagecount int          `json:"pagecount"`
+}
+
+type StockInfo struct {
+	ID             int    `json:"id"`
+	PastureId      int    `json:"pastureId"`
+	PastureName    string `json:"pastureName"`
+	DepartmentId   int    `json:"departmentId"`
+	DepartmentName string `json:"departmentName"`
+	EqId           int    `json:"eqId"`
+	EqCode         string `json:"eqCode"`
+	EqName         string `json:"eqName"`
+	AssetCode      string `json:"assetCode"`
+	RzDate         string `json:"rzdate"`
+	Unit           string `json:"unit"`
+	Specification  string `json:"specification"`
+	Quantity       string `json:"quantity"`
+	Yuanzhi        string `json:"yuanzhi"`
+	Count          string `json:"count"`
+	Profit         string `json:"profit"`
+	Tag            string `json:"tag"`
+	ImportDate     string `json:"importdate"`
+	InventoryDate  string `json:"inventorydate"`
+	CheckTaker     string `json:"checkTaker"`
+	CheckTakerName string `json:"checkTakerName"`
+	Remark         string `json:"remark"`
+	Status         int    `json:"status"` // 0 未盘点 1 已盘点
+}
+
+type DelStockListReq struct {
+	Id []int `json:"id"`
+}

+ 13 - 0
apiserver/model/user.go

@@ -7,3 +7,16 @@ type User struct {
 	EmpName  string `gorm:"column:empname" json:"empname"`
 	PassWord string `gorm:"column:password" json:"password"`
 }
+
+type UserInfo struct {
+	ID       int    `gorm:"column:id" `
+	Username string `gorm:"column:username" json:"username"`
+	Empid    int64  `gorm:"column:empid" json:"empid"`
+	PassWord string `gorm:"column:password" json:"password"`
+	Enable   int    `gorm:"column:enable" json:"enable"`
+	Idaas    string `gorm:"column:idaas" json:"idaas"`
+}
+
+func (UserInfo) TableName() string {
+	return "user"
+}

+ 5 - 1
apiserver/routers/api/api.go

@@ -14,6 +14,8 @@ import (
 	"kpt.xdmy/apiserver/model"
 	modelHttp "kpt.xdmy/apiserver/model/http"
 	"kpt.xdmy/apiserver/service"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
 	"kpt.xdmy/pkg/log"
 	"net/http"
 
@@ -213,7 +215,9 @@ func SparePartsRequisitions(c *gin.Context) {
 	}
 
 	if err := service.CreateSpecialtyPurchase(c, &req); err != nil {
-		apierr.ClassifiedAbort(c, err)
+		//apierr.ClassifiedAbort(c, err)
+		appG := app.Gin{C: c}
+		appG.Response(200, e.ERROR, err.Error())
 		return
 	}
 

+ 222 - 109
apiserver/routers/api/db.go

@@ -1088,7 +1088,7 @@ func getEqRunSurveyListPasture(sqlnamestr string, parammaps *gofasion.Fasion) (m
 
 	chartData["pastureName"] = pasture
 	chartData["eqUseRate"] = eqUse
-	//chartData["eqSum"] = eqSum
+	//chartData["eqS.m"] = eqSum
 	chartData["eqXZRate"] = eqXZ
 	chartData["eqBFRate"] = eqBF
 	chartData["eqFCRate"] = eqFC
@@ -1133,12 +1133,13 @@ func geteqclassFeeSum(sqlnamestr string, parammaps *gofasion.Fasion) (map[string
 }
 func geteqclassSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
 	queryData := make(map[string]interface{})
-	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	//receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
 	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
 	deptName := parammaps.Get(strings.Trim("deptName", " ")).ValueStr()
-
+	startTime := parammaps.Get(strings.Trim("startTime", " ")).ValueStr()
+	//endTime := parammaps.Get(strings.Trim("endTime", " ")).ValueStr()
 	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
-	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime, deptName)
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, startTime, deptName)
 	if len(pSumNow) == 0 {
 		log.Default().Printf("geteqclassSumMonth  result is empty")
 	}
@@ -1159,7 +1160,7 @@ func geteqclassSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[stri
 }
 func getPastureSumDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
 	queryData := make(map[string]interface{})
-	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	receiveTime := parammaps.Get(strings.Trim("startTime", " ")).ValueStr()
 	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
 
 	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
@@ -1172,49 +1173,60 @@ func getPastureSumDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string
 	pSumLast, _ := restful.MapStrList(sqlNow, pastureNames, receiveTimetemp)
 	chartData := make(map[string]interface{})
 	months := []string{}
-	lastYear := []string{}
-	nowYear := []string{}
+	var lastYearList, nowYearList []interface{}
+
 	//lastTotal,nowTotal := 0,0
 	a, b := true, true
-	month := ""
+	pastureNameList := strings.Split(pastureNames, ",")
 	dayCount := GetMonthCount(receiveTime)
 	for i := 1; i <= dayCount; i++ {
-		if i < 10 {
-			month = receiveTime + "-0" + strconv.Itoa(i)
-		} else {
-			month = receiveTime + "-" + strconv.Itoa(i)
-		}
 		months = append(months, strconv.Itoa(i))
-		for _, va := range pSumNow {
-			if va["month"][8:] == month[8:] {
-				nowYear = append(nowYear, va["psum"])
-				a = false
+	}
+
+	for _, pastureName := range pastureNameList {
+		month := ""
+		var nowYear, lastYear []string
+		for i := 1; i <= dayCount; i++ {
+			if i < 10 {
+				month = receiveTime + "-0" + strconv.Itoa(i)
+			} else {
+				month = receiveTime + "-" + strconv.Itoa(i)
 			}
-		}
-		for _, va := range pSumLast {
-			if va["month"][8:] == month[8:] {
-				lastYear = append(lastYear, va["psum"])
-				b = false
+			//months = append(months, strconv.Itoa(i))
+
+			for _, va := range pSumNow {
+				if va["month"][8:] == month[8:] && pastureName == va["name"] {
+					nowYear = append(nowYear, va["psum"])
+					a = false
+				}
 			}
-		}
-		if a {
-			if month[:] > time.Now().Format("2006-01-02") {
-				nowYear = append(nowYear, "")
-			} else {
-				nowYear = append(nowYear, "0")
+			for _, va := range pSumLast {
+				if va["month"][8:] == month[8:] && pastureName == va["name"] {
+					lastYear = append(lastYear, va["psum"])
+					b = false
+				}
 			}
+			if a {
+				if month[:] > time.Now().Format("2006-01-02") {
+					nowYear = append(nowYear, "")
+				} else {
+					nowYear = append(nowYear, "0")
+				}
 
+			}
+			if b {
+				lastYear = append(lastYear, "0")
+			}
+			a = true
+			b = true
 		}
-		if b {
-			lastYear = append(lastYear, "0")
-		}
-		a = true
-		b = true
+		nowYearList = append(nowYearList, nowYear)
+		lastYearList = append(lastYearList, lastYear)
 	}
 	chartData["day"] = months
-
-	chartData["lastYear"] = lastYear
-	chartData["nowYear"] = nowYear
+	chartData["pastureName"] = pastureNameList
+	chartData["lastYear"] = lastYearList
+	chartData["nowYear"] = nowYearList
 	queryData["chart_data"] = chartData
 	queryData["code"] = 0
 	queryData["message"] = "ok"
@@ -1307,68 +1319,125 @@ func GetMonthCount(receiveTime string) (days int) {
 }
 func getPastureSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
 	queryData := make(map[string]interface{})
-	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	startTime := parammaps.Get(strings.Trim("startTime", " ")).ValueStr()
+	endTime := parammaps.Get(strings.Trim("endTime", " ")).ValueStr()
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	//enddate = enddate.AddDate(0, 1, -1)
+
 	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
 	departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr()
 	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
 	var pSumNow []map[string]string
 	if sqlnamestr == "getPastureSumMonth" {
-		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), departmentName, departmentName, departmentName)
 	} else {
-		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime)
+		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"))
 	}
-	tempTime, _ := strconv.Atoi(receiveTime)
-	receiveTimetemp := strconv.Itoa(tempTime - 1)
+
+	//tempTime, _ := strconv.Atoi(receiveTime)
+	//receiveTimetemp := strconv.Itoa(tempTime - 1)
 	var pSumLast []map[string]string
 	if sqlnamestr == "getPastureSumMonth" {
-		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, startdate.AddDate(-1, 0, 0).Format("2006-01-02"), enddate.AddDate(-1, 0, 0).Format("2006-01-02"), departmentName, departmentName, departmentName)
 	} else {
-		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp)
+		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, startdate.AddDate(-1, 0, 0).Format("2006-01-02"), enddate.AddDate(-1, 0, 0).Format("2006-01-02"))
 	}
 
 	chartData := make(map[string]interface{})
 	months := []string{}
-	lastYear := []string{}
-	nowYear := []string{}
+
 	//lastTotal,nowTotal := 0,0
 	a, b := true, true
+	receiveTime := startdate.Format("2006")
 	month := ""
-	for i := 1; i <= 12; i++ {
+	pastureNameList := strings.Split(pastureNames, ",")
+	fmt.Println(int(startdate.Month()), "+++++++++++++", int(enddate.Month()))
+	for i := int(startdate.Month()); i <= int(enddate.Month()); i++ {
 		if i < 10 {
 			month = receiveTime + "-0" + strconv.Itoa(i)
 		} else {
 			month = receiveTime + "-" + strconv.Itoa(i)
 		}
 		months = append(months, month)
-		for _, va := range pSumNow {
-			if va["month"][5:] == month[5:] {
-				nowYear = append(nowYear, va["psum"])
-				a = false
-			}
-		}
-		for _, va := range pSumLast {
-			if va["month"][5:] == month[5:] {
-				lastYear = append(lastYear, va["psum"])
-				b = false
+	}
+
+	var lastYearList, nowYearList, monthBudgetList []interface{}
+	for _, pastureName := range pastureNameList {
+		lastYear := []string{}
+		nowYear := []string{}
+		for _, month := range months {
+			for _, va := range pSumNow {
+				if va["month"][5:] == month[5:] && pastureName == va["name"] {
+					nowYear = append(nowYear, va["psum"])
+					a = false
+				}
 			}
-		}
-		if a {
-			if month[:] > time.Now().Format("2006-01") {
-				nowYear = append(nowYear, "")
-			} else {
-				nowYear = append(nowYear, "0")
+			for _, va := range pSumLast {
+				if va["month"][5:] == month[5:] && pastureName == va["name"] {
+					lastYear = append(lastYear, va["psum"])
+					b = false
+				}
 			}
+			if a {
+				if month[:] > time.Now().Format("2006-01") {
+					nowYear = append(nowYear, "")
+				} else {
+					nowYear = append(nowYear, "0")
+				}
 
+			}
+			if b {
+				lastYear = append(lastYear, "0")
+			}
+			a = true
+			b = true
 		}
-		if b {
-			lastYear = append(lastYear, "0")
+		lastYearList = append(lastYearList, lastYear)
+		nowYearList = append(nowYearList, nowYear)
+	}
+
+	if sqlnamestr == "getPastureSumMonth" || sqlnamestr == "getPastureSumMonthDiesel" {
+		feeType := ""
+		if sqlnamestr == "getPastureSumMonth" {
+			feeType = "维修费"
+		} else {
+			feeType = "柴油费"
+		}
+		sqlYS := `select ifnull(sum(monthBudget),0) psum,p.name,mb.budgetMonth month1  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = ? and mb.budgetMonth between ? and ?   and p.name  = ?  group by  mb.budgetMonth,mb.pastureId`
+		monthBudget, _ := restful.MapStrList(sqlYS, feeType, startdate.Format("2006-01"), enddate.Format("2006-01"), pastureNames)
+		for _, pastureName := range pastureNameList {
+			nowMonthBudget := []string{}
+			for _, month := range months {
+				a := true
+				for _, va := range monthBudget {
+					if va["month1"] == month && pastureName == va["name"] {
+						nowMonthBudget = append(nowMonthBudget, va["psum"])
+						a = false
+					}
+				}
+				if a {
+					nowMonthBudget = append(nowMonthBudget, "0")
+				}
+			}
+			monthBudgetList = append(monthBudgetList, nowMonthBudget)
 		}
-		a = true
-		b = true
 	}
+
+	chartData["pastureName"] = pastureNameList
 	chartData["months"] = months
-	chartData["lastYear"] = lastYear
-	chartData["nowYear"] = nowYear
+	chartData["monthBudgetList"] = monthBudgetList
+	chartData["lastYear"] = lastYearList
+	chartData["nowYear"] = nowYearList
 	queryData["chart_data"] = chartData
 	queryData["code"] = 0
 	queryData["message"] = "ok"
@@ -2064,6 +2133,68 @@ func ExecDataByConfig(c *gin.Context) {
 				tempCommon["jwt_username"] = tempv.(string)
 			}
 
+			for _, paramvalue := range tempval {
+				if paramvalue["name"] == "insertBigPartpurchase" {
+					departmentTotal := 0
+					departmentId := paramvalue["parammaps"].(map[string]interface{})["departmentId"]
+					err = restful.BasicList(` select count(1) from department  where id = ?  and name = '挤奶处' `, []interface{}{departmentId}, &departmentTotal)
+					if err != nil {
+						appG.Response(http.StatusOK, e.ERROR, err.Error())
+						return
+					}
+					if departmentTotal == 0 {
+						pastureId := paramvalue["parammaps"].(map[string]interface{})["pastureId"]
+						sql := `SELECT
+	count(1) count 
+FROM
+	bigpartpurchase bp
+	JOIN pasture p
+	on p.id = bp.pastureId 
+WHERE
+	bp.pastureId = ?
+	AND bp.statue < 3 and bp.purchase_type = 0  and createTime >'2024-03-18'  
+and ( select name from department  where id = bp.departmentId) != '挤奶处' order by   bp.id desc   limit 1`
+						total := 0
+						err = restful.BasicList(sql, []interface{}{pastureId}, &total)
+						if err != nil {
+							appG.Response(http.StatusOK, e.ERROR, err.Error())
+							return
+						}
+						if total > 0 {
+							//"单号已生成,请返回开始页面重新申购!"
+							appG.Response(http.StatusOK, e.ERROR, "单号已生成,请返回开始页面重新申购!")
+							return
+						}
+						//	for _, paramvalue := range tempval {
+						//		if _, ok := paramvalue["resultmaps"]; ok {
+						//			listMap := paramvalue["resultmaps"].(map[string]interface{})["list"].([]map[string]interface{})
+						//			for _, arg := range listMap {
+						//				orderNumber := paramvalue["parammaps"].(map[string]interface{})["orderNumber"]
+						//
+						//				partpurchaseTotal := 0
+						//				restful.BasicList(` select count(1) from partpurchase
+						//where bigId = (select id from bigpartpurchase  where orderNumber = ? )  and partCode = ? and contractId = ? `,
+						//					[]interface{}{orderNumber, arg["partCode"]}, arg["contractId"], &partpurchaseTotal)
+						//				if partpurchaseTotal > 0 {
+						//					appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该单号中已存在相同配件%v %v,请调整后重新保存", arg["partName"], arg["partCode"]))
+						//					return
+						//				}
+						//			}
+						//		}
+						//	}
+
+						employeId := paramvalue["parammaps"].(map[string]interface{})["employeId"]
+						_, err := tx.Exec(` DELETE p FROM partpurchase p JOIN bigpartpurchase bp ON bp.id = p.bigId WHERE bp.pastureId = ?  AND p.reject = 1 
+						AND p.employeId = ?  AND bp.purchase_type = 0  `, pastureId, employeId)
+						if err != nil {
+							appG.Response(http.StatusOK, e.ERROR, err.Error())
+							return
+						}
+					}
+					break
+				}
+			}
+
 			for _, paramvalue := range tempval {
 				if _, ok := paramvalue["resultname"]; !ok {
 					paramvalue["resultname"] = paramvalue["name"]
@@ -3492,7 +3623,7 @@ func GetPartsListSGv2(c *gin.Context) {
          union 
          select  id from bigcontract  where contractCode like concat("%",?,"%") and pastureId = ? `
 	var prices []string
-	var priceExist []string
+	var priceExist, contractVarianceItemList, lifeCycleList []string
 	resp := make(map[string]string)
 
 	for _, part := range partList {
@@ -3505,18 +3636,24 @@ func GetPartsListSGv2(c *gin.Context) {
 		if len(pastureBigcontract) > 0 {
 			//partMap[part["contractCode"]] = true
 			//part["lifeCycle"]
-			var lifeCycle, contractVarianceItem string
-			if part["lifeCycle"] == "" {
-				lifeCycle = "无"
-			} else {
-				lifeCycle = part["lifeCycle"]
-			}
 			if part["contractVarianceItem"] == "" {
-				contractVarianceItem = "无"
+				contractVarianceItemList = append(contractVarianceItemList, "无")
 			} else {
-				contractVarianceItem = part["contractVarianceItem"]
+				contractVarianceItemList = append(contractVarianceItemList, part["contractVarianceItem"])
 			}
-			priceExist = append(priceExist, fmt.Sprintf("%s 使用周期 %s 合同差异性 %s", part["price"], lifeCycle, contractVarianceItem))
+			if part["lifeCycle"] == "" {
+				lifeCycleList = append(lifeCycleList, "无")
+			} else {
+				lifeCycleList = append(lifeCycleList, part["lifeCycle"])
+			}
+			//contractVarianceItem = "无"
+			//} else {
+			//	contractVarianceItem = part["contractVarianceItem"]
+			//if len(priceExist) == 0 {
+			//	priceExist = append(priceExist, fmt.Sprintf("%s", part["price"]))
+			//} else {
+			priceExist = append(priceExist, fmt.Sprintf("%s", part["price"]))
+			//}
 			part["price"] = ""
 			resp = part
 		} else {
@@ -3530,9 +3667,9 @@ func GetPartsListSGv2(c *gin.Context) {
 		if _, ok := partMap[p]; !ok {
 			partMap[p] = partMap[p] + 1
 			if i == 0 {
-				resp["price"] = fmt.Sprintf("%s %s ", pastureName, p)
+				resp["price"] = fmt.Sprintf("%s %s", pastureName, p)
 			} else {
-				resp["price"] = fmt.Sprintf("%s ,%s %s ", resp["price"], pastureName, p)
+				resp["price"] = fmt.Sprintf("%s,%s %s", resp["price"], pastureName, p)
 			}
 		}
 	}
@@ -3541,13 +3678,14 @@ func GetPartsListSGv2(c *gin.Context) {
 		if _, ok := partMap[p]; !ok {
 			partMap[p] = partMap[p] + 1
 			if len(resp["price"]) > 0 {
-				resp["price"] = fmt.Sprintf("%s ,现价格 %s ", resp["price"], p)
+				resp["price"] = fmt.Sprintf("%s,现价格%s ", resp["price"], p)
 			} else {
-				resp["price"] = fmt.Sprintf("现价格 %s ", p)
+				resp["price"] = fmt.Sprintf("现价格 %s", p)
 			}
 		}
 	}
-
+	resp["lifeCycle"] = strings.Join(lifeCycleList, ",")
+	resp["contractVarianceItem"] = strings.Join(contractVarianceItemList, ",")
 	appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{"list": []map[string]string{resp}})
 }
 
@@ -3555,37 +3693,11 @@ func GetWaterAndElectricity(context *gin.Context) {
 	appG := app.Gin{C: context}
 	dataByte, _ := ioutil.ReadAll(context.Request.Body)
 	fsion := gofasion.NewFasion(string(dataByte))
-	//filename := context.Param("filename")
-	//sqlnamestr := parammap.Get("name").ValueStr()
 	pastureName := fsion.Get("pastureId").ValueStr()
-	//pastureName := fsion.Get("pasture").ValueStr()
-	//date := fsion.Get("date").ValueStr()
-	//parammap := fsion.Get("parammaps")
-	//logging.Info("DownloadMailReport ", context.Keys, sqlnamestr, pastureName)
 	parammap := make(map[string]string, 0)
-	//layout := "2006-01-02"
-	//date, err := time.Parse(layout, "2023-06-01")
-	//if err != nil {
-	//	fmt.Println(err)
-	//}
-
-	//获取当月第一天
-	//firstOfMonth := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location())
-	//fmt.Println("当月第一天:", firstOfMonth)
-
-	//获取下个月第一天,然后减去一天即为当月最后一天
-	//nextMonth := firstOfMonth.AddDate(0, 1, 0)
-	//lastOfMonth := nextMonth.AddDate(0, 0, -1)
-
-	//parammap["startTime"] = firstOfMonth.Format("2006-01-02")
-	//parammap["endTime"] = lastOfMonth.Format("2006-01-02")
 	parammap["startTime"] = fsion.Get("startTime").ValueStr()
 	parammap["endTime"] = fsion.Get("endTime").ValueStr()
-	//if fsion.Get("pastureId").ValueStr() == "现代牧业" {
-	//	parammap["pastureId"] = ""
-	//} else {
 	parammap["pastureId"] = fsion.Get("pastureId").ValueStr()
-	//}
 
 	sqlnamesDepartment := []string{}
 	if pastureName == "现代牧业" {
@@ -3641,6 +3753,7 @@ func GetWaterAndElectricity(context *gin.Context) {
 				if !exist {
 					respMap := make(map[string]string, 0)
 					respMap["pastureName"] = v["pastureName"]
+					respMap["pastureId"] = v["pastureId"]
 					if sqlname == "getChooseMonthWater" || sqlname == "getChooseMonthWaterByPasture" {
 						respMap["waterOneCowSumPrice"] = v["oneCowSumPrice"]
 						respMap["waterSumPrice"] = v["sumPrice"]

+ 2 - 0
apiserver/routers/api/user.go

@@ -1,6 +1,7 @@
 package api
 
 import (
+	"fmt"
 	"net/http"
 	"regexp"
 
@@ -110,6 +111,7 @@ func UserLogout(c *gin.Context) {
 // @Router /authdata/userinfo  [GET]
 func GetUserinfo(c *gin.Context) {
 	appG := app.Gin{C: c}
+	fmt.Println(c.MustGet("jwt_username"))
 	data := restful.GetUserInfo(c.MustGet("jwt_username").(string))
 	appG.Response(http.StatusOK, e.SUCCESS, data)
 }

+ 291 - 0
apiserver/routers/chart.go

@@ -1 +1,292 @@
 package routers
+
+import (
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+)
+
+func GetWaterYieldByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWaterYieldByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWaterSingleCowByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWaterSingleCowByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWaterRateByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWaterRateByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWaterRateCompleteByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWaterRateCompleteByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWaterPerHeadByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWaterPerHeadByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetElectricityYieldByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetElectricityYieldByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetElectricitySingleCowByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetElectricitySingleCowByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetElectricityRateByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetElectricityRateByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetElectricityRateCompleteByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	center := c.Query("center")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetElectricityRateCompleteByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetElectricityPerHeadByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetElectricityPerHeadByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWxYieldByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+	departmentName := c.Query("departmentName")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWxYieldByPasture(departmentName, center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWxSingleCowByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	center := c.Query("center")
+
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWxSingleCowByPasture(center, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWxPerHeadByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetWxPerHeadByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+//各牧场年度燃动费对比
+func GetIgnitionYieldByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetIgnitionYieldByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+//各牧场年度柴油对比
+func GetDieselYieldByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetDieselYieldByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+//单头牛柴油
+func GetDieselRateByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetDieselRateByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+//单头牛燃动费
+func GetIgnitionRateByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetIgnitionRateByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+//单头牛燃动费
+func GetDieselPerHeadByPasture(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+	startTime = startTime + "-01"
+	endTime = endTime + "-01"
+	data, err := svc.GetDieselPerHeadByPasture(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}

+ 18 - 0
apiserver/routers/diesel.go

@@ -2,6 +2,7 @@ package routers
 
 import (
 	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model"
 	"kpt.xdmy/apiserver/model/http"
 	"kpt.xdmy/pkg/app"
 	"kpt.xdmy/pkg/e"
@@ -39,3 +40,20 @@ func DieselOff(c *gin.Context) {
 	hrp := svc.DieselOff(p.Id)
 	c.JSON(200, &hrp)
 }
+
+func EditPartpurchase(c *gin.Context) {
+	appG := app.Gin{C: c}
+	req := make([]*model.EditPartpurchaseReq, 0)
+	if err := c.ShouldBind(&req); err != nil {
+
+		appG.Response(500, e.ERROR, "数据格式不正确!"+err.Error())
+		return
+	}
+
+	err := svc.EditPartpurchase(req)
+	if err != nil {
+		appG.Response(200, e.ERROR, err.Error())
+		return
+	}
+	appG.Response(200, e.SUCCESS, true)
+}

+ 132 - 0
apiserver/routers/home.go

@@ -1,9 +1,17 @@
 package routers
 
 import (
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
 	"github.com/gin-gonic/gin"
+	"github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model/http"
 	"kpt.xdmy/pkg/app"
 	"kpt.xdmy/pkg/e"
+	"kpt.xdmy/pkg/util"
+	http1 "net/http"
+	"strings"
 )
 
 func OverallIndex(c *gin.Context) {
@@ -49,3 +57,127 @@ func GetPastureIndex(c *gin.Context) {
 	}
 	appG.Response(200, e.SUCCESS, data)
 }
+
+func GetEquipmentIndex(c *gin.Context) {
+	appG := app.Gin{C: c}
+	//p := new(home.GetPastureIndexReq)
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+
+	data, err := svc.GetEquipmentIndex(pastureId, startTime, endTime)
+	if err != nil {
+		fmt.Println(err)
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetChooseMonthWXByDepartment(c *gin.Context) {
+	appG := app.Gin{C: c}
+	//p := new(home.GetPastureIndexReq)
+	pastureId := c.Query("pastureId")
+	startTime := c.Query("startTime")
+	endTime := c.Query("endTime")
+
+	data, err := svc.GetChooseMonthWXByDepartment(pastureId, startTime, endTime)
+	if err != nil {
+		c.JSON(200, map[string]interface{}{"code": 200, "data": err.Error(), "msg": "fail"})
+		return
+	}
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func OAuth2Token(c *gin.Context) {
+	//appG := app.Gin{C: c}
+	code := c.Query("code")
+	fmt.Println(c.Request.Host)
+	host := ""
+	requestHost := c.Request.Host
+	if strings.Index(requestHost, "Eam") > -1 {
+		host = "eam"
+	} else {
+		host = "http://192.168.61.41"
+	}
+
+	data, err := svc.OAuth2Token(code, host)
+	fmt.Println(err)
+	if err != nil {
+		logrus.Error(err)
+		c.JSON(401, map[string]interface{}{"code": 401, "data": "认证失败", "msg": "fail"})
+		return
+	}
+	//c.Header("token", data.AccessToken)
+	//c.Writer.Header().Set("token", data.AccessToken)
+
+	c.Redirect(http1.StatusSeeOther, fmt.Sprintf("/?access=%s", base64.StdEncoding.EncodeToString([]byte(data.AccessToken))))
+
+	//newRequest, err := http1.NewRequest("GET", "/", nil)
+	//if err != nil {
+	//	c.String(http1.StatusInternalServerError, "Failed to create new request")
+	//	return
+	//}
+	//
+	//// 设置新的请求头
+	//newRequest.Header.Set("Authorization", data.AccessToken)
+	//
+	//// 执行重定向
+	//resp, err := http1.DefaultClient.Do(newRequest)
+	//if err != nil {
+	//	c.String(http1.StatusInternalServerError, "Failed to redirect request")
+	//	return
+	//}
+	//defer resp.Body.Close()
+
+	//appG.Response(200, e.SUCCESS, data)
+}
+
+func OAuth2Logout(c *gin.Context) {
+	appG := app.Gin{C: c}
+	//token := c.Query("token")
+	token := c.GetHeader("token")
+	host := ""
+	requestHost := c.Request.Host
+	if strings.Index(requestHost, "Eam") > -1 {
+		host = "eam"
+	} else {
+		host = "http://192.168.61.41"
+	}
+
+	err := svc.OAuth2Logout(token, host)
+	if err != nil {
+		logrus.Error(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "注销失败!", "msg": "fail"})
+		return
+	}
+	//c.Redirect(303, "/")
+	appG.Response(200, e.SUCCESS, true)
+}
+
+func OAuth2AddUser(c *gin.Context) {
+	req := new(http.OAuth2AddUserReq)
+	err := c.ShouldBind(&req)
+	if err != nil {
+		fmt.Println(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "同步失败!", "msg": "fail"})
+		return
+	}
+
+	user := new(http.OAuth2AddUser)
+	fmt.Println(req.Data)
+	err = json.Unmarshal([]byte(req.Data), &user)
+	data := make(map[string]string, 0)
+
+	//{"password":"Xdmy@123456","name":"米鹏","disabled":false,"id":"UR8busm+AzrA1LqMRHs4NhY4LzU=","pasture":"1","userId":"20231206215655324-5EA8-20662791E","username":"07007"}
+
+	userInfo, err := svc.OAuth2AddUser(user)
+	if err != nil {
+		fmt.Println(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "同步失败!", "msg": "fail"})
+		return
+	}
+	data["id"] = util.AesEncryptByECB(fmt.Sprintf("%d", userInfo.ID))
+	fmt.Println(data)
+	c.JSON(200, map[string]interface{}{"code": 200, "data": data, "msg": "ok"})
+}

+ 134 - 0
apiserver/routers/liugong.go

@@ -1 +1,135 @@
 package routers
+
+import (
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model/liugong"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+	"strconv"
+	"strings"
+)
+
+//func GetLiuGongToken(c *gin.Context) {
+//	resp, err := svc.GetLiuGongToken()
+//	if err != nil {
+//		c.JSON(500, resp)
+//		return
+//	}
+//	c.JSON(200, resp)
+//}
+//
+//func EditVehicle(c *gin.Context) {
+//	p := new(liugong.PushEquipmentInfoReq)
+//	if !Bind(c, p) {
+//		return
+//	}
+//	hrp := new(http.Response)
+//	resp, err := svc.LGPushEquipmentInfo(p)
+//	if err != nil || len(resp) > 0 {
+//		hrp.Code = 500
+//		hrp.Message = strings.Join(resp, ";")
+//		hrp.Msg = strings.Join(resp, ";")
+//		c.JSON(500, hrp)
+//		return
+//	}
+//	hrp.Code = 200
+//	hrp.Message = "上传成功!"
+//	hrp.Msg = "上传成功!"
+//	c.JSON(200, hrp)
+//}
+//
+//func GetVehicleList(c *gin.Context) {
+//	p := new(liugong.GetVehicleListReq)
+//	hrp := new(http.Response)
+//	//c.BindQuery(p)
+//	p.PastureId = c.Query("pastureId")
+//	p.StartTime = c.Query("startTime")
+//	p.EndTime = c.Query("endTime")
+//	p.Offset, _ = strconv.Atoi(c.Query("offset"))
+//	p.PageCount, _ = strconv.Atoi(c.Query("pageCount"))
+//
+//	fmt.Println(p)
+//	resp, count, err := svc.GetVehicleList(p)
+//	if err != nil {
+//		hrp.Code = 500
+//		hrp.Message = err.Error()
+//		hrp.Msg = err.Error()
+//		c.JSON(500, hrp)
+//		return
+//	}
+//	hrp.Data = resp
+//	hrp.Code = 200
+//	hrp.Count = count
+//	hrp.Offset = p.Offset
+//	hrp.PageCount = p.PageCount
+//	c.JSON(200, hrp)
+//}
+
+//GetVehicle
+
+func EditVehicle(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataList := make([]*liugong.EditVehicleReq, 0)
+
+	if err := c.ShouldBind(&dataList); err != nil {
+		appG.Response(500, e.ERROR, "数据格式不正确!")
+		return
+	}
+	errs := svc.EditVehicle(dataList)
+	if len(errs) > 0 {
+		appG.Response(500, e.ERROR, strings.Join(errs, ","))
+		return
+	}
+	appG.Response(200, e.SUCCESS, true)
+}
+
+func GetVehicle(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	offsetStr := c.Query("offset")
+	pagecountStr := c.Query("pagecount")
+
+	startdate := c.Query("startTime")
+	enddate := c.Query("endTime")
+	eqCode := c.Query("eqCode")
+	eqName := c.Query("eqName")
+	departmentId := c.Query("departmentId")
+
+	offset, _ := strconv.Atoi(offsetStr)
+	pagecount, _ := strconv.Atoi(pagecountStr)
+
+	data, err := svc.GetVehicle(pastureId, startdate, enddate, eqCode, eqName, departmentId, offset, pagecount)
+	if err != nil {
+		appG.Response(500, e.ERROR, err)
+		return
+	}
+
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func GetWorkClass(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	dataList := []string{"饲喂车",
+		"推料车",
+		"上料装载机",
+		"卧床疏松车",
+		"吸污车",
+		"推粪装载机",
+		"卧床抛料车",
+		"消毒车",
+		"淘牛车",
+		"剩料收集车",
+		"青贮倒运车",
+		"沼渣倒运装载机",
+		"沼渣倒运自卸车",
+		"沼渣晾晒拖拉机",
+		"犊牛转运车",
+		"兽医装载机",
+		"装卸装载机",
+		"装卸叉车",
+		"犊牛喂奶车",
+		"犊牛垫料装载机",
+		"颗粒撒料车", "其他车辆"}
+	appG.Response(200, e.SUCCESS, dataList)
+}

+ 13 - 0
apiserver/routers/report.go

@@ -6,6 +6,8 @@ import (
 	"github.com/gin-gonic/gin"
 	"io/ioutil"
 	"kpt.xdmy/apiserver/service"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
 	"time"
 )
 
@@ -158,3 +160,14 @@ func StartStopRecord(c *gin.Context) {
 	}
 	c.JSON(200, map[string]interface{}{"code": 200, "data": resp, "msg": "ok"})
 }
+
+func GetEnsiling(c *gin.Context) {
+	appG := app.Gin{C: c}
+	pastureId := c.Query("pastureId")
+	ensilingList, err := svc.GetEnsiling(pastureId)
+	if err != nil {
+		appG.Response(500, e.ERROR, err)
+		return
+	}
+	appG.Response(200, e.SUCCESS, ensilingList)
+}

+ 71 - 3
apiserver/routers/router.go

@@ -2,11 +2,10 @@ package routers
 
 import (
 	"fmt"
+	"kpt.xdmy/middleware/jwt"
 
 	"github.com/gin-gonic/gin"
 	"kpt.xdmy/middleware/comm"
-	"kpt.xdmy/middleware/jwt"
-
 	//	"kpt.xdmy/middleware/permission"
 	"net/http"
 	"strings"
@@ -155,6 +154,64 @@ func InitRouter() *gin.Engine {
 		apiV1.GET("/expense", GetExpense)            //费用统计
 		apiV1.GET("/pasture/index", GetPastureIndex) //牧场指标
 
+		//apiV1.GET("/vehicleL/list", GetVehicleList)
+
+		apiV1.POST("/contract/push", PostPushContractDataToSAP)
+
+		apiV1.GET("/equipment/index", GetEquipmentIndex)
+		apiV1.GET("/choosemonthwx/index", GetChooseMonthWXByDepartment)
+
+		apiV1.POST("/stock/import", StockExcel)
+		apiV1.GET("/stock/list", GetStockList)
+		apiV1.POST("/stock/del", DelStockList)
+
+		//各牧场年度用水量对比
+		apiV1.GET("/water/nowwater", GetWaterYieldByPasture)
+		//单头牛水量
+		apiV1.GET("/water/singlecow", GetWaterSingleCowByPasture)
+		//单头牛水费
+		apiV1.GET("/water/waterrate", GetWaterRateByPasture)
+		//水费完成率
+		apiV1.GET("/water/ratecomplete", GetWaterRateCompleteByPasture)
+		//每月单头牛用水量对比
+		apiV1.GET("/water/perhead", GetWaterPerHeadByPasture)
+
+		//各牧场年度用电量对比
+		apiV1.GET("/electricity/nowelectricity", GetElectricityYieldByPasture)
+		//单头牛电量
+		apiV1.GET("/electricity/singlecow", GetElectricitySingleCowByPasture)
+		//单头牛电费
+		apiV1.GET("/electricity/electricityrate", GetElectricityRateByPasture)
+		//电费完成率
+		apiV1.GET("/electricity/ratecomplete", GetElectricityRateCompleteByPasture)
+		//每月单头牛用电量对比
+		apiV1.GET("/electricity/perhead", GetElectricityPerHeadByPasture)
+
+		//各牧场年度维修对比
+		apiV1.GET("/repair/nowelectricity", GetWxYieldByPasture)
+		//单头牛维修
+		apiV1.GET("/repair/singlecow", GetWxSingleCowByPasture)
+		//每月单头牛维修对比
+		apiV1.GET("/repair/perhead", GetWxPerHeadByPasture)
+
+		//各牧场年度燃动费对比
+		apiV1.GET("/ignition/nowwater", GetIgnitionYieldByPasture)
+		//各牧场年度柴油费对比
+		apiV1.GET("/diesel/nowwater", GetDieselYieldByPasture)
+		//单头牛柴油
+		apiV1.GET("/diesel/rate", GetDieselRateByPasture)
+		//单头牛燃动费
+		apiV1.GET("/ignition/rate", GetIgnitionRateByPasture)
+		//单头牛燃动费
+		apiV1.GET("/diesel/perhead", GetDieselPerHeadByPasture)
+
+		apiV1.GET("/vehicle/list", GetVehicle)
+		//	申购备件修改
+		apiV1.POST("/partpurchase/edit", EditPartpurchase)
+		//工作分类下拉,目前写死
+		apiV1.GET("/work/class", GetWorkClass)
+		apiV1.GET("/ensiling", GetEnsiling)
+
 	}
 
 	if setting.ServerSetting.NoAuth > 0 {
@@ -168,7 +225,7 @@ func InitRouter() *gin.Engine {
 			apiV2.POST("/GetDataByNames", api.GetDataByNames)
 			apiV2.POST("/PostDataByName", api.PostDataByName)
 			apiV2.POST("/PostDataByNames", api.PostDataByNames)
-	
+
 			apiV2.POST("/ExecDataByConfig", api.ExecDataByConfig)
 
 			apiV2.POST("/GetDataByNameForm", api.GetDataByNameForm)
@@ -203,15 +260,26 @@ func InitRouter() *gin.Engine {
 	{
 		apiV3.POST("/GetDataByName", api.GetDataByName)
 		apiV3.POST("/PostDataByName", api.PostDataByName)
+
+		apiV3.POST("/vehicle/edit", EditVehicle)
 	}
 
 	apiV4 := r.Group("/openapi")
 	//apiV4.Use(jwt.JWT())
 	{
+
 		apiV4.POST("/GetDataByName", api.GetDataByNameOPEN)
 		apiV4.POST("/PostDataByName", api.PostDataByNameOPEN)
 	}
 
+	apiV5 := r.Group("/api/v1")
+	{
+		apiV5.GET("/oauth2/token", OAuth2Token)
+		apiV5.GET("/logout", OAuth2Logout)
+		apiV5.POST("/user/add", OAuth2AddUser)
+
+	}
+
 	return r
 }
 

+ 24 - 0
apiserver/routers/sap.go

@@ -313,3 +313,27 @@ func ContractExec(c *gin.Context) {
 
 	c.JSON(200, map[string]interface{}{"code": 200, "data": map[string]interface{}{"code": 200}, "msg": "ok"})
 }
+
+func PostPushContractDataToSAP(c *gin.Context) {
+	req := new(http.PostPushContractDataToSAPReq)
+	hrp := new(http.Response)
+	if err := c.ShouldBind(&req); err != nil {
+		hrp.Code = 200
+		hrp.Message = err.Error()
+		hrp.Msg = "fail"
+		hrp.Data = err.Error()
+		c.JSON(200, hrp)
+		return
+	}
+	err := svc.PostPushContractDataToSAP(req.PastureId, req.ProviderId, req.ContractIdList)
+	if err != nil {
+		hrp.Code = 200
+		hrp.Message = err.Error()
+		hrp.Msg = "fail"
+		hrp.Data = err.Error()
+		c.JSON(200, hrp)
+		return
+	}
+
+	c.JSON(200, map[string]interface{}{"code": 200, "data": map[string]interface{}{"code": 200}, "msg": "ok"})
+}

+ 65 - 0
apiserver/routers/stock.go

@@ -1 +1,66 @@
 package routers
+
+import (
+	"fmt"
+	"github.com/astaxie/beego/logs"
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+	"strconv"
+)
+
+func GetStockList(c *gin.Context) {
+	req := new(model.GetStockListReq)
+
+	req.PastureId = c.Query("pastureId")
+	req.DepartmentId = c.Query("departmentId")
+	offsetStr := c.Query("offset")
+	pagecountStr := c.Query("pagecount")
+	req.StartDate = c.Query("startdate")
+	req.EndDate = c.Query("enddate")
+	req.Offset, _ = strconv.Atoi(offsetStr)
+	req.Pagecount, _ = strconv.Atoi(pagecountStr)
+	req.Offset = req.Offset - 1
+
+	resp, err := svc.GetStockList(req)
+	if err != nil {
+		fmt.Println(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "查询失败!", "msg": err})
+		return
+	}
+
+	resp.Offset = req.Offset + 1
+	resp.Pagecount = req.Pagecount
+	c.JSON(200, map[string]interface{}{"code": 200, "data": resp, "msg": "ok"})
+}
+
+func StockExcel(c *gin.Context) {
+	appG := app.Gin{C: c}
+	data := svc.StockExcel(c)
+	appG.Response(200, e.SUCCESS, data)
+}
+
+func DelStockList(c *gin.Context) {
+	req := new(model.DelStockListReq)
+	err := c.ShouldBind(&req)
+	if err != nil {
+		logs.Error(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "参数有误!", "msg": err})
+		return
+	}
+
+	var idList []string
+	for _, id := range req.Id {
+		idStr := strconv.Itoa(id)
+		idList = append(idList, idStr)
+	}
+
+	err = svc.DelStockList(idList)
+	if err != nil {
+		logs.Error(err)
+		c.JSON(500, map[string]interface{}{"code": 500, "data": "删除失败!", "msg": err})
+		return
+	}
+	c.JSON(200, map[string]interface{}{"code": 200, "data": true, "msg": "ok"})
+}

+ 41 - 9
apiserver/service/asset.go

@@ -38,8 +38,8 @@ func (s *Service) SapAsset(t time.Time, code string, companyCode string) {
 	r.Data.BudatB = t.Format("20060102")
 	r.Data.BudatE = t.Format("20060102")
 	r.Data.EqType = []http.ANLKL{}
-	//r.Data.BudatB = "20221101"
-	//r.Data.BudatE = "20221125"
+	//r.Data.BudatB = "20230929"
+	//r.Data.BudatE = "20230929"
 	r.Data.CompanyCode = []http.Company{
 		{Code: companyCode},
 	}
@@ -127,7 +127,6 @@ func updateEQ(p *http.Asset) {
 	s.d.DB.Where("financeCode = ? ", eq.FinanceCode).First(&oldeq)
 
 	if oldeq.EqName == "" {
-		eq.EqName = p.Name
 		eq.Specification = p.Model
 		//eq.ProId = p.ID
 		eq.Unit = p.Unit
@@ -142,9 +141,15 @@ func updateEQ(p *http.Asset) {
 		eq.SHStatus = 1
 		eq.Status = 17
 	}
-
+	eq.EqName = p.Name
 	eq.Yuanzhi = p.BuyValue
 	eq.Quantity = p.Quantity
+	eq.Purpose = p.ZUSAGE
+	if p.ZSELFNB != "" {
+		eq.EqCode = p.ZSELFNB
+	}
+	//ZUSAGE  string `json:"ZUSAGE"`  // 用途
+	//ZSELFNB string `json:"ZSELFNB"` // 自编号
 	//eq.Salvage = p.Salvage
 	eq.PastureId = pa.ID
 	eq.PastureName = pa.Name
@@ -152,14 +157,33 @@ func updateEQ(p *http.Asset) {
 	eq.EntranceDate = p.BuyDate
 	eq.Subtractvalue = p.Salvage + "%"
 	dep := new(model.Department)
-	s.d.DB.Where("costCenter_code = ? ", p.CostCenter).First(&dep)
-	if dep.ID > 0 {
-		eq.DepartmentId = strconv.Itoa(dep.ID)
-		eq.DepartmentName = dep.Name
+	if p.CostCenter != "" {
+		s.d.DB.Where("costCenter_code = ? ", p.CostCenter).First(&dep)
+		if dep.ID > 0 {
+			//eq.DepartmentId = strconv.Itoa(dep.ID)
+			//eq.DepartmentName = dep.Name
+			eq.DeptId = strconv.Itoa(dep.ID)
+		}
+	}
+	department := new(model.Department)
+	s.d.DB.Where("costCenter_code = ? ", p.KOSTL).First(&department)
+	//if dep.ID > 0 {
+	//eq.DeptId = strconv.Itoa(department.ID)
+	eq.DepartmentId = strconv.Itoa(department.ID)
+	eq.DepartmentName = department.Name
+	//}
+
+	if dep.ID == 0 {
+		eq.DeptId = strconv.Itoa(department.ID)
+		//eq.DepartmentName = department.Name
 	}
 
 	if p.ORD41 == "A3" {
 		eq.Status = 19
+	} else if p.ORD41 == "A4" {
+		eq.Status = 18
+	} else if p.ORD41 == "A2" {
+		eq.Status = 234
 	} else {
 		eq.Status = 17
 	}
@@ -171,9 +195,15 @@ func updateEQ(p *http.Asset) {
 	//if p.BuyValue == "" || p.BuyValue == "0" || p.BuyValue == "0.00 " {
 	//	return
 	//}
+	//if eq.FinanceCode == "1008-41201000494-0" {
+	//	eq.EqCode = "00a000012"
+	//}
 
 	fmt.Println(eq)
 	if oldeq.Id == 0 {
+		//if p.ZSELFNB == "" {
+		//	//eq.EqCode = "NULL"
+		//}
 		if e := s.d.DB.Where(model.Equipment{FinanceCode: eq.FinanceCode}).Assign(eq).FirstOrCreate(&eq).Error; e != nil {
 			//assetChan <- errors.Wrapf(e, "equipment update : %s, %s,%s,%s", p.AssetCode, p.SonCode, p.Name, p.CompanyCode)
 		} else {
@@ -182,7 +212,7 @@ func updateEQ(p *http.Asset) {
 		}
 	} else {
 		eq.Id = oldeq.Id
-		err := s.d.DB.Model(eq).Where("id = ? ", oldeq.Id).Updates(eq).Error
+		err := s.d.DB.Debug().Model(eq).Where("id = ? ", oldeq.Id).Updates(eq).Error
 		if err != nil {
 			log.Error(err)
 		}
@@ -193,6 +223,7 @@ type Equipment struct {
 	PastureId   int    `gorm:"column:pastureId" json:"pastureId"`
 	PastureName string `gorm:"column:pastureName" json:"pastureName"`
 	EqName      string `gorm:"column:eqName" json:"eqName"`
+	EqCode      string `gorm:"default:NULL;column:eqCode" json:"eqCode"`
 	//AssetCode        interface{} `gorm:"column:assetCode" json:"assetCode"`
 	EqClassName      string    `gorm:"column:eqClassName" json:"eqClassName"`
 	Specification    string    `gorm:"column:specification" json:"specification"`
@@ -253,6 +284,7 @@ type Equipment struct {
 	SonCode      string    `gorm:"column:sonCode" json:"sonCode"`
 
 	SapCode string `gorm:"column:sapCode" json:"sapCode"`
+	DeptId  string `gorm:"column:deptId" json:"deptId"`
 }
 
 func (t *Equipment) TableName() string {

+ 8 - 1
apiserver/service/charge_off.go

@@ -218,7 +218,7 @@ func (s *Service) laidProofList(p *model.ProofReq) (hrp *http.Response) {
 	p.ProofYear = bp.CreatDate.Format("2006")
 
 	parts := make([]model.PartLaid, 0)
-	if e = s.d.DB.Raw(` select * from partlaid where  bigid = ? and dflag != 1 order by rowNumber,id desc `, bp.ID).Order("rowNumber,id desc ").
+	if e = s.d.DB.Debug().Raw(` select * from partlaid where  bigid = ? and ifnull(dflag,0) != 1 order by rowNumber,id desc `, bp.ID).Order("rowNumber,id desc ").
 		Find(&parts).Error; e != nil || len(parts) == 0 {
 		hrp.Message = fmt.Sprintf("入库单明细查询报错或结果为空:bigid=%v error=%v,", bp.ID, e)
 		hrp.Msg = "fail"
@@ -555,6 +555,13 @@ func (s *Service) DieselOff(id int64) (hrp *http.Response) {
 		return
 	}
 
+	//err = tx.Exec(`update  diesel set ProofCode = null where id = ? `, id).Error
+	//if err != nil {
+	//	hrp.Message += err.Error()
+	//	tx.Rollback()
+	//	return
+	//}
+
 	r.Data.RowsNumber = sl
 	rbyte, _ := json.Marshal(r)
 	//rbyte, _ := json.Marshal(r)

+ 1795 - 0
apiserver/service/chart.go

@@ -1 +1,1796 @@
 package service
+
+import (
+	"fmt"
+	"github.com/astaxie/beego/logs"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/util"
+	"strconv"
+	"time"
+)
+
+type pastureStatistics struct {
+	Psum      float64 `gorm:"column:psum"`
+	Name      string  `gorm:"column:name"`
+	PastureId int     `gorm:"column:pastureId"`
+}
+
+type monthBudget struct {
+	MonthBudget float64 `gorm:"column:monthBudget"`
+	Name        string  `gorm:"column:name"`
+}
+
+//各牧场年度用水量对比
+func (s *Service) GetWaterYieldByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+round( IFNULL(SUM(w.waterConsumption),0) ,2)psum,
+  p.name as name
+FROM
+  water w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and p.name <> '现代牧业' and (p.center = ? or ? = '' ) and p.IsEnergy = 0	
+GROUP BY ms.pastureId  `
+
+	err = s.d.DB.Debug().Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		nowYearData = append(nowYearData, util.Round(nowYear.Psum, 2))
+		all += nowYear.Psum
+		exist := false
+		for _, lastYear := range lastYearList {
+			if lastYear.Name == nowYear.Name {
+				exist = true
+				lastYearData = append(lastYearData, util.Round(lastYear.Psum, 2))
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = pastureName
+	resp.LastYear = lastYearData
+	resp.NowYear = nowYearData
+
+	resp.All = util.Round(all, 2)
+
+	return resp, nil
+}
+
+func (s *Service) GetWaterSingleCowByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+round( IFNULL(SUM(w.waterConsumption),0) ,2)psum,
+  p.name
+FROM
+  water w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and p.name <> '现代牧业' and (p.center = ? or ? = '' ) and p.IsEnergy = 0	
+GROUP BY ms.pastureId desc `
+
+	err = s.d.DB.Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	lastCowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?  and (p.center = ? or ? = '' )  group by pastureid `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?  and (p.center = ? or ? = '' )   group by pastureid `,
+		startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastCowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll, lastCowNumAll int64
+	for _, item := range cowNumList {
+		cowNumAll += item.FeedSum.CowNum
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	lastCowNum := make(map[string]int64, 0)
+	for _, item := range lastCowNumList {
+		lastCowNumAll += item.FeedSum.CowNum
+		lastCowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all, lastAll float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		if _, ok := cowNum[nowYear.Name]; ok {
+			all += nowYear.Psum
+			nowYearData = append(nowYearData, nowYear.Psum/float64(cowNum[nowYear.Name]))
+		} else {
+			nowYearData = append(nowYearData, 0)
+		}
+		exist := false
+		for _, lastYear := range lastYearList {
+			if lastYear.Name == nowYear.Name {
+				exist = true
+				if _, ok := lastCowNum[lastYear.Name]; ok {
+					lastAll += nowYear.Psum
+					lastYearData = append(lastYearData, lastYear.Psum/float64(lastCowNum[nowYear.Name]))
+				} else {
+					lastYearData = append(lastYearData, 0)
+				}
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	//resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	//resp.LastYear = append(resp.LastYear, util.Round(lastAll/float64(lastCowNumAll), 3))
+	//resp.LastYear = append(resp.LastYear, lastYearData...)
+	for _, item := range lastYearData {
+		resp.LastYear = append(resp.LastYear, util.Round(item, 3))
+	}
+
+	//resp.NowYear = append(resp.NowYear, util.Round(all/float64(cowNumAll), 3))
+	for _, item := range nowYearData {
+		resp.NowYear = append(resp.NowYear, util.Round(item, 3))
+	}
+	resp.All = all
+	resp.Line = util.Round(all/float64(cowNumAll), 3)
+	return resp, nil
+}
+
+//单头牛水费
+func (s *Service) GetWaterRateByPasture(center, startTime, endTime string) (*http.GetWaterRateByPastureResp, error) {
+
+	resp := new(http.GetWaterRateByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?   and (p.center = ? or ? = '' )  group by pastureid    `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll int64
+	for _, item := range cowNumList {
+		//cowNumAll += cowNum[feequery.Pasture.Name]
+
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Debug().Raw(`select sum(HSL) HSL  ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='水费'  and (p.center = ? or ? = '' )  group by fd.pastureId order by p.id`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var hslList []float64
+	var all float64
+	for _, feequery := range feequeryList {
+		pastureName = append(pastureName, feequery.Pasture.Name)
+		var hsl float64
+		hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+		if err != nil {
+			logs.Error("转换失败:", err)
+			hslList = append(hslList, 0)
+		}
+
+		if _, ok := cowNum[feequery.Name]; ok {
+			all += hsl
+			cowNumAll += cowNum[feequery.Pasture.Name]
+			hslList = append(hslList, hsl/float64(cowNum[feequery.Pasture.Name]))
+		} else {
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, item := range pastureList {
+		exist := false
+		for _, f := range feequeryList {
+			if item.Name == f.Name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, item.Name)
+			hslList = append(hslList, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.Actual = append(resp.Actual, util.Round(all/float64(cowNumAll), 3))
+	//select 1748193.91/8271863
+	for _, item := range hslList {
+		resp.Actual = append(resp.Actual, util.Round(item, 3))
+	}
+	resp.Line = util.Round(all/float64(cowNumAll), 3)
+	//resp.Actual = append(resp.Actual, hslList...)
+	return resp, err
+}
+
+func (s *Service) GetWaterRateCompleteByPasture(center, startTime, endTime string) (*http.GetWaterRateCompleteByPastureResp, error) {
+	resp := new(http.GetWaterRateCompleteByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(HSL),0) HSL ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='水费'  and (p.center = ? or ? = '' )   group by fd.pastureId`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '水费' and mb.budgetMonth between ? and ?  and (p.center = ? or ? = '' )   group by mb.pastureId`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var budgetList, actualList, complete []float64
+	var budgetAll, actualAll float64
+	for _, monthBudget := range monthBudgetList {
+		pastureName = append(pastureName, monthBudget.Name)
+		budgetList = append(budgetList, util.Round(monthBudget.MonthBudget, 2))
+		budgetAll += monthBudget.MonthBudget
+		exist := false
+		var hsl float64
+		for _, feequery := range feequeryList {
+			if feequery.Name == monthBudget.Name {
+				exist = true
+
+				hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+				if err != nil {
+					actualList = append(actualList, 0)
+					logs.Error("转换失败:", err)
+				} else {
+					actualAll += hsl
+					actualList = append(actualList, util.Round(hsl, 2))
+					continue
+				}
+
+				break
+			}
+		}
+		if !exist {
+			actualList = append(actualList, 0)
+		}
+
+		//预算减实际除预算加1
+		if monthBudget.MonthBudget > 0 && hsl > 0 {
+			complete = append(complete, util.Round(((monthBudget.MonthBudget-hsl)/monthBudget.MonthBudget+1)*100, 2))
+		} else {
+			complete = append(complete, 0)
+		}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			actualList = append(actualList, 0)
+			budgetList = append(budgetList, 0)
+			complete = append(complete, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+
+	resp.Actual = append(resp.Actual, util.Round(actualAll, 2))
+	resp.Actual = append(resp.Actual, actualList...)
+
+	resp.Budget = append(resp.Budget, util.Round(budgetAll, 2))
+	resp.Budget = append(resp.Budget, budgetList...)
+
+	if budgetAll > 0 && actualAll > 0 {
+		resp.Complete = append(resp.Complete, util.Round(((budgetAll-actualAll)/budgetAll+1)*100, 2))
+	} else {
+		resp.Complete = append(resp.Complete, 0)
+	}
+
+	resp.Complete = append(resp.Complete, complete...)
+	return resp, nil
+}
+
+type dosagePerCow struct {
+	Psum   float64 `gorm:"column:psum"`
+	Date   string  `gorm:"column:date"`
+	Name   string  `gorm:"column:name"`
+	CowNum int64   `gorm:"column:cowNum"`
+}
+
+//每月单头牛用水量对比
+func (s *Service) GetWaterPerHeadByPasture(pastureId, startTime, endTime string) (map[string]interface{}, error) {
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	dosagePerCowList := make([]*dosagePerCow, 0)
+
+	err = s.d.DB.Debug().Raw(`SELECT
+round( IFNULL(SUM(w.waterConsumption),0) ,2)psum,
+  p.name,DATE_FORMAT( w.date, '%Y-%m') date,
+	ifnull((select sum(cowNum)  from feed_sum  where DATE_FORMAT( feedDay, '%Y-%m') = DATE_FORMAT( w.date, '%Y-%m') and pastureId = p.id ),0)cowNum
+FROM
+  water w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and p.name <> '现代牧业'   and  FIND_IN_SET(p.id,?)  
+GROUP BY DATE_FORMAT( w.date, '%Y-%m'),ms.pastureId order by  DATE_FORMAT( w.date, '%Y-%m'),p.name asc `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), pastureId).Find(&dosagePerCowList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	data := dosagePerCowFormat(dosagePerCowList)
+	return data, nil
+}
+
+func dosagePerCowFormat(dosagePerCowList []*dosagePerCow) map[string]interface{} {
+	var dateList, pastureNameList []string
+	var dataList []interface{}
+	data := make(map[string]interface{}, 0)
+	data["data1"] = []string{}
+	data["data2"] = []string{}
+	data["data3"] = []interface{}{}
+	for _, item := range dosagePerCowList {
+		if len(dateList) == 0 {
+			dateList = append(dateList, item.Date)
+		}
+		dateExist := false
+		for _, date := range dateList {
+			if date == item.Date {
+				dateExist = true
+				break
+			}
+		}
+		if !dateExist {
+			dateList = append(dateList, item.Date)
+		}
+
+		if len(pastureNameList) == 0 {
+			pastureNameList = append(pastureNameList, item.Name)
+		}
+		pastureNameExist := false
+		for _, pastureName := range pastureNameList {
+			if pastureName == item.Name {
+				pastureNameExist = true
+				break
+			}
+		}
+		if !pastureNameExist {
+			pastureNameList = append(pastureNameList, item.Name)
+		}
+	}
+
+	for _, pastureName := range pastureNameList {
+		var number []float64
+		for _, date := range dateList {
+			exist := false
+			for _, item := range dosagePerCowList {
+				if item.Date == date && item.Name == pastureName {
+					exist = true
+					number = append(number, util.Round(item.Psum/float64(item.CowNum), 2))
+					break
+				}
+			}
+			if !exist {
+				number = append(number, 0)
+			}
+		}
+		dataList = append(dataList, number)
+	}
+
+	data["data1"] = pastureNameList
+	data["data2"] = dateList
+	data["data3"] = dataList
+	return data
+}
+
+//-----------------------
+
+//各牧场年度用电量对比
+func (s *Service) GetElectricityYieldByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+round( IFNULL(SUM(w.elecConsumption),0) ,2)psum,
+  p.name as name
+FROM
+  electricity w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and p.name <> '现代牧业' and (p.center = ? or ? = '' )
+GROUP BY ms.pastureId  `
+
+	err = s.d.DB.Debug().Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		nowYearData = append(nowYearData, util.Round(nowYear.Psum, 2))
+		all += nowYear.Psum
+		exist := false
+		for _, lastYear := range lastYearList {
+			if lastYear.Name == nowYear.Name {
+				exist = true
+				lastYearData = append(lastYearData, util.Round(lastYear.Psum, 2))
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = pastureName
+	resp.LastYear = lastYearData
+	resp.NowYear = nowYearData
+	resp.All = util.Round(all, 2)
+	return resp, nil
+}
+
+func (s *Service) GetElectricitySingleCowByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+round( IFNULL(SUM(w.elecConsumption),0) ,2)psum,
+  p.name,ms.pastureId
+FROM
+  electricity w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and  ms.meterType = '电表'  and p.name <> '现代牧业' and (p.center = ? or ? = '' ) and p.vendor = 1  and IsEnergy = 0 
+GROUP BY ms.pastureId  `
+	err = s.d.DB.Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	lastCowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name,fd.pastureId from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ? and (p.center = ? or ? = '' ) and p.vendor = 1  and IsEnergy = 0  group by p.id `,
+		startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name,fd.pastureId  from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ? and (p.center = ? or ? = '' ) and p.vendor = 1 and IsEnergy = 0 group by  p.id  `,
+		startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastCowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll, lastCowNumAll int64
+	for _, item := range cowNumList {
+		//cowNumAll += item.FeedSum.CowNum
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	lastCowNum := make(map[string]int64, 0)
+	for _, item := range lastCowNumList {
+		//lastCowNumAll += item.FeedSum.CowNum
+		lastCowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all, lastAll float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		if _, ok := cowNum[nowYear.Name]; ok {
+			all += nowYear.Psum
+			cowNumAll += cowNum[nowYear.Name]
+			nowYearData = append(nowYearData, util.Round(nowYear.Psum/float64(cowNum[nowYear.Name]), 3))
+		} else {
+			nowYearData = append(nowYearData, 0)
+		}
+		exist := false
+		for _, lastYear := range lastYearList {
+			if lastYear.Name == nowYear.Name {
+				exist = true
+				if _, ok := lastCowNum[lastYear.Name]; ok {
+					lastAll += nowYear.Psum
+					lastCowNumAll += lastCowNum[nowYear.Name]
+					lastYearData = append(lastYearData, util.Round(lastYear.Psum/float64(lastCowNum[nowYear.Name]), 3))
+				} else {
+					lastYearData = append(lastYearData, 0)
+				}
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.LastYear = append(resp.LastYear, util.Round(lastAll/float64(lastCowNumAll), 3))
+	//resp.LastYear = append(resp.LastYear, lastYearData...)
+	for _, item := range lastYearData {
+		resp.LastYear = append(resp.LastYear, util.Round(item, 3))
+	}
+
+	resp.NowYear = append(resp.NowYear, util.Round(all/float64(cowNumAll), 3))
+
+	num := 0.0
+	for _, item := range nowYearData {
+		num += item
+		resp.NowYear = append(resp.NowYear, util.Round(item, 3))
+	}
+	fmt.Println(num)
+	resp.All = util.Round(all, 3)
+	cowNumAll1 := float64(cowNumAll)
+	resp.Line = util.Round(all/cowNumAll1, 3)
+	return resp, nil
+}
+
+//单头牛电费
+func (s *Service) GetElectricityRateByPasture(center, startTime, endTime string) (*http.GetWaterRateByPastureResp, error) {
+
+	resp := new(http.GetWaterRateByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?  and (p.center = ? or ? = '' )  group by pastureid    `,
+		startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll int64
+	for _, item := range cowNumList {
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Debug().Raw(`select sum(HSL) HSL  ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='电费'  and (p.center = ? or ? = '' )  group by fd.pastureId order by  p.id`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var hslList []float64
+	var all float64
+	for _, feequery := range feequeryList {
+		pastureName = append(pastureName, feequery.Pasture.Name)
+		var hsl float64
+		hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+		if err != nil {
+			logs.Error("转换失败:", err)
+			hslList = append(hslList, 0)
+		}
+
+		if _, ok := cowNum[feequery.Name]; ok {
+			all += hsl
+			cowNumAll += cowNum[feequery.Pasture.Name]
+			hslList = append(hslList, hsl/float64(cowNum[feequery.Pasture.Name]))
+		} else {
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, item := range pastureList {
+		exist := false
+		for _, f := range feequeryList {
+			if item.Name == f.Name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, item.Name)
+			hslList = append(hslList, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.Actual = append(resp.Actual, util.Round(all/float64(cowNumAll), 3))
+	for _, item := range hslList {
+		resp.Actual = append(resp.Actual, util.Round(item, 3))
+	}
+	resp.Line = util.Round(all/float64(cowNumAll), 3)
+	//resp.Actual = append(resp.Actual, hslList...)
+	return resp, err
+}
+
+func (s *Service) GetElectricityRateCompleteByPasture(center, startTime, endTime string) (*http.GetWaterRateCompleteByPastureResp, error) {
+	resp := new(http.GetWaterRateCompleteByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(HSL),0) HSL ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='电费'   and (p.center = ? or ? = '' )  group by fd.pastureId`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '电费' and mb.budgetMonth between ? and ?  and (p.center = ? or ? = '' )   group by mb.pastureId`, startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var budgetList, actualList, complete []float64
+	var budgetAll, actualAll float64
+	for _, monthBudget := range monthBudgetList {
+		pastureName = append(pastureName, monthBudget.Name)
+		budgetList = append(budgetList, util.Round(monthBudget.MonthBudget/10000, 2))
+		budgetAll += monthBudget.MonthBudget
+		exist := false
+		var hsl float64
+		for _, feequery := range feequeryList {
+			if feequery.Name == monthBudget.Name {
+				exist = true
+
+				hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+				if err != nil {
+					actualList = append(actualList, 0)
+					logs.Error("转换失败:", err)
+				} else {
+					actualAll += hsl
+					actualList = append(actualList, util.Round(hsl/10000, 2))
+					continue
+				}
+
+				break
+			}
+		}
+		if !exist {
+			actualList = append(actualList, 0)
+		}
+
+		//预算减实际除预算加1
+		if monthBudget.MonthBudget > 0 && hsl > 0 {
+			complete = append(complete, util.Round(((monthBudget.MonthBudget-hsl)/monthBudget.MonthBudget+1)*100, 2))
+		} else {
+			complete = append(complete, 0)
+		}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			actualList = append(actualList, 0)
+			budgetList = append(budgetList, 0)
+			complete = append(complete, 0)
+		}
+	}
+
+	//resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+
+	//resp.Actual = append(resp.Actual, util.Round(actualAll/10000, 2))
+	resp.Actual = append(resp.Actual, actualList...)
+
+	//resp.Budget = append(resp.Budget, util.Round(budgetAll/10000, 2))
+	resp.Budget = append(resp.Budget, budgetList...)
+
+	//if budgetAll > 0 && actualAll > 0 {
+	//	resp.Complete = append(resp.Complete, util.Round(((budgetAll-actualAll)/budgetAll+1)*100, 2))
+	//} else {
+	//	resp.Complete = append(resp.Complete, 0)
+	//}
+
+	resp.Complete = append(resp.Complete, complete...)
+	return resp, nil
+}
+
+//每月单头牛用电量对比
+func (s *Service) GetElectricityPerHeadByPasture(pastureId, startTime, endTime string) (map[string]interface{}, error) {
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	dosagePerCowList := make([]*dosagePerCow, 0)
+
+	err = s.d.DB.Debug().Raw(`SELECT
+round( IFNULL(SUM(w.elecConsumption),0) ,2)psum,
+  p.name,DATE_FORMAT( w.date, '%Y-%m') date,
+	ifnull((select sum(cowNum)  from feed_sum  where DATE_FORMAT( feedDay, '%Y-%m') = DATE_FORMAT( w.date, '%Y-%m') and pastureId = p.id ),0)cowNum
+FROM
+  electricity w
+  INNER JOIN measure ms
+    ON w.measureId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  (w.date between ? and ? ) AND ms.useType = '1级表' and p.name <> '现代牧业'   and  FIND_IN_SET(p.id,?)  
+GROUP BY DATE_FORMAT( w.date, '%Y-%m'),ms.pastureId order by  DATE_FORMAT( w.date, '%Y-%m'),p.id  `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), pastureId).Find(&dosagePerCowList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	data := dosagePerCowFormat(dosagePerCowList)
+	return data, nil
+}
+
+//--------------------------------------- 维修
+//各牧场年度维修对比
+func (s *Service) GetWxYieldByPasture(deptname, center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	//lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+  round(ifnull(SUM( pu.sumPrice - pu.quitNumber * pu.price),0),4) psum,
+  p.name
+FROM
+  partuse pu
+  INNER JOIN bigpartuse bpu
+    ON pu.bigId = bpu.id 
+  INNER JOIN pasture p
+    ON bpu.pastureId = p.id
+	#INNER JOIN department dpt
+		#on dpt.id = bpu.departmentId
+WHERE bpu.useType <> 3  and p.IsEnergy = 0
+	AND (SELECT name FROM department d WHERE d.id=bpu.departmentId) not in ('挤奶处','牧场办公室','财务部','餐厅','信息处')
+  AND (
+    pu.useTypeV = '维修'
+    OR pu.useTypeV = '保养'
+  ) 
+and ( bpu.receiveTime  between ? and ?)	
+	AND (bpu.departmentId in (select id from department where pastureId = bpu.pastureId and name = ?  ) 
+or if(? = 1 ,bpu.departmentId in(select id from department where  pastureId = bpu.pastureId and name != '挤奶处' and name != '牧场办公室' ),0=1)  or ?=''	 ) and p.name <> '现代牧业' and (p.center = ? or ? = '' ) and pu.dflag != 1
+GROUP BY bpu.pastureId `
+
+	err = s.d.DB.Debug().Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), deptname, deptname, deptname, center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Debug().Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '维修费' and mb.budgetMonth between ? and ?  AND (mb.deptId in (select id from department where pastureId = mb.pastureId and name = ?  ) 
+or if(? = 1 ,mb.deptId in(select id from department where  pastureId = mb.pastureId and name != '挤奶处' and name != '牧场办公室' ),0=1)  or ?=''	 )    and (p.center = ? or ? = '' )   group by mb.pastureId`,
+		startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), deptname, deptname, deptname, center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	//err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+	//	enddate.AddDate(-1, 0, 0).Format("2006-01-02"), deptname, deptname, deptname, deptname, deptname, center, center).Find(&lastYearList).Error
+	//if err != nil {
+	//	logs.Error(err)
+	//	return nil, err
+	//}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where("IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		nowYearData = append(nowYearData, util.Round(nowYear.Psum, 2))
+		all += nowYear.Psum
+		//exist := false
+		//for _, lastYear := range lastYearList {
+		//	if lastYear.Name == nowYear.Name {
+		//		exist = true
+		//
+		//		break
+		//	}
+		//}
+		//if !exist {
+		//	lastYearData = append(lastYearData, 0)
+		//}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			//lastYearData = append(lastYearData, 0)
+		}
+	}
+	for _, name := range pastureName {
+		exist := false
+		for _, monthBudget := range monthBudgetList {
+			if monthBudget.Name == name {
+				exist = true
+				lastYearData = append(lastYearData, util.Round(monthBudget.MonthBudget, 2))
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = pastureName
+	resp.LastYear = lastYearData
+	resp.NowYear = nowYearData
+	resp.All = util.Round(all, 2)
+	return resp, nil
+}
+
+func (s *Service) GetWxSingleCowByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	//lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+  round(ifnull(SUM( pu.sumPrice - pu.quitNumber * pu.price),0),4) psum,
+  p.name
+FROM
+  partuse pu
+  INNER JOIN bigpartuse bpu
+    ON pu.bigId = bpu.id 
+  INNER JOIN pasture p
+    ON bpu.pastureId = p.id
+	#INNER JOIN department dpt
+		#on dpt.id = bpu.departmentId
+WHERE bpu.useType <> 3
+  AND (
+    pu.useTypeV = '维修'
+    OR pu.useTypeV = '保养'
+  ) 
+and ( bpu.receiveTime  between ? and ?)	
+  and p.name <> '现代牧业'   and (p.center = ? or ? = '' ) and pu.dflag != 1
+	AND (SELECT name FROM department d WHERE d.id=bpu.departmentId) not in ('挤奶处','牧场办公室','财务部','餐厅','信息处')
+GROUP BY bpu.pastureId `
+
+	err = s.d.DB.Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	//lastCowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?
+   and (p.center = ? or ? = '' )  
+ group by pastureid `, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '维修费' and mb.budgetMonth between ? and ?    and (p.center = ? or ? = '' )   group by mb.pastureId`,
+		startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll int64
+	for _, item := range cowNumList {
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	//lastCowNum := make(map[string]int64, 0)
+	//for _, item := range lastCowNumList {
+	//	lastCowNumAll += item.FeedSum.CowNum
+	//	lastCowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	//}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all, lastAll float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		if _, ok := cowNum[nowYear.Name]; ok {
+			all += nowYear.Psum
+			cowNumAll += cowNum[nowYear.Name]
+			nowYearData = append(nowYearData, nowYear.Psum/float64(cowNum[nowYear.Name]))
+		} else {
+			nowYearData = append(nowYearData, 0)
+		}
+	}
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	for _, name := range pastureName {
+		exist := false
+		for _, monthBudget := range monthBudgetList {
+			if monthBudget.Name == name {
+				exist = true
+				if _, ok := cowNum[monthBudget.Name]; ok {
+					lastAll += monthBudget.MonthBudget
+					lastYearData = append(lastYearData, monthBudget.MonthBudget/float64(cowNum[monthBudget.Name]))
+				} else {
+					lastYearData = append(lastYearData, 0)
+				}
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.LastYear = append(resp.LastYear, util.Round(lastAll/float64(cowNumAll), 3))
+	//resp.LastYear = append(resp.LastYear, lastYearData...)
+	for _, item := range lastYearData {
+		resp.LastYear = append(resp.LastYear, util.Round(item, 3))
+	}
+
+	resp.NowYear = append(resp.NowYear, util.Round(all/float64(cowNumAll), 3))
+	for _, item := range nowYearData {
+		resp.NowYear = append(resp.NowYear, util.Round(item, 3))
+	}
+	resp.All = all
+	resp.Line = util.Round(all/float64(cowNumAll), 2)
+	return resp, nil
+}
+
+//每月单头牛维修对比
+func (s *Service) GetWxPerHeadByPasture(pastureId, startTime, endTime string) (map[string]interface{}, error) {
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	dosagePerCowList := make([]*dosagePerCow, 0)
+
+	err = s.d.DB.Debug().Raw(`SELECT
+  round(ifnull(SUM( pu.sumPrice - pu.quitNumber * pu.price),0),4) psum,
+  p.name,DATE_FORMAT(  bpu.receiveTime, '%Y-%m') date,
+		ifnull((select sum(cowNum)  from feed_sum  where DATE_FORMAT( feedDay, '%Y-%m') = DATE_FORMAT( bpu.receiveTime, '%Y-%m') and pastureId = p.id ),0)cowNum
+FROM
+  partuse pu
+  INNER JOIN bigpartuse bpu
+    ON pu.bigId = bpu.id 
+  INNER JOIN pasture p
+    ON bpu.pastureId = p.id
+	#INNER JOIN department dpt
+		#on dpt.id = bpu.departmentId
+WHERE bpu.useType <> 3
+  AND (
+    pu.useTypeV = '维修'
+    OR pu.useTypeV = '保养'
+  ) 
+and ( bpu.receiveTime  between ? and ?)	
+	AND (SELECT name FROM department d WHERE d.id=bpu.departmentId) not in ('挤奶处','牧场办公室','财务部','餐厅','信息处')
+  and p.name <> '现代牧业' and  FIND_IN_SET(p.id,?)   and pu.dflag != 1
+GROUP BY DATE_FORMAT( bpu.receiveTime, '%Y-%m'),p.id order by  DATE_FORMAT( bpu.receiveTime, '%Y-%m'),p.id `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), pastureId).Find(&dosagePerCowList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	data := dosagePerCowFormat(dosagePerCowList)
+	return data, nil
+}
+
+//各牧场年度燃动费对比
+func (s *Service) GetIgnitionYieldByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Debug().Raw(`select sum(HSL) HSL  ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='燃动费'  and (p.center = ? or ? = '' )  group by fd.pastureId order by p.id`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '燃动费' and mb.budgetMonth between ? and ?  and (p.center = ? or ? = '' )   group by mb.pastureId`,
+		startTime, endTime, center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var hslList, monthBudgets []float64
+	var all float64
+	for _, feequery := range feequeryList {
+		pastureName = append(pastureName, feequery.Pasture.Name)
+		var hsl float64
+		hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+		if err != nil {
+			logs.Error("转换失败:", err)
+			hslList = append(hslList, 0)
+			continue
+		}
+		all += util.Round(hsl, 2)
+		hslList = append(hslList, hsl)
+	}
+
+	for _, item := range pastureList {
+		exist := false
+		for _, f := range feequeryList {
+			if item.Name == f.Name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, item.Name)
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, name := range pastureName {
+		exist := false
+		for _, monthBudget := range monthBudgetList {
+			if name == monthBudget.Name {
+				exist = true
+				monthBudgets = append(monthBudgets, util.Round(monthBudget.MonthBudget, 2))
+				break
+			}
+		}
+		if !exist {
+			monthBudgets = append(monthBudgets, 0)
+		}
+	}
+
+	resp.Pasture = pastureName
+	resp.LastYear = monthBudgets
+	resp.NowYear = hslList
+	resp.All = util.Round(all, 2)
+	return resp, nil
+}
+
+//各牧场年度柴油对比
+func (s *Service) GetDieselYieldByPasture(center, startTime, endTime string) (*http.StatementResp, error) {
+	resp := new(http.StatementResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+	nowYearList := make([]*pastureStatistics, 0)
+	lastYearList := make([]*pastureStatistics, 0)
+
+	sqlstr := `SELECT
+ROUND( IFNULL(SUM(w.oilAmount),0) ,2)psum,
+  p.name
+FROM
+  diesel w
+  INNER JOIN oilcard ms
+    ON w.oilcardId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  w.selTime between ? and ?  and p.name <> '现代牧业' and (p.center = ? or ? = '' )
+GROUP BY ms.pastureId `
+
+	err = s.d.DB.Debug().Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&nowYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	err = s.d.DB.Raw(sqlstr, startdate.AddDate(-1, 0, 0).Format("2006-01-02"),
+		enddate.AddDate(-1, 0, 0).Format("2006-01-02"), center, center).Find(&lastYearList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var nowYearData, lastYearData []float64
+	var all float64
+	for _, nowYear := range nowYearList {
+		pastureName = append(pastureName, nowYear.Name)
+		nowYearData = append(nowYearData, util.Round(nowYear.Psum, 2))
+		all += nowYear.Psum
+		exist := false
+		for _, lastYear := range lastYearList {
+			if lastYear.Name == nowYear.Name {
+				exist = true
+				lastYearData = append(lastYearData, util.Round(lastYear.Psum, 2))
+				break
+			}
+		}
+		if !exist {
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	for _, pasture := range pastureList {
+		exist := false
+		for _, name := range pastureName {
+			if pasture.Name == name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, pasture.Name)
+			nowYearData = append(nowYearData, 0)
+			lastYearData = append(lastYearData, 0)
+		}
+	}
+
+	resp.Pasture = pastureName
+	resp.LastYear = lastYearData
+	resp.NowYear = nowYearData
+	resp.All = util.Round(all, 2)
+	return resp, nil
+}
+
+//单头牛柴油
+func (s *Service) GetDieselRateByPasture(center, startTime, endTime string) (*http.GetWaterRateByPastureResp, error) {
+
+	resp := new(http.GetWaterRateByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?   and (p.center = ? or ? = '' )  group by pastureid    `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll int64
+	for _, item := range cowNumList {
+
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where("IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	dieselList := make([]*pastureStatistics, 0)
+	sqlstr := `SELECT
+ROUND( IFNULL(SUM(w.oilAmount),0) ,2)psum,
+  p.name
+FROM
+  diesel w
+  INNER JOIN oilcard ms
+    ON w.oilcardId = ms.id 
+    INNER JOIN pasture p
+    ON ms.pastureId = p.id
+WHERE  
+  w.selTime between ? and ?  and p.name <> '现代牧业' and (p.center = ? or ? = '' )
+GROUP BY ms.pastureId `
+
+	err = s.d.DB.Debug().Raw(sqlstr, startdate.Format("2006-01-02"), enddate.Format("2006-01-02"), center, center).Find(&dieselList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	var pastureName []string
+	var hslList []float64
+	var all float64
+	for _, diesel := range dieselList {
+		pastureName = append(pastureName, diesel.Name)
+		if _, ok := cowNum[diesel.Name]; ok {
+			all += diesel.Psum
+			cowNumAll += cowNum[diesel.Name]
+			hslList = append(hslList, diesel.Psum/float64(cowNum[diesel.Name]))
+		} else {
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, item := range pastureList {
+		exist := false
+		for _, f := range dieselList {
+			if item.Name == f.Name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, item.Name)
+			hslList = append(hslList, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.Actual = append(resp.Actual, util.Round(all/float64(cowNumAll), 3))
+	for _, item := range hslList {
+		resp.Actual = append(resp.Actual, util.Round(item, 3))
+	}
+	resp.Line = util.Round(all/float64(cowNumAll), 3)
+
+	return resp, err
+}
+
+//单头牛燃动费
+func (s *Service) GetIgnitionRateByPasture(center, startTime, endTime string) (*http.GetWaterRateCompleteByPastureResp, error) {
+
+	resp := new(http.GetWaterRateCompleteByPastureResp)
+
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	cowNumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Raw(`select sum(cowNum)cowNum  ,p.name from feed_sum fd join pasture p on p.id = fd.pastureid 
+ where fd.feedDay  between  ? and ?   and (p.center = ? or ? = '' )  group by pastureid    `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), center, center).Find(&cowNumList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	cowNum := make(map[string]int64, 0)
+	var cowNumAll int64
+	for _, item := range cowNumList {
+
+		cowNum[item.Pasture.Name] = item.FeedSum.CowNum
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where(" vendor = 1 ").Where(" IsEnergy = 0").Order("id").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	feequeryList := make([]*model.FeeQueryAndPasture, 0)
+	err = s.d.DB.Debug().Raw(`select sum(HSL) HSL  ,p.name from feequery fd join pasture p on p.id = fd.pastureid 
+ where fd.Date  between  ? and  ? and fd.FYLX ='燃动费'  and (p.center = ? or ? = '' )  group by fd.pastureId order by p.id`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&feequeryList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	monthBudgetList := make([]*monthBudget, 0)
+	err = s.d.DB.Raw(`select ifnull(sum(monthBudget),0) monthBudget,p.name  from month_budget mb join pasture p on p.id = mb.pastureId 
+ where mb.feeType = '燃动费' and mb.budgetMonth between ? and ?  and (p.center = ? or ? = '' )   group by mb.pastureId`,
+		startdate.Format("2006-01"), enddate.Format("2006-01"), center, center).Find(&monthBudgetList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	var pastureName []string
+	var hslList []float64
+	var monthBudgets []float64
+	var all, monthBudgetAll float64
+	for _, feequery := range feequeryList {
+		pastureName = append(pastureName, feequery.Name)
+		var hsl float64
+		hsl, err = strconv.ParseFloat(feequery.HSL, 64)
+		if err != nil {
+			logs.Error("转换失败:", err)
+			hslList = append(hslList, 0)
+		}
+
+		if _, ok := cowNum[feequery.Name]; ok {
+			all += hsl
+			cowNumAll += cowNum[feequery.Name]
+			hslList = append(hslList, hsl/float64(cowNum[feequery.Name]))
+		} else {
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, item := range pastureList {
+		exist := false
+		for _, f := range feequeryList {
+			if item.Name == f.Name {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			pastureName = append(pastureName, item.Name)
+			hslList = append(hslList, 0)
+		}
+	}
+
+	for _, name := range pastureName {
+		exist := false
+		for _, monthBudget := range monthBudgetList {
+			if name == monthBudget.Name {
+				exist = true
+				if _, ok := cowNum[name]; ok {
+					monthBudgetAll += monthBudget.MonthBudget
+					monthBudgets = append(monthBudgets, monthBudget.MonthBudget/float64(cowNum[name]))
+				} else {
+					monthBudgets = append(monthBudgets, 0)
+				}
+				break
+			}
+		}
+		if !exist {
+			monthBudgets = append(monthBudgets, 0)
+		}
+	}
+
+	resp.Pasture = append(resp.Pasture, "集团")
+	resp.Pasture = append(resp.Pasture, pastureName...)
+	resp.Actual = append(resp.Actual, util.Round(all/float64(cowNumAll), 3))
+	for _, item := range hslList {
+		resp.Actual = append(resp.Actual, util.Round(item, 3))
+	}
+	resp.Line = util.Round(all/float64(cowNumAll), 3)
+
+	resp.Budget = append(resp.Budget, util.Round(monthBudgetAll/float64(cowNumAll), 3))
+	for _, item := range monthBudgets {
+		resp.Budget = append(resp.Budget, util.Round(item, 3))
+	}
+
+	return resp, err
+}
+
+//每月单头牛柴油对比
+func (s *Service) GetDieselPerHeadByPasture(pastureId, startTime, endTime string) (map[string]interface{}, error) {
+	layout := "2006-01-02"
+	startdate, err := time.Parse(layout, startTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate, err := time.Parse(layout, endTime)
+	if err != nil {
+		logs.Error("时间转换失败:", err)
+	}
+	enddate = enddate.AddDate(0, 1, -1)
+
+	dosagePerCowList := make([]*dosagePerCow, 0)
+
+	err = s.d.DB.Debug().Raw(`SELECT
+round( IFNULL(SUM(w.oilAmount),0) ,2)psum,
+  p.name,DATE_FORMAT( w.selTime, '%Y-%m') date,
+	ifnull((select sum(cowNum)  from feed_sum  where DATE_FORMAT( feedDay, '%Y-%m') = DATE_FORMAT( w.selTime, '%Y-%m') and pastureId = p.id ),0)cowNum
+FROM
+diesel w
+INNER JOIN oilcard ms
+ON w.oilcardId = ms.id
+INNER JOIN pasture p
+ON ms.pastureId = p.id
+WHERE  
+  (w.selTime between ? and ? )  and p.name <> '现代牧业'   and  FIND_IN_SET(p.id,?)  
+GROUP BY DATE_FORMAT( w.selTime, '%Y-%m'),ms.pastureId order by  DATE_FORMAT( w.selTime, '%Y-%m'),p.id  `, startdate.Format("2006-01-02"),
+		enddate.Format("2006-01-02"), pastureId).Find(&dosagePerCowList).Error
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+	data := dosagePerCowFormat(dosagePerCowList)
+	return data, nil
+}

+ 541 - 48
apiserver/service/contract.go

@@ -3,6 +3,8 @@ package service
 import (
 	"encoding/json"
 	"fmt"
+	"github.com/astaxie/beego/logs"
+	"github.com/pkg/errors"
 	"kpt.xdmy/apiserver/config"
 	"strconv"
 	"strings"
@@ -27,7 +29,7 @@ var (
 			BussTp: ContractToAspBussTp,
 			//Url:    ContractToAspUrl,
 		},
-		DATA: &http.ContractDataToASP{},
+		DATA: []*http.ContractDataToASP{},
 	}
 	loc, _ = time.LoadLocation("Local")
 )
@@ -63,7 +65,7 @@ func GetPastureBigContract(contractCode string) ([]*model.PastureBigcontract, er
 		" select pastureId as pasture_id  ,enable    FROM bigcontract WHERE  contractCode LIKE '%s'   and SHStatus  = 7   GROUP BY pastureId "+
 		" union all "+
 		" SELECT pasture_id, enable FROM pasture_bigcontract WHERE bigcontract_id IN (SELECT id FROM bigcontract WHERE contractCode LIKE  '%s' AND enable = 1  and SHStatus  = 7  )  )t"+
-		" join pasture p on p.id = t.pasture_id   "+
+		" join pasture p on p.id = t.pasture_id  "+
 		" group by pasture_id", "%"+contractCode+"%", "%"+contractCode+"%")
 	if err := s.d.DB.Raw(SQL).Find(&pastureBigContract).Error; err != nil {
 		return nil, err
@@ -169,7 +171,7 @@ func AutoContractToASP() {
 				}
 
 				// 发送数据至SAP
-				errData, bigContracts, contracts := PushContractDataToSAP(bigContract, contractInfo, contractCode)
+				errData, bigContracts, contracts := PushContractDataToSAP(bigContract, contractInfo, contractCode, false)
 				for _, data := range errData {
 					errDataList[contractCode] = append(errDataList[contractCode], data...)
 				}
@@ -224,14 +226,19 @@ func AutoContractToASP() {
 }
 
 // PushContractDataToSAP 同步数据给SAP
-func PushContractDataToSAP(bigContract *model.BigContract, contractInfo *ContractInfo, contractCode string) (map[string][]*model.ContractSapErr, []*model.BigContract, []*model.Contract) {
+func PushContractDataToSAP(bigContract *model.BigContract, contractInfo *ContractInfo, contractCode string, hand bool) (map[string][]*model.ContractSapErr, []*model.BigContract, []*model.Contract) {
 	errMap := make(map[string][]*model.ContractSapErr, 0)
 	errBigContract := make([]*model.BigContract, 0)
 	errContract := make([]*model.Contract, 0)
 
-	for _, contract := range contractInfo.Contract {
-		if contract.IsToSap == 1 {
-			continue
+	contractList := make([]*model.Contract, 0)
+	i := 0
+	for n, contract := range contractInfo.Contract {
+		i++
+		if !hand {
+			if contract.IsToSap == 1 {
+				continue
+			}
 		}
 		LOEKZ := ""
 		if contract.Enable == 0 {
@@ -258,7 +265,7 @@ func PushContractDataToSAP(bigContract *model.BigContract, contractInfo *Contrac
 		} else {
 			isZeroStock = 0
 		}
-		//LOEKZ = "X"
+
 		contractDataToASP := &http.ContractDataToASP{
 			MATNR: contract.PartCode,
 			LIFNR: contractInfo.Provider.SapCode,
@@ -275,52 +282,64 @@ func PushContractDataToSAP(bigContract *model.BigContract, contractInfo *Contrac
 			ESOKZ: fmt.Sprintf("%d", isZeroStock),
 			MEINS: contract.Unit,
 			Code:  bigContract.ContractCode,
+			RCKEY: fmt.Sprintf("%d", i+1),
 		}
-		sapContractReq.DATA = contractDataToASP
 
-		rp := &http.SapContractResp{}
+		contractList = append(contractList, contract)
+		sapContractReq.DATA = append(sapContractReq.DATA, contractDataToASP)
+		fmt.Println(n, len(contractInfo.Contract))
+		if i == 300 || n+1 == len(contractInfo.Contract) {
+			i = 0
+
+			rp := &http.SapContractResp{}
+			rbyte, _ := json.Marshal(sapContractReq)
+			fmt.Println(string(rbyte))
+			if err := s.SyncSap(sapContractReq, rp, sapContractReq); err != nil {
+				log.Errorf("AutoContractToASP SyncSap Err:%v ", err)
+				//continue
+			}
+			log.Info(rp)
+
+			if rp.Dest.Status != "S" {
+				log.Errorf("AutoContractToASP SyncSap Error:%v", rp)
+				for _, contract1 := range contractList {
+					contract1.PastureID = contractInfo.Pasture.ID
+					errMap[contractCode] = append(errMap[contractCode], &model.ContractSapErr{
+						ContractID:    contract1.ID,
+						PastureID:     contractInfo.Pasture.ID,
+						PastureName:   contractInfo.Pasture.Name,
+						PartID:        contract1.PartID,
+						PartName:      contract1.PartName,
+						PartCode:      contract1.PartCode,
+						Specification: contract1.Specification,
+						Price:         contract1.Price,
+						BrandID:       contract1.BrandID,
+						Brand:         contract1.Brand,
+						InventoryType: contract1.InventoryType,
+						PlanAmount:    contract1.PlanAmount,
+						Remark:        contract1.Remark,
+						Enable:        contract1.Enable,
+						Unit:          contract1.Unit,
+						IsZeroStock:   contract1.IsZeroStock,
+						ChangeID:      contract1.ChangeID,
+						SapText:       rp.MessText,
+						ContractCode:  contractCode,
+					})
+					if rp.Dest.Status == "" {
+						errContract = append(errContract, contract1)
+					}
+				}
+			}
 
-		rbyte, _ := json.Marshal(sapContractReq)
-		fmt.Println(string(rbyte))
-		if err := s.SyncSap(sapContractReq, rp, sapContractReq); err != nil {
-			log.Errorf("AutoContractToASP SyncSap Err:%v contract:%v", err, contract)
-			//continue
-		}
-		log.Info(rp)
-
-		if rp.Dest.Status != "S" {
-			log.Errorf("AutoContractToASP SyncSap Error:%v,contract:%v", rp, contract)
-			contract.PastureID = contractInfo.Pasture.ID
-			errMap[contractCode] = append(errMap[contractCode], &model.ContractSapErr{
-				ContractID:    contract.ID,
-				PastureID:     contractInfo.Pasture.ID,
-				PastureName:   contractInfo.Pasture.Name,
-				PartID:        contract.PartID,
-				PartName:      contract.PartName,
-				PartCode:      contract.PartCode,
-				Specification: contract.Specification,
-				Price:         contract.Price,
-				BrandID:       contract.BrandID,
-				Brand:         contract.Brand,
-				InventoryType: contract.InventoryType,
-				PlanAmount:    contract.PlanAmount,
-				Remark:        contract.Remark,
-				Enable:        contract.Enable,
-				Unit:          contract.Unit,
-				IsZeroStock:   contract.IsZeroStock,
-				ChangeID:      contract.ChangeID,
-				SapText:       rp.MessText,
-				ContractCode:  contractCode,
-			})
-		}
-		if rp.Dest.Status == "" {
-			errContract = append(errContract, contract)
+			if len(errContract) > 0 {
+				errBigContract = append(errBigContract, bigContract)
+			}
+			contractList = make([]*model.Contract, 0)
+			sapContractReq.DATA = make([]*http.ContractDataToASP, 0)
 		}
+		//break
 	}
 
-	if len(errContract) > 0 {
-		errBigContract = append(errBigContract, bigContract)
-	}
 	return errMap, errBigContract, errContract
 }
 
@@ -340,3 +359,477 @@ func RemoveRepeatedElement1(arr []string) (newArr []string) {
 	}
 	return
 }
+
+func (s *Service) PostPushContractDataToSAP(pastureId, providerId int64, contractIdList []int64) error {
+	sapContractReq.Url = config.Conf.Http.Routing + "/SRM/MM018/PurchaseInfo"
+	contractList := make([]*model.Contract, 0)
+	err := s.d.DB.Debug().Where(" id in (?) ", contractIdList).Find(&contractList).Error
+	if err != nil {
+		logs.Error(err)
+		return err
+	}
+
+	pasture := new(model.Pasture)
+	err = s.d.DB.Where("id = ? ", pastureId).First(&pasture).Error
+	if err != nil {
+		logs.Error(err)
+		return err
+	}
+
+	provider := new(model.Provider)
+	err = s.d.DB.Where("id = ? ", providerId).First(&provider).Error
+	if err != nil {
+		logs.Error(err)
+		return err
+	}
+
+	contractMap := make(map[int][]*model.Contract, 0)
+	for _, contract := range contractList {
+		contractMap[contract.BigID] = append(contractMap[contract.BigID], contract)
+	}
+
+	pastureBigcontractList := make([]*model.PastureBigcontract, 0)
+	for bigId, m := range contractMap {
+		bigContract := new(model.BigContract)
+		err := s.d.DB.Where(" id = ?  ", bigId).First(&bigContract).Error
+		if err != nil {
+			logs.Error(err)
+			return err
+		}
+
+		if len(pastureBigcontractList) == 0 {
+			contractCode := strings.Split(bigContract.ContractCode, "-")[0]
+			pastureBigcontractList, _ = GetPastureBigContract(contractCode)
+		}
+		exist := false
+		for _, item := range pastureBigcontractList {
+			if item.PastureId == int(pastureId) {
+				exist = true
+				break
+			}
+		}
+		if !exist {
+			return errors.New("牧场没有该合同!")
+		}
+
+		contractInfo := new(ContractInfo)
+		contractInfo.Contract = m
+		contractInfo.Provider = provider
+		contractInfo.Pasture = pasture
+		fmt.Println(contractInfo)
+		PushContractDataToSAP(bigContract, contractInfo, bigContract.ContractCode, true)
+	}
+
+	return nil
+}
+
+//
+//package service
+//
+//import (
+//	"encoding/json"
+//	"fmt"
+//	"github.com/astaxie/beego/logs"
+//	"github.com/pkg/errors"
+//	"kpt.xdmy/apiserver/config"
+//	"strconv"
+//	"strings"
+//	"time"
+//
+//	log "github.com/sirupsen/logrus"
+//	"kpt.xdmy/apiserver/model"
+//	"kpt.xdmy/apiserver/model/http"
+//)
+//
+//const (
+//	//ContractToAspUrl    = config.Conf.Http.Routing + "/SRM/MM018/PurchaseInfo"
+//	ContractToAspDestID = "EQMAN"
+//	ContractToAspBussTp = "MM018"
+//	ContractLimit       = 10
+//)
+//
+//var (
+//	sapContractReq = &http.SapContractReq{
+//		Dest: &http.Dest{
+//			DestID: ContractToAspDestID,
+//			BussTp: ContractToAspBussTp,
+//			//Url:    ContractToAspUrl,
+//		},
+//		DATA: &http.ContractDataToASP{},
+//	}
+//	loc, _ = time.LoadLocation("Local")
+//)
+//
+//type ContractInfo struct {
+//	PastureBigContract *model.PastureBigcontract // 牧场和合同关联表
+//	Contract           []*model.Contract         // 合同子表
+//	Provider           *model.Provider           // 供应商
+//	Pasture            *model.Pasture            // 牧场
+//}
+//
+//// GetBigContractData 获取主合同信息
+//func GetBigContractData() []*model.BigContract {
+//	bigContractData := make([]*model.BigContract, 0)
+//	if err := s.d.DB.Debug().Where("isToSap = ?", 0).Where("SHStatus = ?", 7).Find(&bigContractData).Debug().Error; err != nil {
+//		log.Errorf("AutoContractToASP Error:%v", err)
+//	}
+//
+//	for _, item := range bigContractData {
+//		if item.SHStatus == 7 && item.SHtype == 3 && item.CGChargedate.UnixNano() > time.Now().AddDate(0, 0, -5).UnixNano() {
+//			contractCodeSlice := strings.Split(item.ContractCode, "-")
+//			contractCode := contractCodeSlice[0]
+//			s.d.DB.Exec(`update contract  set isToSap = 0 where enable = 1 and bigid in(select id from bigContract  where contractCode like ? )`, "%"+contractCode+"%")
+//		}
+//	}
+//
+//	return bigContractData
+//}
+//
+//func GetPastureBigContract(contractCode string) ([]*model.PastureBigcontract, error) {
+//	pastureBigContract := make([]*model.PastureBigcontract, 0)
+//	SQL := fmt.Sprintf("select  t.* from( "+
+//		" select pastureId as pasture_id  ,enable    FROM bigcontract WHERE  contractCode LIKE '%s'   and SHStatus  = 7   GROUP BY pastureId "+
+//		" union all "+
+//		" SELECT pasture_id, enable FROM pasture_bigcontract WHERE bigcontract_id IN (SELECT id FROM bigcontract WHERE contractCode LIKE  '%s' AND enable = 1  and SHStatus  = 7  )  )t"+
+//		" join pasture p on p.id = t.pasture_id   "+
+//		" group by pasture_id", "%"+contractCode+"%", "%"+contractCode+"%")
+//	if err := s.d.DB.Raw(SQL).Find(&pastureBigContract).Error; err != nil {
+//		return nil, err
+//	}
+//
+//	return pastureBigContract, nil
+//}
+//
+//// GetContractInfo 获取合同相关信息
+//func GetContractInfo(bigContract *model.BigContract, pastureBigContract *model.PastureBigcontract) *ContractInfo {
+//	//wg := sync.WaitGroup{}
+//	//wg.Add(3)
+//	contractInfo := &ContractInfo{}
+//	// 获取牧场数据合同数据
+//	//go func() {
+//	pasture := &model.Pasture{
+//		ID: pastureBigContract.PastureId,
+//	}
+//	if err := s.d.DB.First(pasture).Error; err != nil {
+//		log.Errorf("AutoContractToASP Pasture Err:%v,bigContractData:%v", err, bigContract)
+//	}
+//	contractInfo.Pasture = pasture
+//	//	wg.Done()
+//	//}()
+//
+//	// 获取合同子表数据
+//	//go func() {
+//	contract := make([]*model.Contract, 0)
+//	if err := s.d.DB.Debug().Where("bigId = ?", bigContract.ID).Where("isToSap = ? ", 0).Find(&contract).Error; err != nil {
+//		log.Errorf("AutoContractToASP contract Err:%v,bigContractData:%v", err, bigContract)
+//	}
+//	contractInfo.Contract = contract
+//	//	wg.Done()
+//	//}()
+//
+//	// 获取供应商数据
+//	//go func() {
+//	provider := &model.Provider{
+//		ID: bigContract.ProviderID,
+//	}
+//	if err := s.d.DB.First(provider).Error; err != nil {
+//		log.Errorf("AutoContractToASP Provider Err:%v,bigContractData:%v", err, bigContract)
+//	}
+//	contractInfo.Provider = provider
+//	//	wg.Done()
+//	//}()
+//	//wg.Wait()
+//	return contractInfo
+//}
+//
+//// http://192.168.61.117/SAPQ0/SRM/MM018/PurchaseInfo
+//// AutoContractToASP 合同信息自动同步到ASP
+//func AutoContractToASP() {
+//	sapContractReq.Url = config.Conf.Http.Routing + "/SRM/MM018/PurchaseInfo"
+//
+//	bigContractData := GetBigContractData()
+//	ContractCodeMap := make(map[string][]*model.PastureBigcontract, 0)
+//	errDataList := make(map[string][]*model.ContractSapErr, 0)
+//
+//	errBigContract := make([]*model.BigContract, 0)
+//	errContract := make([]*model.Contract, 0)
+//
+//	for _, bigContract := range bigContractData {
+//		contractCode := bigContract.ContractCode
+//		if bigContract.SHStatus != 7 {
+//			continue
+//		}
+//
+//		var count int64
+//		s.d.DB.Debug().Table(new(model.BigContract).TableName()).Where("id =  ? ", bigContract.ID).Where("isToSap = ?", 0).Count(&count)
+//		if count == 0 {
+//			continue
+//		}
+//
+//		if strings.Contains(bigContract.ContractCode, "-") {
+//			contractCodeSlice := strings.Split(bigContract.ContractCode, "-")
+//			contractCode = contractCodeSlice[0]
+//		}
+//		var err error
+//		pastureBigContractSlice := make([]*model.PastureBigcontract, 0)
+//		if _, ok := ContractCodeMap[contractCode]; !ok {
+//			pastureBigContractSlice, err = GetPastureBigContract(contractCode)
+//			if err != nil {
+//				log.Errorf("AutoContractToASP pastureBigContractSlice Err:%v", err)
+//				continue
+//			}
+//			ContractCodeMap[contractCode] = append(ContractCodeMap[contractCode], pastureBigContractSlice...)
+//			//if err := s.d.DB.Debug().Table(new(model.BigContract).TableName()).Where("contractCode like  ? ", "%"+contractCode+"%").Update("isToSap", 1).Error; err != nil {
+//			//	log.Errorf("AutoContractToASP SQLUpdate Error:%v", err)
+//			//}
+//		}
+//		if err := s.d.DB.Debug().Table(new(model.BigContract).TableName()).Where("id =  ? ", bigContract.ID).Update("isToSap", 1).Error; err != nil {
+//			log.Errorf("AutoContractToASP SQLUpdate Error:%v", err)
+//		}
+//
+//		if _, ok := ContractCodeMap[contractCode]; ok {
+//			contractInfoList := make([]*ContractInfo, 0)
+//			for _, pastureBigContract := range ContractCodeMap[contractCode] {
+//				// 获取合同相关数据集合
+//				contractInfo := GetContractInfo(bigContract, pastureBigContract)
+//				if len(contractInfo.Contract) == 0 || pastureBigContract.PastureId == 18 {
+//					continue
+//				}
+//
+//				// 发送数据至SAP
+//				errData, bigContracts, contracts := PushContractDataToSAP(bigContract, contractInfo, contractCode, false)
+//				for _, data := range errData {
+//					errDataList[contractCode] = append(errDataList[contractCode], data...)
+//				}
+//				contractInfoList = append(contractInfoList, contractInfo)
+//				errBigContract = append(errBigContract, bigContracts...)
+//				errContract = append(errContract, contracts...)
+//			}
+//
+//			var idList []int
+//			for _, contractInfo := range contractInfoList {
+//				for _, c := range contractInfo.Contract {
+//					if c.IsToSap == 0 {
+//						exist := false
+//						for _, id := range idList {
+//							if id == c.ID {
+//								exist = true
+//								break
+//							}
+//						}
+//						if !exist {
+//							idList = append(idList, c.ID)
+//							if err := s.d.DB.Table("contract").Where("id = ?", c.ID).Update("isToSap", 1).Error; err != nil {
+//								log.Errorf("AutoContractToASP SQLUpdate Error:%v", err)
+//							}
+//						}
+//					}
+//				}
+//			}
+//
+//		}
+//	}
+//	now := time.Now()
+//	for _, contractSapErr := range errDataList {
+//		for _, c := range contractSapErr {
+//			c.CreateTime = now
+//			s.d.DB.Create(&c)
+//		}
+//	}
+//
+//	for _, item := range errBigContract {
+//		if err := s.d.DB.Debug().Table(new(model.BigContract).TableName()).Where("id =  ? ", item.ID).Update("isToSap", 0).Error; err != nil {
+//			log.Errorf("AutoContractToASP SQLUpdate Error:%v", err)
+//		}
+//	}
+//	for _, c := range errContract {
+//		if err := s.d.DB.Table("contract").Where("id = ?", c.ID).Update("isToSap", 0).Error; err != nil {
+//			log.Errorf("AutoContractToASP SQLUpdate Error:%v", err)
+//		}
+//	}
+//
+//	log.Info("AutoContractToASP Success")
+//}
+//
+//// PushContractDataToSAP 同步数据给SAP
+//func PushContractDataToSAP(bigContract *model.BigContract, contractInfo *ContractInfo, contractCode string, hand bool) (map[string][]*model.ContractSapErr, []*model.BigContract, []*model.Contract) {
+//	errMap := make(map[string][]*model.ContractSapErr, 0)
+//	errBigContract := make([]*model.BigContract, 0)
+//	errContract := make([]*model.Contract, 0)
+//
+//	for _, contract := range contractInfo.Contract {
+//		if !hand {
+//			if contract.IsToSap == 1 {
+//				continue
+//			}
+//		}
+//		LOEKZ := ""
+//		if contract.Enable == 0 {
+//			LOEKZ = "X"
+//		}
+//
+//		startTime, _ := time.ParseInLocation(time.RFC3339, bigContract.StartTime, loc)
+//		stopTime, _ := time.ParseInLocation(time.RFC3339, bigContract.StopTime, loc)
+//
+//		astr := strconv.FormatFloat(contract.Price, 'f', -1, 64)
+//		b := strings.Index(astr, ".")
+//		per := ""
+//		if len(astr[b+1:]) > 2 && b > 0 {
+//			num, _ := strconv.ParseFloat(astr[b+1:], 64)
+//			if num > 0 {
+//				contract.Price = contract.Price * 1000
+//				per = "1000"
+//			}
+//		}
+//
+//		var isZeroStock int
+//		if bigContract.IsZeroStock == 1 {
+//			isZeroStock = 2
+//		} else {
+//			isZeroStock = 0
+//		}
+//		//LOEKZ = "X"
+//		contractDataToASP := &http.ContractDataToASP{
+//			MATNR: contract.PartCode,
+//			LIFNR: contractInfo.Provider.SapCode,
+//			EKORG: contractInfo.Pasture.ParchaseOrganization,
+//			WERKS: contractInfo.Pasture.FactoryCode,
+//			WAERS: "CNY",
+//			PEINH: per,
+//			NETPR: fmt.Sprintf("%.2f", contract.Price),
+//			MWSKZ: "J0",
+//			EKGRP: contractInfo.Pasture.PurchasingGroup,
+//			DATAB: startTime.Format("20060102"),
+//			DATBI: stopTime.Format("20060102"),
+//			LOEKZ: LOEKZ,
+//			ESOKZ: fmt.Sprintf("%d", isZeroStock),
+//			MEINS: contract.Unit,
+//			Code:  bigContract.ContractCode,
+//		}
+//		sapContractReq.DATA = contractDataToASP
+//
+//		rp := &http.SapContractResp{}
+//
+//		rbyte, _ := json.Marshal(sapContractReq)
+//		fmt.Println(string(rbyte))
+//		if err := s.SyncSap(sapContractReq, rp, sapContractReq); err != nil {
+//			log.Errorf("AutoContractToASP SyncSap Err:%v contract:%v", err, contract)
+//			//continue
+//		}
+//		log.Info(rp)
+//
+//		if rp.Dest.Status != "S" {
+//			log.Errorf("AutoContractToASP SyncSap Error:%v,contract:%v", rp, contract)
+//			contract.PastureID = contractInfo.Pasture.ID
+//			errMap[contractCode] = append(errMap[contractCode], &model.ContractSapErr{
+//				ContractID:    contract.ID,
+//				PastureID:     contractInfo.Pasture.ID,
+//				PastureName:   contractInfo.Pasture.Name,
+//				PartID:        contract.PartID,
+//				PartName:      contract.PartName,
+//				PartCode:      contract.PartCode,
+//				Specification: contract.Specification,
+//				Price:         contract.Price,
+//				BrandID:       contract.BrandID,
+//				Brand:         contract.Brand,
+//				InventoryType: contract.InventoryType,
+//				PlanAmount:    contract.PlanAmount,
+//				Remark:        contract.Remark,
+//				Enable:        contract.Enable,
+//				Unit:          contract.Unit,
+//				IsZeroStock:   contract.IsZeroStock,
+//				ChangeID:      contract.ChangeID,
+//				SapText:       rp.MessText,
+//				ContractCode:  contractCode,
+//			})
+//		}
+//		if rp.Dest.Status == "" {
+//			errContract = append(errContract, contract)
+//		}
+//	}
+//
+//	if len(errContract) > 0 {
+//		errBigContract = append(errBigContract, bigContract)
+//	}
+//	return errMap, errBigContract, errContract
+//}
+//
+//func RemoveRepeatedElement1(arr []string) (newArr []string) {
+//	newArr = make([]string, 0)
+//	for i := 0; i < len(arr); i++ {
+//		repeat := false
+//		for j := i + 1; j < len(arr); j++ {
+//			if arr[i] == arr[j] {
+//				repeat = true
+//				break
+//			}
+//		}
+//		if !repeat {
+//			newArr = append(newArr, arr[i])
+//		}
+//	}
+//	return
+//}
+//
+//func (s *Service) PostPushContractDataToSAP(pastureId, providerId int64, contractIdList []int64) error {
+//	sapContractReq.Url = config.Conf.Http.Routing + "/SRM/MM018/PurchaseInfo"
+//	contractList := make([]*model.Contract, 0)
+//	err := s.d.DB.Debug().Where(" id in (?) ", contractIdList).Find(&contractList).Error
+//	if err != nil {
+//		logs.Error(err)
+//		return err
+//	}
+//
+//	pasture := new(model.Pasture)
+//	err = s.d.DB.Where("id = ? ", pastureId).First(&pasture).Error
+//	if err != nil {
+//		logs.Error(err)
+//		return err
+//	}
+//
+//	provider := new(model.Provider)
+//	err = s.d.DB.Where("id = ? ", providerId).First(&provider).Error
+//	if err != nil {
+//		logs.Error(err)
+//		return err
+//	}
+//
+//	contractMap := make(map[int][]*model.Contract, 0)
+//	for _, contract := range contractList {
+//		contractMap[contract.BigID] = append(contractMap[contract.BigID], contract)
+//	}
+//
+//	pastureBigcontractList := make([]*model.PastureBigcontract, 0)
+//	for bigId, m := range contractMap {
+//		bigContract := new(model.BigContract)
+//		err := s.d.DB.Where(" id = ?  ", bigId).First(&bigContract).Error
+//		if err != nil {
+//			logs.Error(err)
+//			return err
+//		}
+//
+//		if len(pastureBigcontractList) == 0 {
+//			contractCode := strings.Split(bigContract.ContractCode, "-")[0]
+//			pastureBigcontractList, _ = GetPastureBigContract(contractCode)
+//		}
+//		exist := false
+//		for _, item := range pastureBigcontractList {
+//			if item.PastureId == int(pastureId) {
+//				exist = true
+//				break
+//			}
+//		}
+//		if !exist {
+//			return errors.New("牧场没有该合同!")
+//		}
+//
+//		contractInfo := new(ContractInfo)
+//		contractInfo.Contract = m
+//		contractInfo.Provider = provider
+//		contractInfo.Pasture = pasture
+//		fmt.Println(contractInfo)
+//		PushContractDataToSAP(bigContract, contractInfo, bigContract.ContractCode, true)
+//	}
+//
+//	return nil
+//}

+ 145 - 100
apiserver/service/diesel.go

@@ -44,7 +44,7 @@ func (s *Service) InsertDieselData(req *http.DieselReq) error {
 		resp := tx.Create(diesel)
 
 		if resp.Error != nil {
-			logs.Error(resp.Error)
+			logs.Error("DieseUseProof0: ", resp.Error)
 			return resp.Error
 		}
 		req.Id = diesel.Id
@@ -57,7 +57,7 @@ func (s *Service) InsertDieselData(req *http.DieselReq) error {
 		dieselList = append(dieselList, diesel)
 		err = s.DieseUseProof(dieselList, tx, strconv.FormatInt(req.PastureId, 10), code.OrderCode, req.SelTime)
 		if err != nil {
-			//logs.Error(err)
+			logs.Error("DieseUseProof2: ", err)
 			return err
 		}
 		return nil
@@ -106,10 +106,27 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 	}
 	dieselList := make([]*model.Diesel, 0)
 	errBool := false
-	//var selTime string
+	var selTime string
 	code := new(model.CreateCodeN)
-	s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(code)
+	s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(&code)
+
+	if code.OrderCode == "" {
+		s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(&code)
+		if code.OrderCode == "" {
+			outentry := make(map[string]interface{})
+			outentry["error_msg"] = "上传失败,请重新导入"
+			error++
+			queryData = append(queryData, outentry)
+
+			data := make(map[string]interface{})
+			data["result"] = queryData
+			//data["success"] = ok
+			data["err_count"] = 1
+			return data, nil
+		}
+	}
 	tx := s.d.DB.Begin()
+	var dateList []string
 	for i, row := range rows {
 		if i > 0 {
 			if len(paramslist) > 0 {
@@ -190,8 +207,22 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 					continue
 				}
 
-				now, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
+				if len(dateList) == 0 {
+					dateList = append(dateList, jyTime.Format("2006-01-02"))
+				} else {
+					exist := false
+					for _, date := range dateList {
+						if date == jyTime.Format("2006-01-02") {
+							exist = true
+							break
+						}
+					}
+					if !exist {
+						dateList = append(dateList, jyTime.Format("2006-01-02"))
+					}
+				}
 
+				now, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
 				if jyTime.Unix() > now.Unix() {
 					outentry["error_msg"] = "本次抄表日期不可大于当前日期"
 					error++
@@ -225,9 +256,11 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 
 				if oilcard.CardType != "外部" {
 					equipment := new(model.Equipment)
-					tx.Where("eqCode = ? and pastureId =?  ", entry["设备编号"], pasture.ID).First(equipment)
+					tx.Debug().Where("eqCode = ? and pastureId =?  ", entry["设备编号"], pasture.ID).First(equipment)
 					diesel.EqCode = equipment.EqCode
 					diesel.EqId = int64(equipment.Id)
+					deptId, _ := strconv.ParseInt(equipment.DepartmentId, 10, 64)
+					diesel.DeptId = deptId
 					if equipment.EqCode == "" {
 						outentry["error_msg"] = entry["设备编号"] + "资产不存在或不在本牧场"
 						error++
@@ -258,8 +291,11 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 				if _, ok := entry["加油工班"]; ok {
 					diesel.OilClass = entry["加油工班"]
 				}
-				deptId, _ := strconv.ParseInt(oilcard.DepartmentId, 10, 64)
-				diesel.DeptId = deptId
+
+				if diesel.DeptId == 0 {
+					deptId, _ := strconv.ParseInt(oilcard.DepartmentId, 10, 64)
+					diesel.DeptId = deptId
+				}
 				oilcardId, _ := strconv.ParseInt(oilcard.Id, 10, 64)
 				diesel.OilcardId = oilcardId
 
@@ -315,6 +351,7 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 					error++
 					queryData = append(queryData, outentry)
 					//tx.Rollback()
+					logs.Error("DieseUseProof0: ", err)
 					errBool = true
 					continue
 				}
@@ -333,13 +370,28 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 					errBool = true
 					continue
 				}
-				//selTime = diesel.SelTime
+				selTime = diesel.SelTime
 				dieselList = append(dieselList, diesel)
 				ok++
 			}
 		}
 	}
 
+	if len(dateList) > 1 {
+		tx.Rollback()
+		data := make(map[string]interface{})
+		outentry := make(map[string]interface{})
+		outentry["error_msg"] = "请勿上传多个日期数据!"
+		error++
+		queryData = append(queryData, outentry)
+
+		data["result"] = queryData
+		data["result"] = queryData
+		//data["success"] = ok
+		data["err_count"] = 1
+		return data, nil
+	}
+
 	if errBool {
 		tx.Rollback()
 		data := make(map[string]interface{})
@@ -349,23 +401,35 @@ func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
 		return data, nil
 	}
 
-	//err = s.DieseUseProof(dieselList, tx, pastureId, code.OrderCode, selTime)
-	//if err != nil {
-	//	outentry := make(map[string]interface{})
-	//	outentry["error_msg"] = err.Error()
-	//	error++
-	//	queryData = append(queryData, outentry)
-	//
-	//	data := make(map[string]interface{})
-	//	data["result"] = queryData
-	//	//data["success"] = ok
-	//	data["err_count"] = 1
-	//	tx.Rollback()
-	//	return data, nil
-	//}
+	err = s.DieseUseProof(dieselList, tx, pastureId, code.OrderCode, selTime)
+	if err != nil {
+		outentry := make(map[string]interface{})
+		outentry["error_msg"] = err.Error()
+		error++
+		queryData = append(queryData, outentry)
 
-	tx.Commit()
+		data := make(map[string]interface{})
+		data["result"] = queryData
+		//data["success"] = ok
+		data["err_count"] = 1
+		tx.Rollback()
+		return data, nil
+	}
 
+	err = tx.Commit().Error
+	if err != nil {
+		outentry := make(map[string]interface{})
+		outentry["error_msg"] = "上传失败"
+		error++
+		queryData = append(queryData, outentry)
+
+		data := make(map[string]interface{})
+		data["result"] = queryData
+		//data["success"] = ok
+		data["err_count"] = 1
+		tx.Rollback()
+		return data, nil
+	}
 	data := make(map[string]interface{})
 	data["result"] = queryData
 	data["success"] = len(dieselList)
@@ -438,8 +502,6 @@ func (s *Service) DieseUseProof(reqList []*model.Diesel, tx *gorm.DB, pastureId,
 	//}
 	for i, req := range reqList {
 		eq := new(model.Equipment)
-		//storage := new(model.PartRepertory)
-
 		dp := new(model.Department)
 		if e := tx.Where("id = ? ", req.DeptId).First(dp).Error; e != nil {
 			log.Error(e)
@@ -455,39 +517,19 @@ func (s *Service) DieseUseProof(reqList []*model.Diesel, tx *gorm.DB, pastureId,
 		}
 
 		sdetail.EXT01 = "6601011703"
-		// 报废出库
-
-		// 领用出库、手动出库
-		//if pr.UseType == 0 || pr.UseType == 1 {
 		sdetail.MoveType = "201"
 		sdetail.CostCenter = dp.CostCenterCode
-		//if dp.Factory == "" {
 		sdetail.Factory = pa.FactoryCode
-		//} else {
-		//	sdetail.Factory = dp.Factory
-		//}
-
 		if sdetail.Factory == "M005" && strings.Contains(dp.Name, "二期") {
 			sdetail.Factory = "M017"
 		}
 
 		sdetail.RowNumber = fmt.Sprintf("%d", i+1)
 		sdetail.Quantity = fmt.Sprintf("%s", req.OilAmount)
-		//sdetail.Unit = v.Unit.(string)
 		sdetail.Code = diesePartMap[req.OilName]
 		sdetail.Location = "1005"
-		//if contractID > 0 && bc.IsZeroStock == 1 {
-		//	sdetail.SaveType = "K"
-		//}
-		//
-		//if sdetail.SaveType == "K" {
-		//	sdetail.Provider = pv.SapCode
-		//}
 		r.Data.Detail = append(r.Data.Detail, sdetail)
 		tx.Exec(`  update diesel set  sort = ?  where id = ?  `, sdetail.RowNumber, req.Id)
-		//if e := s.d.DB.Model(&model.PartUse{}).Where("id=?", v.ID).Update("rowNumber", sdetail.RowNumber).Error; e != nil {
-		//	log.Errorln(e, v.ID)
-		//}
 	}
 
 	//_, err = tx.Exec(` update partuse set rowNumber = ?  where id = ? `, sdetail.RowNumber, v.ID)
@@ -511,7 +553,10 @@ func (s *Service) DieseUseProof(reqList []*model.Diesel, tx *gorm.DB, pastureId,
 			//if e := s.d.DB.Model(&model.BigPartUse{}).Where("useform = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
 			//	log.Errorln(e)
 			//}
-			tx.Exec(`  update diesel set  ProofCode = ?  where dieselCode = ?  `, rp.Data.SapNumber, dieselCode)
+			err := tx.Exec(`  update diesel set  ProofCode = ?  where dieselCode = ?  `, rp.Data.SapNumber, dieselCode).Error
+			if err != nil {
+				log.Printf("%s", err.Error())
+			}
 		} else {
 			log.Warnf(" use proof :%s", rp.Dest.MessText)
 			return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
@@ -520,62 +565,62 @@ func (s *Service) DieseUseProof(reqList []*model.Diesel, tx *gorm.DB, pastureId,
 	return nil
 }
 
-func (s *Service) zdDieselData(pastureId int, date string) error {
-	code := new(model.CreateCodeN)
-	s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(code)
+func (s *Service) zdDieselData(pastureId, date, code string) error {
+	//code := new(model.CreateCodeN)
+	//s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(code)
 	return s.d.DB.Transaction(func(tx *gorm.DB) error {
-		deselOffList := make([]*model.DieselOff, 0)
-		err := tx.Where("pastureId = ?", pastureId).Where(" selTime  like concat('%',?,'%') ", date).Find(&deselOffList).Error
-		fmt.Println(err)
-		if err != nil {
-			//logs.Error(err)
-			return err
-		}
-		if len(deselOffList) == 0 {
-			return nil
-		}
-		dieselList := make([]*model.Diesel, 0)
-		for _, item := range deselOffList {
-			//fmt.Println(item)
-			var targetTime = ""
-			t, err := time.Parse(time.RFC3339, item.SelTime)
-			if err != nil {
-				fmt.Println("解析错误:", err)
-				targetTime = item.SelTime
-			} else {
-				targetTime = t.Format("2006-01-02 15:04:05")
-			}
-
-			// 转换为指定格式的时间字符串
-			fmt.Println(targetTime)
-			diesel := &model.Diesel{
-				Id:         item.Id,
-				PastureId:  item.PastureId,
-				DeptId:     item.DeptId,
-				EqId:       item.EqId,
-				EqCode:     item.EqCode,
-				OilcardId:  item.OilcardId,
-				CardNumber: item.CardNumber,
-				OilClass:   item.OilClass,
-				OilAmount:  item.OilAmount,
-				NowPrice:   item.NowPrice,
-				Price:      item.Price,
-				EmpId:      item.EmpId,
-				InputId:    item.InputId,
-				SelTime:    targetTime,
-				Note:       item.Note,
-				OilName:    item.OilName,
-				OilType:    item.OilType,
-				DieselCode: code.OrderCode,
-			}
-			tx.Create(diesel)
-			dieselList = append(dieselList, diesel)
-			tx.Exec(`delete from diesel_off where id = ?`, item.Id)
-		}
+		deselOffList := make([]*model.Diesel, 0)
+		tx.Debug().Where("pastureId = ?", pastureId).Where("selTime = ?", date).Where(" dieselCode  = ? ", code).Find(&deselOffList)
+		//fmt.Println(err)
+		//if err != nil {
+		//	//logs.Error(err)
+		//	return err
+		//}
+		//if len(deselOffList) == 0 {
+		//	return nil
+		//}
+		//dieselList := make([]*model.Diesel, 0)
+		//for _, item := range deselOffList {
+		//fmt.Println(item)
+		//var targetTime = ""
+		//t, err := time.Parse("2006-01-02 15:04:05", item.SelTime)
+		//if err != nil {
+		//	fmt.Println("解析错误:", err)
+		//	targetTime = item.SelTime
+		//} else {
+		//	targetTime = t.Format("2006-01-02 15:04:05")
+		//}
+		//
+		//// 转换为指定格式的时间字符串
+		//fmt.Println(targetTime)
+		//diesel := &model.Diesel{
+		//	Id:         item.Id,
+		//	PastureId:  item.PastureId,
+		//	DeptId:     item.DeptId,
+		//	EqId:       item.EqId,
+		//	EqCode:     item.EqCode,
+		//	OilcardId:  item.OilcardId,
+		//	CardNumber: item.CardNumber,
+		//	OilClass:   item.OilClass,
+		//	OilAmount:  item.OilAmount,
+		//	NowPrice:   item.NowPrice,
+		//	Price:      item.Price,
+		//	EmpId:      item.EmpId,
+		//	InputId:    item.InputId,
+		//	SelTime:    targetTime,
+		//	Note:       item.Note,
+		//	OilName:    item.OilName,
+		//	OilType:    item.OilType,
+		//	DieselCode: item.DieselCode,
+		//}
+		//tx.Create(diesel)
+		//dieselList = append(dieselList, diesel)
+		//tx.Exec(`delete from diesel_off where id = ?`, item.Id)
+		//}
 
-		err = s.DieseUseProof(dieselList, tx, strconv.Itoa(pastureId), code.OrderCode, date)
+		err := s.DieseUseProof(deselOffList, tx, pastureId, code, date)
 		if err != nil {
-			//logs.Error(err)
+			logs.Error(err)
 			return err
 		}
 		return nil

+ 546 - 0
apiserver/service/equipment.go

@@ -1,2 +1,548 @@
 package service
 
+import (
+	"fmt"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/home"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/util"
+	"time"
+)
+
+func (s *Service) GetEquipmentIndex(pastureId, startTime, endTime string) (*http.EquipmentIndexResp, error) {
+	resp := new(http.EquipmentIndexResp)
+
+	startDate, _ := time.Parse("2006-01-02", startTime)
+	endDate, _ := time.Parse("2006-01-02", endTime)
+
+	monthBudgetList := make([]*home.MonthBudget, 0)
+	err := s.d.DB.Debug().Raw(`SELECT
+		sum( monthBudget ) monthBudget,
+	feeType,pastureId
+FROM
+	month_budget  join  pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth BETWEEN date_format(?,'%Y-%m') and date_format(?,'%Y-%m')   and (pastureId = ? or ? ='')  and vendor = 1  and feeType != '维修费'
+GROUP BY
+	feeType,pastureId 
+UNION ALL
+SELECT
+		sum( monthBudget ) monthBudget,
+	feeType,pastureId
+FROM
+	month_budget  join  pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth BETWEEN date_format(?,'%Y-%m') and date_format(?,'%Y-%m')   and (pastureId = ? or ? ='')  and vendor = 1  and feeType = '维修费'
+  and (SELECT iscal FROM department d WHERE d.id=month_budget.deptId)= 0   and (SELECT name FROM department d WHERE d.id=month_budget.deptId) not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+GROUP BY
+	feeType,pastureId `, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId,
+		startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId).Find(&monthBudgetList).Error
+	if err != nil {
+		return resp, err
+	}
+	//
+	feedSumList := make([]*model.FeedSumAndPasture, 0)
+	err = s.d.DB.Debug().Raw(`SELECT sum(fs.cowNum) cowNum ,fs.pastureId,p.name FROM  feed_sum fs INNER JOIN pasture p ON p.id = fs.pastureId  
+                      where feedDay between ?  and ?  and  (fs.pastureId = ?  or ? ='') group by fs.pastureId`, startDate.Format("2006-01-02"),
+		endDate.Format("2006-01-02"), pastureId, pastureId).Find(&feedSumList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	feetSumPriceList := make([]*home.ThisYearActual, 0)
+	err = s.d.DB.Debug().Raw(`select FYLX feeType,sum(HSL) sumPrice,pastureId from feequery  where 	DATE_FORMAT(STR_TO_DATE( Date, '%Y-%m' ),'%Y-%m') 
+    between ? and ?   and FYLX in ('水费','燃动费','电费','柴油费')  and (pastureId = ? or ? = '')  group by FYLX,pastureId
+
+UNION ALL
+SELECT
+  '维修费' feeType ,IFNULL(SUM( pu.sumPrice - pu.quitNumber * pu.price),0) sumPrice,bpu.pastureId
+FROM
+  partuse pu
+  INNER JOIN bigpartuse bpu
+    ON pu.bigId = bpu.id	 
+WHERE  bpu.useType <> 3  
+  AND (
+    pu.useTypeV = '维修'
+    OR pu.useTypeV = '保养'
+  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 and   (SELECT name FROM department d WHERE d.id=bpu.departmentId) 
+                                                                                  not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+  AND  bpu.receiveTime BETWEEN ? AND ?
+  AND (bpu.pastureid = ?  OR '' = ?) and  pu.dflag != 1  group by pastureId`, startDate.Format("2006-01"),
+		endDate.Format("2006-01"), pastureId, pastureId, startDate.Format("2006-01-02"),
+		endDate.AddDate(0, 0, 1).Format("2006-01-02"), pastureId, pastureId).Find(&feetSumPriceList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	var sumDay, realDay int64
+	sumDay = int64(endDate.Sub(startDate).Hours() / 24)
+	if endDate.Unix() < time.Now().Unix() {
+		realDay = sumDay
+	} else {
+		realDay = int64(time.Now().Sub(startDate).Hours() / 24)
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Debug().Where(" id != 18 ").Where(" id = ? or ? = '' ", pastureId, pastureId).Where("vendor = 1").Order("center_sort,id").Find(&pastureList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	pastureLs := new(model.Pasture)
+	equipmentList := make([]*http.EquipmentIndex, 0)
+	chooseMonthWXList := make([]*http.EquipmentIndex, 0)
+	chooseWaterPriceList := make([]*http.EquipmentIndex, 0)
+	chooseElectricityPriceList := make([]*http.EquipmentIndex, 0)
+	chooseMonthiolPriceList := make([]*http.EquipmentIndex, 0)
+	lgnitionChargePriceList := make([]*http.EquipmentIndex, 0)
+	dosageIndexList := make([]map[string]interface{}, 0)
+
+	pastureCount := len(pastureList) - 1
+	for i, pasture := range pastureList {
+		if i == 0 {
+			pastureLs = pasture
+		}
+
+		if pastureLs.Center != pasture.Center {
+			equipmentList = append(equipmentList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			chooseMonthWXList = append(chooseMonthWXList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			chooseWaterPriceList = append(chooseWaterPriceList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			chooseElectricityPriceList = append(chooseElectricityPriceList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			chooseMonthiolPriceList = append(chooseMonthiolPriceList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			lgnitionChargePriceList = append(lgnitionChargePriceList, &http.EquipmentIndex{PastureName: pastureList[i-1].Center, Center: pastureList[i-1].Center})
+			//center := make(map[string]interface{})
+			//center["pastureName"] = pastureList[i-1].Center
+			//center["center"] = pastureList[i-1].Center
+			//dosageIndexList = append(dosageIndexList, center)
+		}
+
+		data := make(map[string]interface{})
+		data["pastureName"] = pasture.Name
+		data["center"] = pasture.Center
+		data["pastureId"] = pasture.ID
+		dosageIndexList = append(dosageIndexList, data)
+
+		equipmentList = append(equipmentList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		chooseMonthWXList = append(chooseMonthWXList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		chooseWaterPriceList = append(chooseWaterPriceList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		chooseElectricityPriceList = append(chooseElectricityPriceList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		chooseMonthiolPriceList = append(chooseMonthiolPriceList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		lgnitionChargePriceList = append(lgnitionChargePriceList, &http.EquipmentIndex{PastureName: pasture.Name, PastureId: pasture.ID, Center: pasture.Center})
+		if i == pastureCount {
+			equipmentList = append(equipmentList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			chooseWaterPriceList = append(chooseWaterPriceList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			chooseWaterPriceList = append(chooseWaterPriceList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			chooseElectricityPriceList = append(chooseElectricityPriceList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			chooseMonthiolPriceList = append(chooseMonthiolPriceList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			lgnitionChargePriceList = append(lgnitionChargePriceList, &http.EquipmentIndex{PastureName: pasture.Center, Center: pasture.Center})
+			//center := make(map[string]interface{})
+			//center["pastureName"] = pasture.Center
+			//center["center"] = pasture.Center
+			//dosageIndexList = append(dosageIndexList, center)
+		}
+		pastureLs = pasture
+	}
+
+	equipmentJT := new(http.EquipmentIndex)
+	equipmentJT.PastureName = "集团"
+	for _, eq := range equipmentList {
+		for _, monthBudget := range monthBudgetList {
+			if eq.PastureId == monthBudget.PastureId && (monthBudget.FeeType == "燃动费" || monthBudget.FeeType == "水费" || monthBudget.FeeType == "电费" || monthBudget.FeeType == "维修费") {
+				eq.MonthBudget += monthBudget.MonthBudget
+				eq.QmonthBudget += monthBudget.MonthBudget / float64(sumDay) * float64(realDay)
+			}
+		}
+		for _, feedSum := range feedSumList {
+			if eq.PastureId == int(feedSum.PastureId) {
+				eq.CowSum += feedSum.CowNum
+				break
+			}
+		}
+		for _, feedSum := range feetSumPriceList {
+			if eq.PastureId == feedSum.PastureId && (feedSum.FeeType == "燃动费" || feedSum.FeeType == "水费" || feedSum.FeeType == "电费" || feedSum.FeeType == "维修费") {
+				eq.SumPrice += feedSum.SumPrice
+			}
+		}
+		eq.Asave = eq.MonthBudget - eq.SumPrice
+		if eq.MonthBudget > 0 && eq.SumPrice > 0 {
+			eq.RealReason = fmt.Sprintf("%v", util.Round((1+((eq.MonthBudget/float64(sumDay)*float64(realDay))-(eq.SumPrice))/(eq.MonthBudget/float64(sumDay)*float64(realDay)))*100, 2)) + " %"
+		} else {
+			eq.RealReason = "0 %"
+		}
+		if eq.MonthBudget > 0 && eq.SumPrice > 0 && eq.CowSum > 0 {
+			eq.OneCowSumPrice = util.Round(eq.SumPrice/float64(eq.CowSum/sumDay*realDay), 2)
+		} else {
+			eq.OneCowSumPrice = 0.0
+		}
+		equipmentJT.MonthBudget += eq.MonthBudget
+		equipmentJT.SumPrice += eq.SumPrice
+		equipmentJT.QmonthBudget += eq.QmonthBudget
+		equipmentJT.Asave += eq.Asave
+		equipmentJT.CowSum += eq.CowSum
+	}
+
+	for _, eq := range equipmentList {
+		if eq.PastureId == 0 {
+			for _, item := range equipmentList {
+				if item.Center == eq.PastureName && eq.PastureName != item.PastureName {
+					eq.MonthBudget += item.MonthBudget
+					eq.SumPrice += item.SumPrice
+					eq.QmonthBudget += item.QmonthBudget
+					eq.Asave += item.Asave
+					eq.CowSum += item.CowSum
+				}
+			}
+		}
+	}
+
+	equipmentList = append(equipmentList, equipmentJT)
+	for _, eq := range equipmentList {
+		if eq.PastureId == 0 {
+			if eq.MonthBudget > 0 && eq.SumPrice > 0 {
+				eq.RealReason = fmt.Sprintf("%v", util.Round((1+((eq.MonthBudget/float64(sumDay)*float64(realDay))-(eq.SumPrice))/(eq.MonthBudget/float64(sumDay)*float64(realDay)))*100, 2)) + " %"
+			} else {
+				eq.RealReason = "0 %"
+			}
+			if eq.MonthBudget > 0 && eq.SumPrice > 0 && eq.CowSum > 0 {
+				eq.OneCowSumPrice = util.Round(eq.SumPrice/float64(eq.CowSum/sumDay*realDay), 2)
+			} else {
+				eq.OneCowSumPrice = 0
+			}
+		}
+
+		eq.MonthBudget = util.Round(eq.MonthBudget/10000, 2)
+		eq.SumPrice = util.Round(eq.SumPrice/10000, 2)
+		eq.QmonthBudget = util.Round(eq.QmonthBudget/10000, 2)
+		eq.Asave = util.Round(eq.Asave/10000, 2)
+	}
+
+	resp.EquipmentIndex = equipmentList
+	resp.ChooseMonthWX = chooseMonth("维修费", chooseMonthWXList, feedSumList, monthBudgetList, feetSumPriceList, sumDay, realDay)
+	resp.ChooseWaterPrice = chooseMonth("水费", chooseWaterPriceList, feedSumList, monthBudgetList, feetSumPriceList, sumDay, realDay)
+	resp.ChooseElectricityPrice = chooseMonth("电费", chooseElectricityPriceList, feedSumList, monthBudgetList, feetSumPriceList, sumDay, realDay)
+	resp.ChooseMonthiolPrice = chooseMonth("柴油费", chooseMonthiolPriceList, feedSumList, monthBudgetList, feetSumPriceList, sumDay, realDay)
+	resp.LgnitionChargePrice = chooseMonth("燃动费", lgnitionChargePriceList, feedSumList, monthBudgetList, feetSumPriceList, sumDay, realDay)
+
+	waterIndexList := make([]*http.DosageIndex, 0)
+	err = s.d.DB.Debug().Raw(`SELECT
+  m.pastureId,
+  ROUND(IFNULL(SUM(e.waterConsumption ),0),2) sumPrice,p.name pastureName
+FROM
+  water e
+  INNER JOIN measure m
+    ON m.id = e.measureId
+	join pasture p on m.pastureid = p.id
+WHERE  m.meterType = '水表' AND m.useType='1级表' AND e.date between ? and  ?
+and (p.id = ?  or ? = 0)
+group by m.pastureId 
+`, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId).Find(&waterIndexList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	electricityIndexList := make([]*http.DosageIndex, 0)
+	err = s.d.DB.Debug().Raw(`SELECT
+	m.pastureId,
+		ROUND(IFNULL(SUM(e.elecConsumption),0),2) sumPrice,
+		p.name pastureName
+	FROM
+	electricity e
+	INNER JOIN measure m
+	ON m.id = e.measureId
+	join pasture p on p.id = m.pastureid
+	WHERE  m.meterType = '电表' AND m.useType='1级表' AND e.date  between ? and  ? 
+	and (p.id = ? or ? = '')
+	GROUP BY  m.pastureId`, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId).Find(&electricityIndexList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	dieselIndexList := make([]*http.DosageIndex, 0)
+	err = s.d.DB.Debug().Raw(`SELECT
+	d.pastureId,
+		ROUND(IFNULL(SUM(d.oilAmount),0),2) sumPrice,
+		p.name pastureName
+	FROM
+	diesel d
+	join pasture p on p.id = d.pastureid
+	WHERE  d.selTime  between ? and    ? 
+	and (p.id = ? or ? = '')
+	GROUP BY  d.pastureId`, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId).Find(&dieselIndexList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	for _, dosage := range dosageIndexList {
+		dosageMap := dosage
+		var cowNum int64
+		for _, feedSum := range feedSumList {
+			if dosageMap["pastureName"].(string) == feedSum.Name {
+				cowNum = feedSum.CowNum
+				break
+			}
+		}
+		if _, ok := dosageMap["pastureId"]; !ok {
+			continue
+		}
+		for _, water := range waterIndexList {
+			if dosageMap["pastureName"].(string) == water.PastureName {
+				dosageMap["waterOneCowSumPrice"] = 0
+				dosageMap["waterSumPrice"] = 0
+				if water.SumPrice > 0 {
+					if cowNum > 0 {
+						dosageMap["waterOneCowSumPrice"] = util.Round(water.SumPrice/float64(cowNum), 2)
+					}
+					dosageMap["waterSumPrice"] = util.Round(water.SumPrice, 2)
+				}
+				break
+			}
+		}
+		for _, electricity := range electricityIndexList {
+			if dosageMap["pastureName"].(string) == electricity.PastureName {
+				dosageMap["electricityOneCowSumPrice"] = 0
+				dosageMap["electricitySumPrice"] = 0
+				if electricity.SumPrice > 0 {
+					if cowNum > 0 {
+						dosageMap["electricityOneCowSumPrice"] = util.Round(electricity.SumPrice/float64(cowNum), 2)
+					}
+					dosageMap["electricitySumPrice"] = util.Round(electricity.SumPrice, 2)
+				}
+				break
+			}
+		}
+		for _, diesel := range dieselIndexList {
+			if dosageMap["pastureName"].(string) == diesel.PastureName {
+				dosageMap["monthiolOneCowSumPrice"] = 0
+				dosageMap["monthiolSumPrice"] = 0
+				if diesel.SumPrice > 0 {
+					if cowNum > 0 {
+						dosageMap["monthiolOneCowSumPrice"] = util.Round(diesel.SumPrice/float64(cowNum), 2)
+					}
+					dosageMap["monthiolSumPrice"] = util.Round(diesel.SumPrice, 2)
+				}
+				break
+			}
+		}
+		dosageMap["cowNum"] = cowNum
+	}
+	for _, dosage := range dosageIndexList {
+		dosageMap := dosage
+		if _, ok := dosageMap["pastureId"]; !ok {
+			var waterSumPrice, electricitySumPrice, monthiolSumPrice float64
+			var cowNum int64
+			for _, dosage1 := range dosageIndexList {
+				dosage1Map := dosage1
+				if _, ok := dosage1Map["pastureId"]; ok {
+					if dosage1Map["center"].(string) == dosageMap["pastureName"].(string) {
+						if _, ok := dosage1Map["waterSumPrice"]; ok {
+							waterSumPrice += dosage1Map["waterSumPrice"].(float64)
+						}
+						if _, ok := dosage1Map["electricitySumPrice"]; ok {
+							electricitySumPrice += dosage1Map["electricitySumPrice"].(float64)
+						}
+						if _, ok := dosage1Map["monthiolSumPrice"]; ok {
+							monthiolSumPrice += dosage1Map["monthiolSumPrice"].(float64)
+						}
+						if _, ok := dosage1Map["cowNum"]; ok {
+							cowNum += dosage1Map["cowNum"].(int64)
+						}
+					}
+				}
+			}
+			if cowNum > 0 {
+				dosageMap["waterOneCowSumPrice"] = util.Round(waterSumPrice/float64(cowNum), 2)
+				dosageMap["electricityOneCowSumPrice"] = util.Round(waterSumPrice/float64(cowNum), 2)
+				dosageMap["monthiolOneCowSumPrice"] = util.Round(waterSumPrice/float64(cowNum), 2)
+			} else {
+				dosageMap["waterOneCowSumPrice"] = 0
+				dosageMap["electricityOneCowSumPrice"] = 0
+				dosageMap["monthiolOneCowSumPrice"] = 0
+			}
+
+			dosageMap["waterSumPrice"] = util.Round(waterSumPrice, 2)
+			dosageMap["electricitySumPrice"] = util.Round(waterSumPrice, 2)
+			dosageMap["monthiolSumPrice"] = util.Round(waterSumPrice, 2)
+		}
+	}
+
+	resp.DosageIndex = dosageIndexList
+	return resp, nil
+}
+
+func chooseMonth(feeType string, equipmentList []*http.EquipmentIndex, feedSumList []*model.FeedSumAndPasture, monthBudgetList []*home.MonthBudget, feetSumPriceList []*home.ThisYearActual, sumDay, realDay int64) []*http.EquipmentIndex {
+	chooseMonthJT := new(http.EquipmentIndex)
+	chooseMonthJT.PastureName = "集团"
+	for _, eq := range equipmentList {
+		for _, monthBudget := range monthBudgetList {
+			if eq.PastureId == monthBudget.PastureId && (monthBudget.FeeType == feeType) {
+				eq.MonthBudget += monthBudget.MonthBudget
+				eq.QmonthBudget += monthBudget.MonthBudget / float64(sumDay) * float64(realDay)
+			}
+		}
+		for _, feedSum := range feedSumList {
+			if eq.PastureId == int(feedSum.PastureId) {
+				eq.CowSum += feedSum.CowNum
+				break
+			}
+		}
+		for _, feedSum := range feetSumPriceList {
+			if eq.PastureId == feedSum.PastureId && feeType == feedSum.FeeType {
+				eq.SumPrice += feedSum.SumPrice
+			}
+		}
+		eq.Asave = eq.MonthBudget - eq.SumPrice
+		if eq.MonthBudget > 0 && eq.SumPrice > 0 {
+			eq.RealReason = fmt.Sprintf("%v", util.Round((1+((eq.MonthBudget/float64(sumDay)*float64(realDay))-(eq.SumPrice))/(eq.MonthBudget/float64(sumDay)*float64(realDay)))*100, 2)) + " %"
+		} else {
+			eq.RealReason = "0 %"
+		}
+		if eq.MonthBudget > 0 && eq.SumPrice > 0 && eq.CowSum > 0 {
+			eq.OneCowSumPrice = util.Round(eq.SumPrice/float64(eq.CowSum/sumDay*realDay), 2)
+		} else {
+			eq.OneCowSumPrice = 0.0
+		}
+		chooseMonthJT.MonthBudget += eq.MonthBudget
+		chooseMonthJT.SumPrice += eq.SumPrice
+		chooseMonthJT.QmonthBudget += eq.QmonthBudget
+		chooseMonthJT.Asave += eq.Asave
+		chooseMonthJT.CowSum += eq.CowSum
+	}
+
+	for _, eq := range equipmentList {
+		if eq.PastureId == 0 {
+			for _, item := range equipmentList {
+				if item.Center == eq.PastureName && eq.PastureName != item.PastureName {
+					eq.MonthBudget += item.MonthBudget
+					eq.SumPrice += item.SumPrice
+					eq.QmonthBudget += item.QmonthBudget
+					eq.Asave += item.Asave
+					eq.CowSum += item.CowSum
+				}
+			}
+		}
+	}
+
+	equipmentList = append(equipmentList, chooseMonthJT)
+	for _, eq := range equipmentList {
+		if eq.PastureId == 0 {
+			if eq.MonthBudget > 0 && eq.SumPrice > 0 {
+				eq.RealReason = fmt.Sprintf("%v", util.Round((1+((eq.MonthBudget/float64(sumDay)*float64(realDay))-(eq.SumPrice))/(eq.MonthBudget/float64(sumDay)*float64(realDay)))*100, 2)) + " %"
+			} else {
+				eq.RealReason = "0 %"
+			}
+			if eq.MonthBudget > 0 && eq.SumPrice > 0 && eq.CowSum > 0 {
+				eq.OneCowSumPrice = util.Round(eq.SumPrice/float64(eq.CowSum/sumDay*realDay), 2)
+			} else {
+				eq.OneCowSumPrice = 0
+			}
+		}
+
+		eq.MonthBudget = util.Round(eq.MonthBudget/10000, 2)
+		eq.SumPrice = util.Round(eq.SumPrice/10000, 2)
+		eq.QmonthBudget = util.Round(eq.QmonthBudget/10000, 2)
+		eq.Asave = util.Round(eq.Asave/10000, 2)
+	}
+
+	return equipmentList
+}
+
+func (s *Service) GetChooseMonthWXByDepartment(pastureId, startTime, endTime string) ([]*http.EquipmentIndex, error) {
+	startDate, _ := time.Parse("2006-01-02", startTime)
+	endDate, _ := time.Parse("2006-01-02", endTime)
+
+	departmentList := make([]*model.Department, 0)
+	resp := make([]*http.EquipmentIndex, 0)
+	err := s.d.DB.Where("pastureId = ? ", pastureId).Where("isPasture = 0 ").
+		Where(" name not in ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')").Find(&departmentList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	feetSumPriceList := make([]*home.ThisYearActual, 0)
+	err = s.d.DB.Debug().Raw(`
+SELECT
+'维修费' feeType ,IFNULL(SUM( pu.sumPrice - pu.quitNumber * pu.price),0) sumPrice,bpu.pastureId,departmentId
+FROM
+partuse pu
+INNER JOIN bigpartuse bpu
+  ON pu.bigId = bpu.id
+WHERE  bpu.useType <> 3
+AND (
+  pu.useTypeV = '维修'
+  OR pu.useTypeV = '保养'
+) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)
+                                                                                not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+AND  bpu.receiveTime BETWEEN ? AND ?
+AND (bpu.pastureid = ?  OR '' = ?) and  pu.dflag != 1  group by departmentId,pastureId`, startDate.Format("2006-01-02"),
+		endDate.AddDate(0, 0, 1).Format("2006-01-02"), pastureId, pastureId).Find(&feetSumPriceList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	monthBudgetList := make([]*home.MonthBudget, 0)
+	err = s.d.DB.Debug().Raw(`
+SELECT
+		sum( monthBudget ) monthBudget,
+	feeType,pastureId,month_budget.deptId
+FROM
+	month_budget  join  pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth BETWEEN date_format(?,'%Y-%m') and date_format(?,'%Y-%m')   and (pastureId = ? or ? ='')  and vendor = 1  and feeType = '维修费'
+  and (SELECT iscal FROM department d WHERE d.id=month_budget.deptId)= 0   and (SELECT name FROM department d WHERE d.id=month_budget.deptId) not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+GROUP BY
+	month_budget.deptId,feeType,pastureId `, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), pastureId, pastureId).Find(&monthBudgetList).Error
+	if err != nil {
+		return resp, err
+	}
+
+	feedSum := new(model.FeedSumAndPasture)
+	err = s.d.DB.Debug().Raw(`SELECT sum(fs.cowNum) cowNum ,fs.pastureId,p.name FROM  feed_sum fs INNER JOIN pasture p ON p.id = fs.pastureId  
+                      where feedDay between ?  and ?  and  (fs.pastureId = ?  or ? ='') group by fs.pastureId`, startDate.Format("2006-01-02"),
+		endDate.Format("2006-01-02"), pastureId, pastureId).First(&feedSum).Error
+	if err != nil {
+		return resp, err
+	}
+
+	var sumDay, realDay int64
+	sumDay = int64(endDate.Sub(startDate).Hours() / 24)
+	if endDate.Unix() < time.Now().Unix() {
+		realDay = sumDay
+	} else {
+		realDay = int64(time.Now().Sub(startDate).Hours() / 24)
+	}
+
+	for _, department := range departmentList {
+		data := new(http.EquipmentIndex)
+		data.DeptName = department.Name
+
+		for _, monthBudget := range monthBudgetList {
+			if department.ID == monthBudget.DeptId {
+				data.MonthBudget = monthBudget.MonthBudget
+				break
+			}
+		}
+
+		for _, feetSum := range feetSumPriceList {
+			if department.ID == feetSum.DepartmentId {
+				data.SumPrice = feetSum.SumPrice
+				break
+			}
+		}
+		data.QmonthBudget = data.MonthBudget / float64(sumDay) * float64(realDay)
+		data.Asave = data.MonthBudget - data.SumPrice
+		if data.MonthBudget > 0 && data.SumPrice > 0 {
+			data.RealReason = fmt.Sprintf("%v", util.Round((1+((data.MonthBudget/float64(sumDay)*float64(realDay))-(data.SumPrice))/(data.MonthBudget/float64(sumDay)*float64(realDay)))*100, 2)) + " %"
+		} else {
+			data.RealReason = "0 %"
+		}
+
+		data.CowSum = feedSum.CowNum
+		if data.MonthBudget > 0 && data.SumPrice > 0 && data.CowSum > 0 {
+			data.OneCowSumPrice = util.Round(data.SumPrice/float64(data.CowSum/sumDay*realDay), 2)
+		} else {
+			data.OneCowSumPrice = 0.0
+		}
+		resp = append(resp, data)
+	}
+	return resp, nil
+}

+ 8 - 7
apiserver/service/feequery.go

@@ -35,7 +35,7 @@ func AutoFeeQuery(werks string, pastureID int) {
 		fmt.Println(string(rbyte))
 		if e = s.SyncSap(r, rp, rbyte); e == nil {
 			if rp.Dest.Status == "S" {
-				log.Infof("sap  FeeQuery  success sum=%d", len(rp.Data.Items))
+				log.Infof("sap  FeeQuery  success sum=%d")
 			} else {
 				log.Infof("sap FeeQuery fail", rp.Dest.MessText)
 				pp.Print(r)
@@ -57,7 +57,7 @@ func AutoFeeQuery(werks string, pastureID int) {
 				Where("GJAHR = ? ", item.GJAHR).Where("POPER = ? ", poper).Count(&n)
 
 			var dateStr string
-			if poper > 10 {
+			if poper >= 10 {
 				dateStr = fmt.Sprintf("%s-%d", item.GJAHR, poper)
 			} else {
 				dateStr = fmt.Sprintf("%s-0%d", item.GJAHR, poper)
@@ -83,8 +83,9 @@ func AutoFeeQuery(werks string, pastureID int) {
 				}).Error
 				fmt.Println(err)
 			} else {
-				s.d.DB.Exec(` update feequery set HSL = ? where pastureId = ? and FYLX = ? and GJAHR = ? and POPER = ? `, item.HSL,
-					pastureID, item.FYLX, item.GJAHR, poper)
+				err = s.d.DB.Exec(` update feequery set HSL = ? where pastureId = ? and FYLX = ? and GJAHR = ? and POPER = ? `, item.HSL,
+					pastureID, item.FYLX, item.GJAHR, poper).Error
+				fmt.Println(err)
 			}
 		}
 	} else {
@@ -99,7 +100,7 @@ func AutoFeeQuery(werks string, pastureID int) {
 		fmt.Println(string(rbyte))
 		if e = s.SyncSap(r, rp, rbyte); e == nil {
 			if rp.Dest.Status == "S" {
-				log.Infof("sap  FeeQuery  success sum=%d", len(rp.Data.Items))
+				log.Infof("sap  FeeQuery  success sum=")
 			} else {
 				log.Infof("sap FeeQuery fail", rp.Dest.MessText)
 				pp.Print(r)
@@ -107,12 +108,12 @@ func AutoFeeQuery(werks string, pastureID int) {
 		} else {
 			log.Error(e)
 		}
-
 		sapItems := make([]*http.SapITEMS, 0)
 		for _, item := range rp.Data.Items {
 			if item.FYLX == "" {
 				continue
 			}
+
 			exist := false
 			for _, sapItem := range sapItems {
 				if sapItem.FYLX == item.FYLX && item.POPER == sapItem.POPER {
@@ -141,7 +142,7 @@ func AutoFeeQuery(werks string, pastureID int) {
 				Where("GJAHR = ? ", item.GJAHR).Where("POPER = ? ", poper).Count(&n)
 
 			var dateStr string
-			if poper > 10 {
+			if poper >= 10 {
 				dateStr = fmt.Sprintf("%s-%d", item.GJAHR, poper)
 			} else {
 				dateStr = fmt.Sprintf("%s-0%d", item.GJAHR, poper)

+ 161 - 73
apiserver/service/home.go

@@ -22,15 +22,33 @@ func (s *Service) OverallIndex() (*home.OverallIndexResp, error) {
 		)) monthBudget,
 	feeType 
 FROM
-	month_budget 
+	month_budget join pasture on pasture.id = month_budget.pastureId
 WHERE
-	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' ) 
+	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and vendor = 1  and feeType != '维修费'
 GROUP BY
-	feeType `).Find(&monthBudgetList).Error
+	feeType 
+UNION ALL
+	SELECT
+(
+		sum( monthBudget )*(
+			DATEDIFF(
+				NOW(),
+				CONCAT( YEAR ( NOW()), '-01-01' )) / DATEDIFF(
+				CONCAT( YEAR ( NOW()), '-12-31' ),
+			CONCAT( YEAR ( NOW()), '-01-01' )) 
+		)) monthBudget,
+	feeType 
+FROM
+	month_budget join pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and vendor = 1  and feeType = '维修费'
+and (SELECT iscal FROM department d WHERE d.id=month_budget.deptId)= 0 and  (SELECT name FROM department d WHERE d.id=month_budget.deptId)not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+GROUP BY
+	feeType`).Find(&monthBudgetList).Error
 	if err != nil {
 		return resp, err
 	}
-
+	//
 	thisYearActualList := make([]*home.ThisYearActual, 0)
 	err = s.d.DB.Raw(`select FYLX feeType,sum(HSL) sumPrice from feequery  where Date like  concat( '%',YEAR(NOW()),'%')   and FYLX in ('水费','燃动费','电费')  group by FYLX
 
@@ -46,14 +64,15 @@ WHERE  bpu.useType <> 3
   AND (
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
-  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
-  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and bpu.sterilisation = 0`).Find(&thisYearActualList).Error
+  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)  
+                                                                                   not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
+  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and  pu.dflag != 1`).Find(&thisYearActualList).Error
 	if err != nil {
 		return resp, err
 	}
 
 	lastYearActualList := make([]*home.ThisYearActual, 0)
-	err = s.d.DB.Raw(`select FYLX feeType,sum(HSL) sumPrice from feequery  where Date like  concat( '%',YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'%')  
+	err = s.d.DB.Raw(`select FYLX feeType,sum(HSL) sumPrice from feequery  where 	DATE_FORMAT(STR_TO_DATE( Date, '%Y-%m' ),'%Y-%m') between CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01') and DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 YEAR),'%Y-%m')
                                                      and FYLX in ('水费','燃动费','电费')  group by FYLX
 
 UNION ALL
@@ -68,14 +87,15 @@ WHERE  bpu.useType <> 3
   AND (
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
-  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
-  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and bpu.sterilisation = 0`).Find(&lastYearActualList).Error
+  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 and   (SELECT name FROM department d WHERE d.id=bpu.departmentId) 
+                                                                       not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处') AND  bpu.receiveTime BETWEEN CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01-01') AND DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
+  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and  pu.dflag != 1`).Find(&lastYearActualList).Error
 	if err != nil {
 		return resp, err
 	}
 
 	feedSum := new(model.FeedSum)
-	err = s.d.DB.Raw(` select sum(cowNum) cowNum  from feed_sum `).First(feedSum).Error
+	err = s.d.DB.Raw(` select sum(cowNum) cowNum  from feed_sum where feedDay like concat('%',?,'%')`, time.Now().Format("2006")).First(feedSum).Error
 	if err != nil {
 		return resp, err
 	}
@@ -87,40 +107,40 @@ WHERE  bpu.useType <> 3
 
 	for _, monthBudget := range monthBudgetList {
 		if monthBudget.FeeType == "维修费" {
-			repair.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+			repair.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 		} else if monthBudget.FeeType == "电费" {
-			electricity.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+			electricity.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 		} else if monthBudget.FeeType == "水费" {
-			water.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+			water.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 		} else if monthBudget.FeeType == "燃动费" {
-			ignition.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+			ignition.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 		}
 	}
 	cowNum := float64(feedSum.CowNum)
 	for _, item := range thisYearActualList {
 		if item.FeeType == "维修费" {
-			repair.Actual = util.Round(item.SumPrice/1000000, 2)
+			repair.Actual = util.Round(item.SumPrice/10000, 2)
 			repair.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 		} else if item.FeeType == "电费" {
-			electricity.Actual = util.Round(item.SumPrice/1000000, 2)
+			electricity.Actual = util.Round(item.SumPrice/10000, 2)
 			electricity.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 		} else if item.FeeType == "水费" {
-			water.Actual = util.Round(item.SumPrice/1000000, 2)
+			water.Actual = util.Round(item.SumPrice/10000, 2)
 			water.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 		} else if item.FeeType == "燃动费" {
-			ignition.Actual = util.Round(item.SumPrice/1000000, 2)
+			ignition.Actual = util.Round(item.SumPrice/10000, 2)
 			ignition.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 		}
 	}
 	for _, item := range lastYearActualList {
 		if item.FeeType == "维修费" {
-			repair.LastActual = util.Round(item.SumPrice/1000000, 2)
+			repair.LastActual = util.Round(item.SumPrice/10000, 2)
 		} else if item.FeeType == "电费" {
-			electricity.LastActual = util.Round(item.SumPrice/1000000, 2)
+			electricity.LastActual = util.Round(item.SumPrice/10000, 2)
 		} else if item.FeeType == "水费" {
-			water.LastActual = util.Round(item.SumPrice/1000000, 2)
+			water.LastActual = util.Round(item.SumPrice/10000, 2)
 		} else if item.FeeType == "燃动费" {
-			ignition.LastActual = util.Round(item.SumPrice/1000000, 2)
+			ignition.LastActual = util.Round(item.SumPrice/10000, 2)
 		}
 	}
 
@@ -157,22 +177,42 @@ func (s *Service) CentralIndex() (*home.CentralIndexResp, error) {
 				CONCAT( YEAR ( NOW()), '-12-31' ),
 			CONCAT( YEAR ( NOW()), '-01-01' )) 
 		)) monthBudget,
-	p.center 
+	center
 FROM
 	month_budget mb
 	JOIN pasture p ON p.id = mb.pastureId 
 WHERE
 	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' ) 
-	AND feeType IN ( '维修费', '电费', '水费', '燃动费', '柴油费', '生物质颗粒', '汽油用量', '煤炭用量' ) 
+	AND feeType IN ( '电费', '水费', '燃动费' ) 
 GROUP BY
-	center `).Find(&monthBudgetList).Error
+	center ,feeType
+	
+	UNION ALL
+	SELECT
+(
+		sum( monthBudget )*(
+			DATEDIFF(
+				NOW(),
+				CONCAT( YEAR ( NOW()), '-01-01' )) / DATEDIFF(
+				CONCAT( YEAR ( NOW()), '-12-31' ),
+			CONCAT( YEAR ( NOW()), '-01-01' )) 
+		)) monthBudget,
+	center 
+FROM
+	month_budget join pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and vendor = 1  and feeType = '维修费'
+and (SELECT iscal FROM department d WHERE d.id=month_budget.deptId)= 0 and  (SELECT name FROM department d WHERE d.id=month_budget.deptId)not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+GROUP BY
+	center`).Find(&monthBudgetList).Error
 	if err != nil {
 		return resp, err
 	}
 
 	thisYearActualList := make([]*home.ThisYearActual, 0)
 	err = s.d.DB.Raw(`select  sum(t.sumPrice) sumPrice,p.center  from (
-	select pastureid,FYLX feeType,sum(HSL) sumPrice from feequery  where Date like  concat( '%',YEAR(NOW()),'%')   and FYLX in ('水费','燃动费','电费','柴油费')  group by FYLX,pastureid 
+	select pastureid,FYLX feeType,sum(HSL) sumPrice from feequery  where Date like  concat( '%',YEAR(NOW()),'%')   
+	 and FYLX in ('水费','燃动费','电费')  group by FYLX,pastureid 
 UNION ALL
 SELECT
   bpu.pastureid,'维修费' feeType ,IFNULL(SUM( pu.sumPrice - pu.quitNumber * pu.price),0) sumPrice
@@ -184,9 +224,10 @@ WHERE  bpu.useType <> 3
   AND (
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
-  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
-  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and bpu.sterilisation = 0  group by bpu.pastureId)  t  
-    join pasture p on p.id = t.pastureId   GROUP BY p.center`).Find(&thisYearActualList).Error
+  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0  and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)  
+ not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处') AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
+  AND (bpu.pastureid = (SELECT id FROM pasture WHERE name = '现代牧业') OR '现代牧业' = '现代牧业') and  pu.dflag != 1  group by bpu.pastureId)  t  
+    join pasture p on p.id = t.pastureId   and p.vendor = 1 and p.IsEnergy = 0 GROUP BY p.center`).Find(&thisYearActualList).Error
 	if err != nil {
 		return resp, err
 	}
@@ -203,25 +244,24 @@ WHERE  bpu.useType <> 3
 	sum := end.Sub(start)
 	sumDay := sum.Hours() / 24
 	realDay := real.Hours() / 24
-	fmt.Println(realDay, sumDay)
 
 	for _, central := range centralIndexList {
 		for _, monthBudget := range monthBudgetList {
 			if monthBudget.Center == central.Central {
-				central.Budget = util.Round(monthBudget.MonthBudget, 2)
-				break
+				central.Budget += util.Round(monthBudget.MonthBudget, 2)
+				//break
 			}
 		}
 		for _, item := range thisYearActualList {
 			if item.Center == central.Central {
-				central.Actual = util.Round(item.SumPrice, 2)
-				break
+				central.Actual += util.Round(item.SumPrice, 2)
+				//break
 			}
 		}
 		if central.Budget > 0 && central.Actual > 0 {
-			central.Complete = util.Round(1+(central.Budget/sumDay*realDay-(central.Actual))/central.Budget*100, 2)
-			central.Budget = util.Round(central.Budget/1000000, 2)
-			central.Actual = util.Round(central.Actual/1000000, 2)
+			central.Complete = util.Round((1+(central.Budget/sumDay*realDay-(central.Actual))/central.Budget)*100, 2)
+			central.Budget = util.Round(central.Budget/10000, 2)
+			central.Actual = util.Round(central.Actual/10000, 2)
 		}
 	}
 	resp.Central = append(resp.Central, centralIndexList...)
@@ -239,7 +279,7 @@ func (s *Service) GetExpense(pastureName string) (*home.GetExpenseResp, error) {
 	}
 
 	monthBudgetList := make([]*home.MonthBudget, 0)
-	err := s.d.DB.Debug().Raw(`SELECT
+	err := s.d.DB.Raw(`SELECT
 (
 		sum( monthBudget )*(
 			DATEDIFF(
@@ -248,13 +288,31 @@ func (s *Service) GetExpense(pastureName string) (*home.GetExpenseResp, error) {
 				CONCAT( YEAR ( NOW()), '-12-31' ),
 			CONCAT( YEAR ( NOW()), '-01-01' )) 
 		)) monthBudget,
-	feeType ,p.center
+	feeType ,pasture.center
 FROM
-	month_budget mb join pasture p on p.id = mb.pastureId
+	month_budget join pasture on pasture.id = month_budget.pastureId
 WHERE
-	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and ( ? = 0  or pastureId = ?)
+	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and vendor = 1  and feeType != '维修费'
 GROUP BY
-	feeType,p.center `, pasture.ID, pasture.ID).Find(&monthBudgetList).Error
+	feeType 
+UNION ALL
+	SELECT
+(
+		sum( monthBudget )*(
+			DATEDIFF(
+				NOW(),
+				CONCAT( YEAR ( NOW()), '-01-01' )) / DATEDIFF(
+				CONCAT( YEAR ( NOW()), '-12-31' ),
+			CONCAT( YEAR ( NOW()), '-01-01' )) 
+		)) monthBudget,
+	feeType ,pasture.center
+FROM
+	month_budget join pasture on pasture.id = month_budget.pastureId
+WHERE
+	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' )  and vendor = 1  and feeType = '维修费'
+and (SELECT iscal FROM department d WHERE d.id=month_budget.deptId)= 0 and  (SELECT name FROM department d WHERE d.id=month_budget.deptId)not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+GROUP BY
+	feeType`).Find(&monthBudgetList).Error
 	if err != nil {
 		return resp, err
 	}
@@ -278,14 +336,15 @@ WHERE  bpu.useType <> 3
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
   ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') 
-      AND CONCAT(YEAR(NOW()),'-12-31')
-  AND  ( ? = 0  or pastureId = ?) and bpu.sterilisation = 0 group by p.center`, pasture.ID, pasture.ID, pasture.ID, pasture.ID).Find(&thisYearActualList).Error
+      AND CONCAT(YEAR(NOW()),'-12-31') and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)  
+                                                  not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处')
+  AND  ( ? = 0  or pastureId = ?) and  pu.dflag != 1   and p.vendor = 1 group by p.center`, pasture.ID, pasture.ID, pasture.ID, pasture.ID).Find(&thisYearActualList).Error
 	if err != nil {
 		return resp, err
 	}
 
 	lastYearActualList := make([]*home.ThisYearActual, 0)
-	err = s.d.DB.Debug().Raw(`select FYLX feeType,sum(HSL) sumPrice,p.center from feequery  fq  join pasture p on p.id = fq.pastureId  where Date like  concat( '%',YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'%')  
+	err = s.d.DB.Debug().Raw(`select FYLX feeType,sum(HSL) sumPrice,p.center from feequery  fq  join pasture p on p.id = fq.pastureId  where  	DATE_FORMAT(STR_TO_DATE( Date, '%Y-%m' ),'%Y-%m') between CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01') and DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 YEAR),'%Y-%m')
                                                      and FYLX in ('水费','燃动费','电费')   and ( ? = 0  or pastureId = ?)  group by FYLX,p.center
 
 UNION ALL
@@ -301,14 +360,9 @@ WHERE  bpu.useType <> 3
   AND (
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
-  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
-  AND  ( ? = 0  or pastureId = ?)  and bpu.sterilisation = 0 group by p.center`, pasture.ID, pasture.ID, pasture.ID, pasture.ID).Find(&lastYearActualList).Error
-	if err != nil {
-		return resp, err
-	}
-
-	feedSum := new(model.FeedSum)
-	err = s.d.DB.Raw(` select sum(cowNum) cowNum  from feed_sum `).First(feedSum).Error
+  ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)),'-01-01') AND DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
+  AND  ( ? = 0  or pastureId = ?) and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)  
+                                            not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处') and  pu.dflag != 1 group by p.center`, pasture.ID, pasture.ID, pasture.ID, pasture.ID).Find(&lastYearActualList).Error
 	if err != nil {
 		return resp, err
 	}
@@ -334,39 +388,68 @@ WHERE  bpu.useType <> 3
 		if monthBudget.FeeType == "维修费" {
 			for _, repair := range repairList {
 				if repair.Center == monthBudget.Center {
-					repair.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+					repair.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 					break
 				}
 			}
 		} else if monthBudget.FeeType == "电费" {
 			for _, electricity := range electricityList {
 				if electricity.Center == monthBudget.Center {
-					electricity.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+					electricity.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 					break
 				}
 			}
 		} else if monthBudget.FeeType == "水费" {
 			for _, water := range waterList {
 				if water.Center == monthBudget.Center {
-					water.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+					water.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 					break
 				}
 			}
 		} else if monthBudget.FeeType == "燃动费" {
 			for _, ignition := range ignitionList {
 				if ignition.Center == monthBudget.Center {
-					ignition.Budget = util.Round(monthBudget.MonthBudget/1000000, 2)
+					ignition.Budget = util.Round(monthBudget.MonthBudget/10000, 2)
 					break
 				}
 			}
 		}
 	}
-	cowNum := float64(feedSum.CowNum)
+
+	feedSumList := make([]*model.FeedSumAndPasture, 0)
+	feedSum := new(model.FeedSumAndPasture)
+	if pasture.ID == 0 {
+		err = s.d.DB.Raw(` select sum(cowNum) cowNum,center  from feed_sum  join pasture on pasture.id = feed_sum.pastureId
+                            where feedDay like concat('%',?,'%')   group by center`, time.Now().Format("2006")).Find(&feedSumList).Error
+		if err != nil {
+			return resp, err
+		}
+	} else {
+		err = s.d.DB.Raw(` select sum(cowNum) cowNum  from feed_sum  join pasture on pasture.id = feed_sum.pastureId
+                            where feedDay like concat('%',?,'%')  and pastureId = ?  `, time.Now().Format("2006"), pasture.ID).First(&feedSum).Error
+		if err != nil {
+			return resp, err
+		}
+	}
+	//cowNum := float64(feedSum.CowNum)
 	for _, item := range thisYearActualList {
+		var cowNum float64
+		if pasture.ID == 0 {
+			for _, center := range feedSumList {
+				if center.Center == item.Center {
+					cowNum = float64(center.CowNum)
+					break
+				}
+			}
+		} else {
+			cowNum = float64(feedSum.CowNum)
+		}
+
 		if item.FeeType == "维修费" {
 			for _, repair := range repairList {
 				if repair.Center == item.Center {
-					repair.Actual = util.Round(item.SumPrice/1000000, 2)
+					repair.Actual = util.Round(item.SumPrice/10000, 2)
+
 					repair.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 					break
 				}
@@ -376,7 +459,7 @@ WHERE  bpu.useType <> 3
 			//electricity.Actual = util.Round(electricity.Actual/cowNum, 2)
 			for _, electricity := range electricityList {
 				if electricity.Center == item.Center {
-					electricity.Actual = util.Round(item.SumPrice/1000000, 2)
+					electricity.Actual = util.Round(item.SumPrice/10000, 2)
 					electricity.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 					break
 				}
@@ -386,7 +469,7 @@ WHERE  bpu.useType <> 3
 			//water.Actual = util.Round(water.Actual/cowNum, 2)
 			for _, water := range waterList {
 				if water.Center == item.Center {
-					water.Actual = util.Round(item.SumPrice/1000000, 2)
+					water.Actual = util.Round(item.SumPrice/10000, 2)
 					water.SingleCow = util.Round(item.SumPrice/cowNum, 2)
 					break
 				}
@@ -398,7 +481,7 @@ WHERE  bpu.useType <> 3
 				if ignition.Center == item.Center {
 					//ignition.Actual = util.Round(item.SumPrice, 2)
 					ignition.SingleCow = util.Round(item.SumPrice/cowNum, 2)
-					ignition.Actual = util.Round(item.SumPrice/1000000, 2)
+					ignition.Actual = util.Round(item.SumPrice/10000, 2)
 					break
 				}
 			}
@@ -409,7 +492,7 @@ WHERE  bpu.useType <> 3
 		if item.FeeType == "维修费" {
 			for _, repair := range repairList {
 				if repair.Center == item.Center {
-					repair.LastActual = util.Round(item.SumPrice/1000000, 2)
+					repair.LastActual = util.Round(item.SumPrice/10000, 2)
 					break
 				}
 			}
@@ -418,7 +501,7 @@ WHERE  bpu.useType <> 3
 			//electricity.LastActual = util.Round(item.SumPrice, 2)
 			for _, electricity := range electricityList {
 				if electricity.Center == item.Center {
-					electricity.LastActual = util.Round(item.SumPrice/1000000, 2)
+					electricity.LastActual = util.Round(item.SumPrice/10000, 2)
 					break
 				}
 			}
@@ -426,7 +509,7 @@ WHERE  bpu.useType <> 3
 			//water.LastActual = util.Round(item.SumPrice, 2)
 			for _, water := range waterList {
 				if water.Center == item.Center {
-					water.LastActual = util.Round(item.SumPrice/1000000, 2)
+					water.LastActual = util.Round(item.SumPrice/10000, 2)
 					break
 				}
 			}
@@ -434,7 +517,7 @@ WHERE  bpu.useType <> 3
 			//ignition.LastActual = util.Round(item.SumPrice, 2)
 			for _, ignition := range ignitionList {
 				if ignition.Center == item.Center {
-					ignition.LastActual = util.Round(item.SumPrice/1000000, 2)
+					ignition.LastActual = util.Round(item.SumPrice/10000, 2)
 					break
 				}
 			}
@@ -459,7 +542,7 @@ FROM
 	JOIN pasture p ON p.id = mb.pastureId 
 WHERE
 	budgetMonth LIKE concat( '%', date_format( now(), '%Y' ), '%' ) 
-	AND feeType IN ( '维修费', '电费', '水费', '燃动费', '柴油费', '生物质颗粒', '汽油用量', '煤炭用量' )  and p.name = ? `, pastureName).Find(&monthBudget).Error
+	AND feeType IN ( '维修费', '电费', '水费', '燃动费' )  and p.name = ? `, pastureName).Find(&monthBudget).Error
 	if err != nil {
 		return resp, err
 	}
@@ -467,7 +550,7 @@ WHERE
 	thisYearActual := new(home.ThisYearActual)
 	err = s.d.DB.Raw(`select  sum(t.sumPrice) sumPrice from (
 	select pastureid,FYLX feeType,sum(HSL) sumPrice from feequery  fq join pasture p on p.id = fq.pastureId where Date like  concat( '%',YEAR(NOW()),'%')  
-	                                                               and FYLX in ('水费','燃动费','电费','柴油费')  and p.name = ?
+	                                                               and FYLX in ('水费','燃动费','电费')  and p.name = ?
 UNION ALL
 SELECT
   bpu.pastureid,'维修费' feeType ,IFNULL(SUM( pu.sumPrice - pu.quitNumber * pu.price),0) sumPrice
@@ -481,8 +564,8 @@ WHERE  bpu.useType <> 3
     pu.useTypeV = '维修'
     OR pu.useTypeV = '保养'
   ) AND (SELECT iscal FROM department d WHERE d.id=bpu.departmentId)= 0 AND  bpu.receiveTime BETWEEN CONCAT(YEAR(NOW()),'-01-01') AND CONCAT(YEAR(NOW()),'-12-31')
-  AND p.name = ?  and bpu.sterilisation = 0  group by bpu.pastureId)  t  
-    join pasture p on p.id = t.pastureId   GROUP BY p.center`, pastureName, pastureName).Find(&thisYearActual).Error
+  AND p.name = ? and   (SELECT name FROM department d WHERE d.id=bpu.departmentId)   not in  ('饲养处','犊牛处','品控处','繁育处','兽医处','安环处','供应处') and  pu.dflag != 1  group by bpu.pastureId)  t  
+    join pasture p on p.id = t.pastureId and p.vendor = 1  GROUP BY p.center`, pastureName, pastureName).Find(&thisYearActual).Error
 	if err != nil {
 		return resp, err
 	}
@@ -502,9 +585,14 @@ WHERE  bpu.useType <> 3
 	fmt.Println(realDay, sumDay)
 	resp.Budget = monthBudget.MonthBudget
 	resp.Actual = thisYearActual.SumPrice
-	resp.Complete = util.Round((1+(resp.Budget/sumDay*realDay-(resp.Actual))/resp.Budget)*100, 2)
-	resp.Budget = util.Round(resp.Budget/1000000, 2)
-	resp.Actual = util.Round(resp.Actual/1000000, 2)
+
+	if resp.Budget != 0 && resp.Actual != 0 {
+		resp.Complete = util.Round((1+(resp.Budget/sumDay*realDay-(resp.Actual))/resp.Budget)*100, 2)
+	}
+	//ROUND(1+((qq.monthLimit/qq.sumDay*qq.realDay-(qq.sumPrice/10000))/(qq.monthLimit/qq.sumDay*qq.realDay)), 2)
+
+	resp.Budget = util.Round(resp.Budget/10000, 2)
+	resp.Actual = util.Round(resp.Actual/10000, 2)
 	//resp.Complete = util.Round(1+(resp.Budget/sumDay*realDay-(resp.Actual/10000))/(resp.Budget/sumDay*realDay), 2)
 
 	return resp, nil

+ 214 - 0
apiserver/service/idaas.go

@@ -1 +1,215 @@
 package service
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/middleware/jwt"
+	"kpt.xdmy/pkg/logging"
+	"kpt.xdmy/pkg/setting"
+	"kpt.xdmy/pkg/util"
+	"net"
+	"time"
+)
+
+func (s *Service) OAuth2Token(code, host string) (*http.OAuth2TokenResp, error) {
+	authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(setting.IDaaSSetting.ClientId+":"+setting.IDaaSSetting.ClientSecret)))
+	resp := new(http.OAuth2TokenResp)
+	fmt.Println(code, time.Now())
+	//host = "http://tmrwatch.cn:8082"
+	if host == "eam" {
+		host = "https://192-168-61-418000-8jyo36i0p8n4to.ztna-dingtalk.com"
+		url := fmt.Sprintf(setting.IDaaSSetting.Url+"/api/v1/oauth2/token?&grant_type=%s&code=%s&redirect_uri=%s", "authorization_code",
+			code, fmt.Sprintf("%s/api/v1/oauth2/token", host))
+		respByte, err := jwt.PostPush(url, nil, authorization)
+		if err != nil {
+			host = "https://eam.modernfarming.cn:8000"
+			url := fmt.Sprintf(setting.IDaaSSetting.Url+"/api/v1/oauth2/token?&grant_type=%s&code=%s&redirect_uri=%s", "authorization_code",
+				code, fmt.Sprintf("%s/api/v1/oauth2/token", host))
+			respByte, err := jwt.PostPush(url, nil, authorization)
+			if err != nil {
+				log.Error(err)
+				return resp, err
+			}
+			err = json.Unmarshal(respByte, &resp)
+			if err != nil {
+				log.Error(err)
+				return resp, err
+			}
+			return resp, nil
+		}
+		err = json.Unmarshal(respByte, &resp)
+		if err != nil {
+			log.Error(err)
+			return resp, err
+		}
+		return resp, nil
+	}
+
+	fmt.Println(fmt.Sprintf("%s/api/v1/oauth2/token", host))
+	url := fmt.Sprintf(setting.IDaaSSetting.Url+"/api/v1/oauth2/token?&grant_type=%s&code=%s&redirect_uri=%s", "authorization_code",
+		code, fmt.Sprintf("%s/api/v1/oauth2/token", host))
+	respByte, err := jwt.PostPush(url, nil, authorization)
+	if err != nil {
+		log.Error(err)
+		return resp, err
+	}
+
+	err = json.Unmarshal(respByte, &resp)
+	if err != nil {
+		log.Error(err)
+		return resp, err
+	}
+
+	return resp, nil
+}
+
+func (s *Service) OAuth2Logout(token, host string) error {
+	authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(setting.IDaaSSetting.ClientId+":"+setting.IDaaSSetting.ClientSecret)))
+	url := fmt.Sprintf(setting.IDaaSSetting.Url+"/api/v1/oauth2/introspect?token=%s&token_type_hint=%s", token, "access_token")
+	_, err := jwt.PostPush(url, nil, authorization)
+	if err != nil {
+		log.Error(err)
+		return err
+	}
+	//host = "http://tmrwatch.cn:8082"
+	if host == "eam" {
+		host = "https://192-168-61-418000-8jyo36i0p8n4to.ztna-dingtalk.com"
+		_, err = jwt.PostPush(fmt.Sprintf("%s/api/v1/logout?redirect_url=%s&client_id=%s", setting.IDaaSSetting.Url, host, setting.IDaaSSetting.ClientId), nil, "")
+		if err != nil {
+			host = "https://eam.modernfarming.cn:8000"
+			_, err = jwt.PostPush(fmt.Sprintf("%s/api/v1/logout?redirect_url=%s&client_id=%s", setting.IDaaSSetting.Url, host, setting.IDaaSSetting.ClientId), nil, "")
+			if err != nil {
+				log.Error(err)
+				return err
+			}
+		}
+		return nil
+	}
+
+	_, err = jwt.PostPush(fmt.Sprintf("%s/api/v1/logout?redirect_url=%s&client_id=%s", setting.IDaaSSetting.Url, host, setting.IDaaSSetting.ClientId), nil, "")
+	if err != nil {
+		log.Error(err)
+		return err
+	}
+
+	return nil
+}
+
+func getHostIp() string {
+	addrList, err := net.InterfaceAddrs()
+	if err != nil {
+		fmt.Println("get current host ip err: ", err)
+		return ""
+	}
+	var ip string
+	for _, address := range addrList {
+		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
+			if ipNet.IP.To4() != nil {
+				ip = ipNet.IP.String()
+				break
+			}
+		}
+	}
+
+	return ip
+}
+
+func (s *Service) OAuth2AddUser(userInfo *http.OAuth2AddUser) (*model.UserInfo, error) {
+	var userCount, empCount int64
+
+	err := s.d.DB.Table("emp").Where("empCode = ? ", userInfo.Username).Count(&empCount).Error
+	if err != nil {
+		logging.Error(err)
+		return nil, err
+	}
+
+	emp1 := new(model.Emp)
+	s.d.DB.Table("emp").Where("empCode = ? ", userInfo.Username).First(&emp1)
+
+	pasture := new(model.Pasture)
+	if userInfo.Pasture != "" {
+		err = s.d.DB.Where("name = ? ", userInfo.Pasture).First(&pasture).Error
+		if err != nil {
+			logging.Error(err)
+			return nil, err
+		}
+	}
+
+	emp := new(model.Emp)
+	emp.Empname = userInfo.Name
+	emp.EmpCode = userInfo.Username
+	emp.Empname = userInfo.Name
+	if !userInfo.Disabled {
+		emp.Work = 1
+	} else {
+		emp.Work = 0
+	}
+	if empCount == 0 {
+		emp.PastureId = "18"
+	} else {
+		emp.PastureId = emp1.PastureId
+	}
+	if empCount == 0 {
+		err = s.d.DB.Create(&emp).Error
+		if err != nil {
+			logging.Error(err)
+			return nil, err
+		}
+	} else {
+		fmt.Println(emp)
+		err = s.d.DB.Debug().Exec(` update emp set work = ? ,pastureId = ? ,empname = ? where empCode = ?  `,
+			emp.Work, emp.PastureId, emp.Empname, userInfo.Username).Error
+		if err != nil {
+			logging.Error(err)
+			return nil, err
+		}
+
+		err = s.d.DB.Where("empCode = ? ", userInfo.Username).First(&emp).Error
+		if err != nil {
+			logging.Error(err)
+			return nil, err
+		}
+	}
+
+	err = s.d.DB.Table("user").Where("username = ? ", userInfo.Username).Count(&userCount).Error
+	if err != nil {
+		logging.Error(err)
+		return nil, err
+	}
+
+	user := new(model.UserInfo)
+	user.Empid = emp.Id
+	user.Username = userInfo.Username
+	user.Enable = emp.Work
+	user.Idaas = userInfo.UserId
+	if userInfo.PassWord != "" {
+		user.PassWord = util.EncodeMD5(userInfo.PassWord)
+	}
+
+	if userCount == 0 {
+		err = s.d.DB.Create(&user).Error
+		if err != nil {
+			logging.Error(err)
+			return user, err
+		}
+	} else {
+		err = s.d.DB.Debug().Exec(`UPDATE user SET  empid =?, password=?,enable = ?  WHERE username = ? `, user.Empid, user.PassWord, user.Enable, user.Username).Error
+		if err != nil {
+			logging.Error(err)
+			return user, err
+		}
+
+		err = s.d.DB.Where(" username = ? ", user.Username).First(&user).Error
+		if err != nil {
+			logging.Error(err)
+			return user, err
+		}
+
+	}
+
+	return user, nil
+}

+ 35 - 2
apiserver/service/job.go

@@ -24,6 +24,34 @@ func SapJobInit() {
 	})
 	//c.Start()
 
+	//t := time.Now()
+	//i := 60
+	//pastureList := make([]*model.Pasture, 0)
+	//s.d.DB.Table("pasture").Where("id in(1768,1769,1770,1771,1772)").Find(&pastureList)
+	//
+	//for {
+	//	//for _, pasture := range pastureList {
+	//	s.SapAsset(t.AddDate(0, 0, -i), "", "1020")
+	//	//}
+	//
+	//	if i == 0 {
+	//		panic("break")
+	//	}
+	//	i--
+	//}
+	var t time.Time
+	t = time.Now()
+	s.SapMaterial(t.AddDate(0, 0, -1), "")
+	s.SapMaterial(t.AddDate(0, 0, -2), "")
+	s.SapMaterial(t.AddDate(0, 0, -3), "")
+	s.SapMaterial(t.AddDate(0, 0, -4), "")
+	s.SapMaterial(t.AddDate(0, 0, -5), "")
+	s.SapMaterial(t.AddDate(0, 0, -6), "")
+	s.SapMaterial(t.AddDate(0, 0, -7), "")
+	s.SapMaterial(t.AddDate(0, 0, -8), "")
+	//s.SapMaterial(t.AddDate(0, 0, -9), "")
+	//s.SapMaterial(t.AddDate(0, 0, -10), "")
+	//s.SapMaterial(t.AddDate(0, 0, -11), "")
 	c1 := cron.New()
 	c1.AddFunc("0 40 23 * * ?", func() {
 		fmt.Println(time.Now())
@@ -40,6 +68,9 @@ func SapJobInit() {
 			s.SapAssetSalvage(t, pasture.CompanyCode, pasture.ID)
 		}
 		s.SapMaterial(t, code)
+		s.SapMaterial(t.AddDate(0, 0, -1), code)
+		s.SapMaterial(t.AddDate(0, 0, -2), code)
+		s.SapMaterial(t.AddDate(0, 0, -3), code)
 		s.d.DB.Exec(`call createEqstatus()`)
 	})
 
@@ -55,7 +86,6 @@ func SapJobInit() {
 			s.d.DB.Exec(`call createRUcode(?)`, pasture.ID)
 		}
 	})
-
 	duetimecst, _ = time.ParseInLocation("15:04:05", "00:05:00", time.Local)
 	duetimecst1, _ = time.ParseInLocation("15:04:05", "00:00:00", time.Local)
 	spec2 := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
@@ -91,10 +121,13 @@ func SapJobInit() {
 	})
 
 	c1.AddFunc("0 20 23 * * ?", func() {
+		s.SyncPasture()
+		s.SyncEquipmentDate()
 		AutoContractToASP()
 	})
-	AutoContractToASP()
+	//AutoContractToASP()
 	//c1.Start()
+	//s.SyncEquipmentDate()
 }
 
 func jobMaterial() {

+ 551 - 0
apiserver/service/liugong.go

@@ -1 +1,552 @@
 package service
+
+import (
+	"encoding/json"
+	"fmt"
+	"github.com/astaxie/beego/logs"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/liugong"
+	"kpt.xdmy/pkg/util"
+	"strings"
+	"time"
+)
+
+////柳工客户平台注册
+//func (s *Service) RegisterLG() {
+//	registerReq := new(liugong.RegisterLG)
+//	registerReq.UserName = s.http.Liugong.UserName
+//	registerReq.PassWord = s.http.Liugong.PassWord
+//	reqStr, _ := json.Marshal(registerReq)
+//	registerByte, err := util.PostPush(s.http.Liugong.Routing, reqStr)
+//	if err != nil {
+//		logging.Error("柳工接口注册失败error-1:" + err.Error())
+//		return
+//	}
+//
+//	resp := new(liugong.RegisterLGResp)
+//	err = json.Unmarshal(registerByte, &resp)
+//	if err != nil {
+//		logging.Error("柳工接口注册失败error-2:" + err.Error())
+//		return
+//	}
+//
+//	liugongData := new(liugong.LiuGongToken)
+//	liugongData.Token = resp.Token
+//	liugongData.UpdateDate = time.Now()
+//	var count int64
+//	s.d.DB.Model(liugongData).Count(&count)
+//	if count == 0 {
+//		err = s.d.DB.Debug().FirstOrCreate(liugongData).Error
+//		if err != nil {
+//			logging.Error("柳工接口注册失败error-3:" + err.Error())
+//			return
+//		}
+//	} else {
+//		err = s.d.DB.Debug().Where("1=1").Updates(liugongData).Error
+//		if err != nil {
+//			logging.Error("柳工接口注册失败error-3:" + err.Error())
+//			return
+//		}
+//	}
+//}
+//
+////客户令牌获取
+//func (s *Service) GetLiuGongToken() (*liugong.LiuGongToken, error) {
+//	resp := new(liugong.LiuGongToken)
+//	err := s.d.DB.Debug().First(&resp).Error
+//	if err != nil {
+//		logging.Error(err.Error())
+//		return nil, err
+//	}
+//
+//	return resp, nil
+//}
+//
+////柳工设备数据推送
+//func (s *Service) LGPushEquipmentInfo(req *liugong.PushEquipmentInfoReq) ([]string, error) {
+//	var errorList []string
+//	for _, eq := range req.EquipmentList {
+//		//date, err1 := time.Parse("2006-01-02 15:04:05", eq.Date)
+//		//fmt.Println(err1)
+//		vehicle := new(liugong.Vehicle)
+//		vehicle.License = eq.License
+//		vehicle.WorkHour = eq.WorkHour
+//		vehicle.IdleHour = eq.IdleHour
+//		vehicle.FuelConsumption = eq.FuelConsumption
+//		vehicle.IdleFuel = eq.IdleFuel
+//		vehicle.HoursConsumption = eq.HoursConsumption
+//		vehicle.Longitude = eq.Longitude
+//		vehicle.Latitude = eq.Latitude
+//		vehicle.FuelLevel = eq.FuelLevel
+//		vehicle.PowerConsumption = eq.PowerConsumption
+//		vehicle.HoursPowerConsumption = eq.HoursPowerConsumption
+//		vehicle.ChargeCapacity = eq.ChargeCapacity
+//		vehicle.ChargeHour = eq.ChargeHour
+//		vehicle.ChargeStatus = eq.ChargeStatus
+//		vehicle.BatteryPackSoc = eq.BatteryPackSoc
+//		vehicle.Date = eq.Date[:11]
+//		//eqData := new(model.Equipment)
+//		//err := s.d.DB.Select("id,eqCode,pastureId").Where("license = ?", eq.License).First(&eqData).Error
+//		//if err != nil {
+//		//	logging.Error(err)
+//		//	errorList = append(errorList, fmt.Sprintf("%s %s 未找到对应设备;", err.Error(), eq.License))
+//		//	continue
+//		//}
+//		//vehicle.EqId = int64(eqData.Id)
+//		//vehicle.EqCode = eqData.EqCode
+//		//vehicle.PastureId = eqData.PastureId
+//		//`eqId`, `eqCode`, `license`, `dataTime`
+//		var count int64
+//		err := s.d.DB.Debug().Model(new(liugong.Vehicle)).Where(liugong.Vehicle{License: eq.License, Date: vehicle.Date}).Count(&count).Error
+//		if count == 0 {
+//			err = s.d.DB.Where(liugong.Vehicle{License: eq.License, Date: vehicle.Date}).FirstOrCreate(&vehicle).Error
+//			if err != nil {
+//				logging.Error(err)
+//				continue
+//			}
+//		} else {
+//			err = s.d.DB.Where(liugong.Vehicle{License: eq.License, Date: vehicle.Date}).Updates(&vehicle).Error
+//			if err != nil {
+//				logging.Error(err)
+//				continue
+//			}
+//		}
+//
+//	}
+//
+//	now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
+//	err := s.d.DB.Exec(` update vehicle v  set v.currentWorkHour =v.workHour - (select ifnull(workHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ) ,
+//                       v.currentIdleHour = v.idleHour-(select ifnull(idleHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ),
+//                       v.currentFuelConsumption = v.fuelConsumption -(select ifnull(fuelConsumption,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ),
+//                       v.currentIdleFuel = v.idleFuel-(select ifnull(idleFuel,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    				   v.currentPowerConsumption = v.powerConsumption-(select ifnull(powerConsumption,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    					v.currentChargeCapacity = v.chargeCapacity-(select ifnull(chargeCapacity,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    				  v.currentChargeHour = v.chargeHour-(select ifnull(chargeHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1)
+//                      where dataTime = ? `, now, now, now, now, now, now, now, now).Error
+//	if err != nil {
+//		logging.Error(err)
+//		return nil, err
+//	}
+//	//currentPowerConsumption
+//	//currentChargeCapacity
+//	//currentChargeHour
+//	now = time.Now().Format("2006-01-02")
+//	err = s.d.DB.Exec(` update vehicle v  set v.currentWorkHour =v.workHour - (select ifnull(workHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ) ,
+//                       v.currentIdleHour = v.idleHour-(select ifnull(idleHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ),
+//                       v.currentFuelConsumption = v.fuelConsumption -(select ifnull(fuelConsumption,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1 ),
+//                       v.currentIdleFuel = v.idleFuel-(select ifnull(idleFuel,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    				   v.currentPowerConsumption = v.powerConsumption-(select ifnull(powerConsumption,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    					v.currentChargeCapacity = v.chargeCapacity-(select ifnull(chargeCapacity,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1),
+//    				  v.currentChargeHour = v.chargeHour-(select ifnull(chargeHour,0) from vehicle where dataTime < ? and license = v.license  order by  dataTime desc limit 1)
+//                      where dataTime = ? `, now, now, now, now, now, now, now, now).Error
+//	if err != nil {
+//		logging.Error(err)
+//		return nil, err
+//	}
+//
+//	return errorList, nil
+//}
+//
+//func (s *Service) GetVehicleList(req *liugong.GetVehicleListReq) ([]*liugong.VehicleAndPasture, int64, error) {
+//	tx := s.d.DB.Table(new(liugong.Vehicle).TableName())
+//
+//	tx.Joins(" join equipment  on equipment.license = vehicle.license")
+//	tx.Joins(" join pasture  on pasture.id = equipment.pastureId")
+//
+//	tx.Select("vehicle.id,equipment.Id eqId,equipment.eqCode,equipment.pastureId,vehicle.license," +
+//		"vehicle.workHour,vehicle.idleHour,vehicle.fuelConsumption,vehicle.idleFuel,vehicle.hoursConsumption," +
+//		"vehicle.longitude,vehicle.latitude,vehicle.fuelLevel,DATE_FORMAT(vehicle.dataTime,'%Y-%m-%d') dataTime  ,vehicle.createTime,vehicle.currentWorkHour," +
+//		"vehicle.currentIdleHour,vehicle.currentIdleFuel,vehicle.powerConsumption,vehicle.hoursPowerConsumption," +
+//		"vehicle.chargeCapacity,vehicle.chargeHour,vehicle.chargeStatus,vehicle.batteryPackSoc,vehicle.currentPowerConsumption," +
+//		"vehicle.currentChargeCapacity,vehicle.currentChargeHour,vehicle.currentFuelConsumption,pasture.name")
+//	if req.PastureId != "" {
+//		tx.Where("pastureId = ?", req.PastureId)
+//	}
+//	if req.StartTime != "" {
+//		tx.Where(" dataTime between ? and ?", req.StartTime, req.EndTime)
+//	}
+//
+//	vehicleList := make([]*liugong.VehicleAndPasture, 0)
+//	var count int64
+//	tx.Count(&count)
+//	tx.Limit(req.PageCount).Offset(req.Offset)
+//
+//	err := tx.Debug().Order(" dataTime desc,pastureId asc ").Find(&vehicleList).Error
+//	if err != nil {
+//		return nil, 0, err
+//	}
+//	return vehicleList, count, nil
+//}
+func (s *Service) SyncEquipmentDate() {
+	eqList := make([]*model.EquipmentAndDepartment, 0)
+	err := s.d.DB.Raw(`select * from equipment e  join eqclass ec on ec.id = e.eqClassId  
+    join department d on d.id = e.departmentId where e.license is not null  and  e.license != ''  and e.pushStatus in(0,1,2) `).Find(&eqList).Error
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+	if len(eqList) == 0 {
+		return
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Raw(`select p.id,p.center,p.name,p.pastureNumber,d1.name region,d1.id region_id 
+from pasture  p join  department d on  d.id = p.id join department d1 on d1.id = d.parentid where p.vendor = 1 `).Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+	}
+
+	vehicleList := make([]*liugong.VehicleInfo, 0)
+	for _, eq := range eqList {
+		arg := new(liugong.VehicleInfo)
+		for _, pasture := range pastureList {
+			if pasture.ID == eq.PastureId {
+				arg.AreaName = fmt.Sprintf("%d", pasture.RegionID)
+				center := 0
+				if pasture.Center == "一中心" {
+					center = 1
+				} else if pasture.Center == "二中心" {
+					center = 2
+				} else if pasture.Center == "三中心" {
+					center = 3
+				}
+				arg.OperationName = fmt.Sprintf("%d", center)
+				break
+			}
+		}
+		arg.RancheName = fmt.Sprintf("%d", eq.Equipment.PastureId)
+		arg.VehicleType = eq.EqClass.TypeName
+		arg.VehicleLicense = eq.EqCode
+		arg.DeviceLicense = eq.License
+		arg.Specification = eq.Specification
+		arg.Brand = eq.Brand
+		arg.Usage = eq.Purpose
+		arg.DeptName = eq.Department.Name
+
+		purchaseDate, err := time.Parse("20060102", eq.PurchaseDate)
+		if err != nil {
+			arg.PurchaseDate = eq.PurchaseDate
+		} else {
+			arg.PurchaseDate = purchaseDate.Format("2006-01-02")
+		}
+
+		entranceDate, err := time.Parse("20060102", eq.EntranceDate)
+		if err != nil {
+			entranceDate1, err := time.Parse("2006-01-02", eq.EntranceDate)
+			if err == nil {
+				arg.EnterDate = entranceDate1.Format("2006-01-02")
+			} else {
+				continue
+			}
+		} else {
+			arg.EnterDate = entranceDate.Format("2006-01-02")
+		}
+
+		arg.ScrapDate = eq.LeaveDate.Format("2006-01-02")
+		arg.StandardHour = eq.Duration
+		arg.Status = eq.PushStatus
+		arg.VehicleName = eq.EqName
+		arg.WorkClass = eq.WorkClass
+		vehicleList = append(vehicleList, arg)
+	}
+
+	vehicleListReq := make([]*liugong.VehicleInfo, 0)
+	for _, vehicle := range vehicleList {
+		vehicleListReq = append(vehicleListReq, vehicle)
+		if len(vehicleListReq) > 50 {
+
+			dataByte, err := json.Marshal(vehicleListReq)
+			if err != nil {
+				logs.Error(err)
+				return
+			}
+			fmt.Println(string(dataByte))
+			url := "http://meadow.nandasoft-its.com:26101/vientiane/pushVehicleInfo"
+			respByte, err := util.PostPush(url, dataByte)
+			if err != nil {
+				logs.Error(err)
+			}
+
+			fmt.Println(string(respByte))
+			vientianeResp := new(liugong.VientianeResp)
+			err = json.Unmarshal(respByte, &vientianeResp)
+			if err != nil {
+				logs.Error(err)
+				return
+			}
+			fmt.Println(string(dataByte))
+			if vientianeResp.Code == 200 {
+				for _, eq := range eqList {
+					err := s.d.DB.Exec(` update equipment set pushStatus = 3  where id = ? `, eq.Equipment.Id).Error
+					if err != nil {
+						logs.Error(err)
+						return
+					}
+				}
+				vientianeResp.Status = vientianeResp.Code
+			}
+			err = s.d.DB.Exec(` insert into vehiclelog(url,param,status,msgtext,resp)values(?,?,?,?,?) `, url, string(dataByte), vientianeResp.Status, vientianeResp.Msg, string(respByte)).Error
+			if err != nil {
+				logs.Error(err)
+				return
+			}
+			vehicleListReq = make([]*liugong.VehicleInfo, 0)
+		}
+	}
+
+	if len(vehicleListReq) > 0 {
+		dataByte, err := json.Marshal(vehicleListReq)
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+		fmt.Println(string(dataByte))
+		url := "http://meadow.nandasoft-its.com:26101/vientiane/pushVehicleInfo"
+		respByte, err := util.PostPush(url, dataByte)
+		if err != nil {
+			logs.Error(err)
+		}
+
+		fmt.Println(string(respByte))
+		vientianeResp := new(liugong.VientianeResp)
+		err = json.Unmarshal(respByte, &vientianeResp)
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+		fmt.Println(string(dataByte))
+		if vientianeResp.Code == 200 {
+			for _, eq := range eqList {
+				err := s.d.DB.Exec(` update equipment set pushStatus = 3  where id = ? `, eq.Equipment.Id).Error
+				if err != nil {
+					logs.Error(err)
+					return
+				}
+			}
+			vientianeResp.Status = vientianeResp.Code
+		}
+
+		err = s.d.DB.Exec(` insert into vehiclelog(url,param,status,msgtext,resp)values(?,?,?,?,?) `, url, string(dataByte), vientianeResp.Status, vientianeResp.Msg, string(respByte)).Error
+		if err != nil {
+			logs.Error(err)
+			return
+		}
+	}
+}
+
+func (s *Service) SyncPasture() {
+	pastureList := make([]*model.Pasture, 0)
+	err := s.d.DB.Raw(`select p.id,p.center,p.name,p.pastureNumber,d1.name region,d1.id region_id 
+from pasture  p join  department d on  d.id = p.id join department d1 on d1.id = d.parentid where p.vendor = 1 and p.IsEnergy = 0 `).Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+	}
+
+	pasturePushList := make([]map[string]interface{}, 0)
+	center1 := make(map[string]interface{}, 0)
+	center1["code"] = 1
+	center1["name"] = "一中心"
+
+	center2 := make(map[string]interface{}, 0)
+	center2["code"] = 2
+	center2["name"] = "二中心"
+
+	center3 := make(map[string]interface{}, 0)
+	center3["code"] = 3
+	center3["name"] = "三中心"
+
+	regionList := make([]map[string]interface{}, 0)
+	regionNameList := make([]string, 0)
+
+	for _, pasture := range pastureList {
+		if len(regionNameList) == 0 {
+			regionNameList = append(regionNameList, pasture.Region)
+		} else {
+			exist := false
+			for _, regionName := range regionNameList {
+				if regionName == pasture.Region {
+					exist = true
+					break
+				}
+			}
+			if exist {
+				continue
+			}
+			regionNameList = append(regionNameList, pasture.Region)
+		}
+		region := make(map[string]interface{}, 0)
+		region["code"] = pasture.RegionID
+		region["name"] = pasture.Region
+		region["center"] = pasture.Center
+		pastureMapList := make([]map[string]interface{}, 0)
+		for _, pasture1 := range pastureList {
+			if pasture.Region == pasture1.Region {
+				pastureMap := make(map[string]interface{}, 0)
+				pastureMap["code"] = pasture1.ID
+				pastureMap["name"] = pasture1.Name
+				pastureMapList = append(pastureMapList, pastureMap)
+			}
+		}
+		region["subDepts"] = pastureMapList
+		regionList = append(regionList, region)
+	}
+	pasturePushList = append(pasturePushList, center1)
+	pasturePushList = append(pasturePushList, center2)
+	pasturePushList = append(pasturePushList, center3)
+	for _, center := range pasturePushList {
+		regionData := make([]map[string]interface{}, 0)
+		for _, region := range regionList {
+			if center["name"].(string) == region["center"].(string) {
+				regionData = append(regionData, region)
+			}
+		}
+		center["subDepts"] = regionData
+	}
+
+	dataByte, err := json.Marshal(pasturePushList)
+	if err != nil {
+		logs.Error(err)
+	}
+
+	url := "http://meadow.nandasoft-its.com:26101/vientiane/pushOrgStructure"
+	respByte, err := util.PostPush(url, dataByte)
+	if err != nil {
+		logs.Error(err)
+	}
+	fmt.Println(string(dataByte))
+
+	vientianeResp := new(liugong.VientianeResp)
+	err = json.Unmarshal(respByte, &vientianeResp)
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+
+	if vientianeResp.Code == 200 {
+		vientianeResp.Status = vientianeResp.Code
+	}
+
+	err = s.d.DB.Exec(` insert into vehiclelog(url,param,status,msgtext,resp)values(?,?,?,?,?) `, url, string(dataByte), vientianeResp.Status, vientianeResp.Msg, string(respByte)).Error
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+}
+
+func (s *Service) EditVehicle(vehicleList []*liugong.EditVehicleReq) []string {
+	var errors []string
+
+	for _, vehicle := range vehicleList {
+		err := s.d.DB.Debug().Exec(`  insert into vehicle(pastureId,pastureName,date,eqId,eqCode,hour,eqClass,eqName,
+                      license,specification,purpose,purchaseDate,entranceDate,leaveDate,duration,departmentId,departmentName,brand)
+ select e.pastureId,e.pastureName,?,e.id,e.eqCode,?,e.eqClassName,e.eqname,e.license,e.specification,e.purpose
+      ,e.purchaseDate,e.entranceDate,e.leaveDate,e.duration,e.departmentId,(select name from department  where id = e.departmentId ),e.brand
+ from equipment e where e.eqCode = ?
+  ON DUPLICATE KEY UPDATE hour = ?  `, vehicle.Date, vehicle.WorkHour,
+			vehicle.VehicleLicense, vehicle.WorkHour).Error
+		if err != nil {
+			logs.Error(err)
+			errors = append(errors, err.Error())
+		}
+	}
+
+	reqByte, _ := json.Marshal(vehicleList)
+	err := s.d.DB.Exec(` insert into vehiclelog(url,param,status,msgtext,resp)values(?,?,?,?,?) `,
+		"", string(reqByte), "", "", strings.Join(errors, ",")).Error
+	if err != nil {
+		logs.Error(err)
+	}
+
+	return errors
+}
+
+func (s *Service) GetVehicle(pastureId, startdate, enddate, eqCode, eqName, departmentId string, offset, pagecount int) (*liugong.GetVehicleResp, error) {
+	vehicleList := make([]*liugong.VehicleResp, 0)
+	resp := new(liugong.GetVehicleResp)
+	tx := s.d.DB.Table("vehicle")
+	if pastureId != "" {
+		tx.Where("pastureId = ? ", pastureId)
+	}
+	if startdate != "" {
+		tx.Where(" date between ? and ? ", startdate, enddate)
+	}
+	if eqCode != "" {
+		tx.Where(" eqCode like ?  ", "%"+eqCode+"%")
+	}
+	if eqName != "" {
+		tx.Where(" eqName like ? ", "%"+eqName+"%")
+	}
+	if departmentId != "" {
+		tx.Where(" departmentId  = ? ", departmentId)
+	}
+	err := tx.Order(" date desc ").Limit(pagecount).Offset(offset - 1).Find(&vehicleList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	tx1 := s.d.DB.Table("vehicle")
+	if pastureId != "" {
+		tx1.Where("pastureId = ? ", pastureId)
+	}
+	if startdate != "" {
+		tx1.Where(" date between ? and ? ", startdate, enddate)
+	}
+	if eqCode != "" {
+		tx1.Where(" eqCode like ?  ", "%"+eqCode+"%")
+	}
+	if eqName != "" {
+		tx1.Where(" eqName like ? ", "%"+eqName+"%")
+	}
+	if departmentId != "" {
+		tx1.Where(" departmentId  = ? ", departmentId)
+	}
+	var count int64
+	err = tx1.Count(&count).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	pastureList := make([]*model.Pasture, 0)
+	err = s.d.DB.Where("vendor = 1 ").Find(&pastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	for _, v := range vehicleList {
+		for _, pasture := range pastureList {
+			if v.PastureId == pasture.ID {
+				v.Region = pasture.Region
+				v.Center = pasture.Center
+				break
+			}
+		}
+	}
+
+	for _, v := range vehicleList {
+		purchaseDate, err := time.Parse("20060102", v.PurchaseDate)
+		if err == nil {
+			v.PurchaseDate = purchaseDate.Format("2006-01-02")
+		}
+		entranceDate, err := time.Parse("20060102", v.EntranceDate)
+		if err == nil {
+			v.EntranceDate = entranceDate.Format("2006-01-02")
+		}
+		leaveDate, err := time.Parse("2006-01-02", v.LeaveDate)
+		if err == nil {
+			v.LeaveDate = leaveDate.Format("2006-01-02")
+		}
+		date, err := time.Parse("2006-01-02", v.Date[:len("2006-01-02")])
+		if err == nil {
+			v.Date = date.Format("2006-01-02")
+		}
+	}
+
+	resp.VehicleList = vehicleList
+	resp.Offset = offset
+	resp.PageCount = pagecount
+	resp.Count = count
+	return resp, err
+}

+ 98 - 1
apiserver/service/material.go

@@ -3,6 +3,7 @@ package service
 import (
 	"encoding/json"
 	"fmt"
+	"github.com/astaxie/beego/logs"
 	"kpt.xdmy/apiserver/config"
 	"regexp"
 	"strconv"
@@ -424,6 +425,8 @@ func EquipmentExec(rows [][]string, pastureId int) error {
 		levelone := v[28]
 		leveltwo := v[30]
 		levelthree := v[32]
+		//license := v[34]
+		//duration := v[35]
 
 		brandInfo := model.Brand{}
 		if brand != "" {
@@ -466,7 +469,7 @@ func EquipmentExec(rows [][]string, pastureId int) error {
          brand = ?, brandId = ? ,proId= ?,proName= ? ,eqClassName = ?,eqClassId = (select id from eqclass where typeName = ?),eqName = ?,
          	maintenance= (select GROUP_CONCAT(id) from emp where  FIND_IN_SET(replace(empname,' ',''),replace(?,' ',''))     and pastureId = ? and enable = 1  ),levelone=(select id from emp where  replace(empname,' ','') =  replace(?,' ','')    and pastureId = ? and enable = 1 ) ,
 		leveltwo = (select id from emp where  replace(empname,' ','') =  replace(?,' ','')   and pastureId = ? and enable = 1 ),levelthree=(select id from emp where replace(empname,' ','')  =  replace(?,' ','')    and pastureId = ? and enable = 1 )
-		,leveloneTime = ? ,leveltwoTime = ?,levelthreeTime= ?  where financeCode = ? `,
+		,leveloneTime = ? ,leveltwoTime = ?,levelthreeTime= ? ,pushStatus = 2 where financeCode = ? `,
 			eqCode, eqCode, specification, purpose, depreciation, yuanzhi,
 			salvage, subtractvalue, upkeepgrade, yearUpkeepCost, yearMaintainCost, baseHours, employeName, pasture.ID, employeName, pasture.ID, inputUser, leaveDate,
 			brandInfo.BrandName, brandInfo.ID, provider.ID, provider.ProviderName, eqName, v[1], v[3], maintenance, pasture.ID, levelone, pasture.ID,
@@ -626,3 +629,97 @@ WHERE
 		}
 	}
 }
+
+func (s *Service) EditPartpurchase(reqList []*model.EditPartpurchaseReq) error {
+	tx := s.d.DB.Begin()
+	var bigId, employeId int64
+	idList := []int64{}
+
+	for _, req := range reqList {
+		bigId = req.BigId
+		break
+	}
+	var total int64
+	s.d.DB.Debug().Model(&model.BigPartPurchase{}).Where("id = ? ", bigId).Where("statue >= 3 ").Count(&total)
+	if total > 0 {
+		return errors.New("单号已合单,请返回开始页面重新申购!")
+	}
+
+	for _, req := range reqList {
+		var partPurchaseCount int64
+		err := tx.Model(&model.PartPurchase{}).Where(" reject = 0 ").Where(" bigId = ? ", req.BigId).Where("partCode = ? ", req.PartCode).Where(" contractId = ? ", req.ContractId).Count(&partPurchaseCount).Error
+		if err != nil {
+			tx.Rollback()
+			logs.Error("EditPartpurchase-0:" + err.Error())
+			return err
+		}
+		if partPurchaseCount > 0 {
+			return errors.New(fmt.Sprintf("该单号中已存在相同配件%s %s,请调整后重新保存", req.PartCode, req.PartName))
+		}
+	}
+
+	//appG.Response(http.StatusOK, e.ERROR, )
+	for _, req := range reqList {
+		//bigId = req.BigId
+		employeId = req.EmployeId
+		if req.Id == 0 {
+			if req.Reject == "" {
+				req.Reject = "0"
+			}
+			part := &model.PartPurchase{
+				BigId:                req.BigId,
+				PartId:               req.PartId,
+				PartName:             req.PartName,
+				PartCode:             req.PartCode,
+				Amount:               req.Amount,
+				Specification:        req.Specification,
+				Purpose:              req.Purpose,
+				Unit:                 req.Unit,
+				BrandId:              req.BrandId,
+				StorageAmount:        req.StorageAmount,
+				Price:                req.Price,
+				ContractId:           req.ContractId,
+				LifeCycle:            req.LifeCycle,
+				ContractVarianceItem: req.ContractVarianceItem,
+				Reject:               req.Reject,
+				DepartmentId:         req.DepartmentId,
+				Explain:              req.Explain,
+				EmployeId:            req.EmployeId,
+				Date:                 time.Now().Format("2006-01-02 15:04:05"),
+			}
+			resp := tx.Debug().Create(&part)
+			if resp.Error != nil {
+				tx.Rollback()
+				logs.Error("EditPartpurchase-0:" + resp.Error.Error())
+				return resp.Error
+			}
+			idList = append(idList, part.Id)
+		} else {
+			err := tx.Exec(` update partpurchase set  reject = 0 ,amount = ? ,purpose = ?,bigId = ?,date = now() where id = ? `, req.Amount, req.Purpose, req.BigId, req.Id).Error
+			if err != nil {
+				tx.Rollback()
+				logs.Error("EditPartpurchase-1:" + err.Error())
+				return err
+			}
+			idList = append(idList, req.Id)
+		}
+	}
+	if bigId > 0 {
+		err := tx.Debug().Exec(` delete from partpurchase  where id in((select pl.id from  partpurchase pl 	 
+     join bigpartpurchase  bpp on bpp.id = pl.bigId  where   bpp.purchase_type = (select purchase_type from bigpartpurchase  where id = ? )  
+     and pl.reject = 1  and pl.id not in(?)))  and  employeId = ?  `, bigId, idList, employeId).Error
+		if err != nil {
+			tx.Rollback()
+			logs.Error("EditPartpurchase-2:" + err.Error())
+			return err
+		}
+	}
+
+	err := tx.Commit().Error
+	if err != nil {
+		tx.Rollback()
+		logs.Error("EditPartpurchase-3:" + err.Error())
+		return err
+	}
+	return nil
+}

+ 4 - 3
apiserver/service/order.go

@@ -207,7 +207,7 @@ func SapOrder(p *model.BigBuyDetail, dflag string, purchaseType modernPb.Purchas
 			detail.Unit = par.Unit
 			detail.MaterialCode = v.PartCode
 		}
-		if purchaseType.Number() > 0 {
+		if purchaseType.Number() > 0 && purchaseType.Number() != 4 {
 			detail.IsFree = "X"
 		}
 
@@ -395,8 +395,6 @@ func SrmOrder(p *model.BigBuyDetail, IsReturn string) {
 			detail.PricingUnitCode = par.Unit
 		}
 		s.d.DB.First(pr, model.PartRepertory{ContractID: v.ContractID})
-		r.Data.TotalNonTaxAmount += price
-		r.Data.TotalTaxAmount += price
 		detail.RowNo = strconv.Itoa(v.RowNumber)
 		//detail.Manufacturer = pa.FactoryCode
 		//detail.Manufacturer =
@@ -457,6 +455,9 @@ func SrmOrder(p *model.BigBuyDetail, IsReturn string) {
 		detail.TaxAmount = detail.NonTaxPrice
 		detail.TaxPrice = detail.NonTaxPrice
 		detail.NonTaxAmount = detail.NonTaxPrice
+
+		r.Data.TotalNonTaxAmount += price * float64(v.Amount)
+		r.Data.TotalTaxAmount += price * float64(v.Amount)
 		r.Data.Detail = append(r.Data.Detail, detail)
 		//if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil {
 		//	log.Errorln(e, v.ID)

+ 44 - 4
apiserver/service/proof.go

@@ -8,6 +8,7 @@ import (
 	"github.com/xormplus/xorm/schemas"
 	"kpt.xdmy/apiserver/config"
 	"reflect"
+	"regexp"
 	"strconv"
 	"strings"
 	"time"
@@ -202,9 +203,11 @@ func (s *Service) LaidProof(p interface{}, tx *sqlx.Tx) error {
 			log.Printf("laid proof success:%s,%s", rp.Data.EqNumber, rp.Data.SapNumber)
 			tx.Exec(`  update bigpartlaid set  ProofCode = ?  where laidcode = ?  `, rp.Data.SapNumber, rp.Data.EqNumber)
 		} else {
-			log.Warnf("%s laid proof failed:causetext=%s", rp.Dest.MessText)
+			log.Warnf("%s laid proof failed:causetext=%s", rp.Dest.MessText, rp.Dest.MessText)
 			pp.Print(r)
-			fmt.Println(e)
+			if strings.Index(rp.Dest.MessText, "采购信息记录") > -1 {
+				return errors.New("SAP中没有相应的合同\n解决方案:合同管理页面备件明细最左侧勾选没有合同的备件,点击SAP上传按钮。十分钟后再次进行入库操作。")
+			}
 			return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
 		}
 	}
@@ -368,7 +371,7 @@ func (s *Service) UseProof(p interface{}, tx *sqlx.Tx) error {
 		// 领用出库、手动出库
 		//if pr.UseType == 0 || pr.UseType == 1 {
 		sdetail.MoveType = "201"
-		sdetail.CostCenter = dp.CostCenterCode
+
 		//if dp.Factory == "" {
 		sdetail.Factory = pa.FactoryCode
 		//} else {
@@ -379,6 +382,8 @@ func (s *Service) UseProof(p interface{}, tx *sqlx.Tx) error {
 		if pr.UseType == 6 {
 			sdetail.MoveType = "Z69"
 			sdetail.AUFNR = pr.GreenFodderNumber
+		} else {
+			sdetail.CostCenter = dp.CostCenterCode
 		}
 
 		if sdetail.Factory == "M005" && strings.Contains(dp.Name, "二期") {
@@ -430,6 +435,19 @@ func (s *Service) UseProof(p interface{}, tx *sqlx.Tx) error {
 			tx.Exec(`  update bigpartuse set  ProofCode = ?  where useform = ?  `, rp.Data.SapNumber, rp.Data.EqNumber)
 		} else {
 			log.Warnf(" use proof :%s", rp.Dest.MessText)
+			fmt.Println(strings.Index(rp.Dest.MessText, "短缺"))
+			if strings.Index(rp.Dest.MessText, "短缺") > -1 {
+				messText, err := extractCode(rp.Dest.MessText)
+				if err != nil {
+					return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
+				}
+				return errors.New(fmt.Sprintf("SAP库存不足 %s "+
+					"\n解决方案:在SAP系统中查询MB51,核对该备件库存。", strings.Join(messText, ",")))
+			}
+			if strings.Index(rp.Dest.MessText, "管道") > -1 {
+				return errors.New("SAP中没有相应的合同\n解决方案:合同管理页面备件明细最左侧勾选没有合同的备件,点击SAP上传按钮。十分钟后再次进行入库操作。")
+			}
+
 			return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
 		}
 	}
@@ -598,7 +616,7 @@ func (s *Service) QuitProof(p interface{}, tx *sqlx.Tx) error {
 			//}
 			tx.Exec(`  update bigpartquit set  ProofCode = ?  where useform = ?  `, rp.Data.SapNumber, rp.Data.EqNumber)
 		} else {
-			log.Warnf("%s quit proof failed:causetext=%s", rp.Dest.MessText)
+			log.Warnf("%s quit proof failed:causetext=%s", rp.Dest.MessText, rp.Dest.MessText)
 			pp.Print(r)
 			return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
 		}
@@ -792,6 +810,9 @@ func (s *Service) RefundProof(p interface{}, tx *sqlx.Tx) error {
 			tx.Exec(`  update bigpartrefund set  ProofCode = ?  where useform = ?  `, rp.Data.SapNumber, rp.Data.EqNumber)
 		} else {
 			log.Warnf("return good fail: %s", rp.Dest.MessText)
+			if strings.Index(rp.Dest.MessText, "不正确的移动类型") > -1 {
+				return errors.New("寄售件退货订单中含有自购件\n解决方案:检查退货订单中的备件属性。自购件先做退货采购订单,再做备件退货,类型选择自购件。寄售件直接做备件退货,类型选择寄售件。")
+			}
 			return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
 		}
 	}
@@ -953,3 +974,22 @@ func reflect2object(rawValue *reflect.Value) (value interface{}, err error) {
 	}
 	return
 }
+
+func extractCode(input string) ([]string, error) {
+	re := regexp.MustCompile(`\d{2}\.\d{2}\.\d{2}\.\d{2}\.\d{6}`)
+	matches := re.FindAllString(input, -1)
+
+	if matches == nil {
+		return nil, fmt.Errorf("No matches found")
+	}
+	return matches, nil
+}
+
+func (s *Service) GetEnsiling(pastureId string) ([]*model.Ensiling, error) {
+	ensilingList := make([]*model.Ensiling, 0)
+	err := s.d.DB.Where("pastureId = ? ", pastureId).Find(&ensilingList).Error
+	if err != nil {
+		return ensilingList, err
+	}
+	return ensilingList, nil
+}

+ 32 - 1
apiserver/service/purchase.go

@@ -14,6 +14,28 @@ import (
 // CreateSpecialtyPurchase 创建特殊申购信息
 func CreateSpecialtyPurchase(ctx context.Context, req *modernPb.SparePartsRequisitionsRequest) error {
 	var bigPartPurchaseId int64 = 0
+
+	if req.PurchaseType == 1 {
+		sql := `SELECT
+		count(1) count
+	FROM
+		bigpartpurchase bp
+		JOIN pasture p
+		on p.id = bp.pastureId
+	WHERE
+		bp.pastureId = ?
+		AND bp.statue < 3 and bp.purchase_type = 1 and createTime >'2024-03-18'
+	and ( select name from department  where id = bp.departmentId) != '挤奶处' order by   bp.id desc   limit 1 `
+		var total int64
+		s.d.DB.Raw(sql, req.PastureId).Count(&total)
+		if total > 0 {
+			return errors.New("单号已生成,请返回开始页面重新申购!")
+		}
+
+		s.d.DB.Exec(` delete from partpurchase p  where (select pastureId from department where id = p.departmentId ) = ?   and reject = 1 and employeId = ? 
+                               and (select purchase_type from bigpartpurchase  where id = p.bigId )  = 1 `, req.DepartmentId, req.EmployeId)
+
+	}
 	// 赠品
 	defer func() {
 		if req.PurchaseType == modernPb.PurchaseType_Complimentary_Item {
@@ -35,12 +57,21 @@ func CreateSpecialtyPurchase(ctx context.Context, req *modernPb.SparePartsRequis
 		}
 
 		partPurchaseList := make([]*model.PartPurchase, 0)
+		//for _, v := range req.SpotList {
+		//	amount, _ := strconv.Atoi(v.Amount)
+		//	partPurchaseList = append(partPurchaseList, model.NewPartPurchase(
+		//		newBigPartPurchase.Id, int64(req.PastureId), v.PartId, int64(v.BrandId), int64(amount),
+		//		v.ContractId, v.PartCode, v.PartName, v.Specification, v.Unit, v.Purpose, v.Price,
+		//		float64(v.StorageAmount)))
+		//}
+
 		for _, v := range req.SpotList {
 			amount, _ := strconv.Atoi(v.Amount)
+			emp, _ := strconv.ParseInt(v.EmployeId, 10, 64)
 			partPurchaseList = append(partPurchaseList, model.NewPartPurchase(
 				newBigPartPurchase.Id, int64(req.PastureId), v.PartId, int64(v.BrandId), int64(amount),
 				v.ContractId, v.PartCode, v.PartName, v.Specification, v.Unit, v.Purpose, v.Price,
-				float64(v.StorageAmount)))
+				float64(v.StorageAmount), v.DepartmentId, v.Date, emp))
 		}
 
 		if len(partPurchaseList) > 0 {

+ 122 - 16
apiserver/service/report.go

@@ -40,10 +40,10 @@ func MaintainList(pastureName, eqClassIdStr string, startTime, endTime time.Time
 
 	for _, eq := range eqList {
 		pastureMaintainList := make([]*model.Maintain, 0)
-		err := s.d.DB.Raw(` 	SELECT m.* FROM maintain m JOIN equipment e on e.id = m.eqId WHERE e.eqClassId = ? 
+		err := s.d.DB.Raw(` 	SELECT m.* FROM maintain m JOIN equipment e on e.id = m.eqId WHERE (e.eqClassId = ? or   ? = '')
  and m.stopTime is not null and (m.pastureid = (select id from pasture where name = ? and name != '现代牧业') or ? = '现代牧业' ) 
   and m.stopTime between ? and ? 	and TIMESTAMPDIFF(hour, m.orderTime, m.stopTime) < 1000 order by requestTime,m.pastureid  `,
-			eq.EqClass.ID, eq.Pasture.Name, eq.Pasture.Name, startTime, endTime).Find(&pastureMaintainList).Error
+			eq.EqClass.ID, eq.EqClass.ID, eq.Pasture.Name, eq.Pasture.Name, startTime, endTime).Find(&pastureMaintainList).Error
 		if err != nil {
 			return 0, nil, errors.New(fmt.Sprintf("查看维修信息出错 error:%s", err.Error()))
 		}
@@ -397,7 +397,7 @@ func MaintainListPid(pastureName, eqClassId string, startTime, endTime time.Time
 		eqClassList1 = append(eqClassList1, &model.EqClass{ID: n})
 	}
 	pastureList := make([]*model.Pasture, 0)
-	err := s.d.DB.Select("id,name").Where(" name = ? or ? = '' or ?= '现代牧业' ", pastureName, pastureName, pastureName).Where("id != 18").Order("id").Find(&pastureList).Error
+	err := s.d.DB.Select("id,name,center").Where(" name = ? or ? = '' or ?= '现代牧业' ", pastureName, pastureName, pastureName).Where("id != 18").Order("center_sort,id").Find(&pastureList).Error
 	if err != nil {
 		return 0, nil, errors.New("查询牧场信息出错!!!")
 	}
@@ -406,6 +406,9 @@ func MaintainListPid(pastureName, eqClassId string, startTime, endTime time.Time
 	pastureCount := len(pastureList)
 
 	n := 0
+
+	var jtCount, jtAllCount, jtT2, jtT3 float64
+	centerMap := make(map[string][]map[string]float64, 0)
 	for i, eq1 := range eqClassList1 {
 		if len(respMap) >= pagecount {
 			continue
@@ -520,20 +523,71 @@ func MaintainListPid(pastureName, eqClassId string, startTime, endTime time.Time
 					eqClassMap[pastureId]["count"] += count
 					eqClassMap[pastureId]["t2"] += t2
 					eqClassMap[pastureId]["t3"] += t3
-					//data["mtbf"] = FloatRound(allCount/count, 2)
-					//data["mttr"] = FloatRound((t2+t3)/count, 2)
-					//data["mttf"] = FloatRound((allCount-t2-t3)/count, 2)
-					//data["count"] = count
-					//pasture := model.Pasture{}
-					//err := s.d.DB.Where("id = ? ", pastureId).First(&pasture).Error
-					//if err != nil {
-					//	return nil, errors.New("查询牧场信息出错!!!")
-					//}
-					//data["pastureName"] = pasture.Name
-					//data["eqClassName"] = eqClass.TypeName
-					//respMap = append(respMap, data)
 				}
 			}
+			//jtData := make(map[string]interface{})
+			//centerMap := make([]map[string]interface{}, 0)
+
+			if offset == 1 {
+				if pastureName == "现代牧业" || pastureName == "" {
+					for _, item := range pastureList {
+						if item.ID == 18 {
+							continue
+						}
+						pastureId := strconv.Itoa(item.ID)
+						jtAllCount += eqClassMap[pastureId]["allCount"]
+						jtCount += eqClassMap[pastureId]["count"]
+						fmt.Println(eqClassMap[pastureId]["count"])
+						jtT2 += eqClassMap[pastureId]["t2"]
+						jtT3 += eqClassMap[pastureId]["t3"]
+					}
+
+					centerList := []string{"一中心", "二中心", "三中心"}
+					for _, centerName := range centerList {
+						var allCount, count, t2, t3 float64
+						data := make(map[string]float64)
+						for _, item := range pastureList {
+							if item.ID == 18 {
+								continue
+							}
+							if centerName == item.Center {
+								pastureId := strconv.Itoa(item.ID)
+								allCount += eqClassMap[pastureId]["allCount"]
+								count += eqClassMap[pastureId]["count"]
+								t2 += eqClassMap[pastureId]["t2"]
+								t3 += eqClassMap[pastureId]["t3"]
+							}
+						}
+						data["allCount"] += allCount
+						data["count"] += count
+						data["t2"] += t2
+						data["t3"] += t2
+
+						//if allCount > 0 && count > 0 && t2 > 0 && t3 > 0 {
+						//if allCount != 0 && count != 0 {
+						//	data["mtbf"] = FloatRound(allCount/count, 2)
+						//} else {
+						//	data["mtbf"] = 0
+						//}
+						//if (t2 != 0 || t3 != 0) && count != 0 {
+						//	data["mttr"] = FloatRound((t2+t3)/count, 2)
+						//} else {
+						//	data["mttr"] = 0
+						//}
+						//if allCount != 0 && count != 0 {
+						//	data["mttf"] = FloatRound((allCount-t2-t3)/count, 2)
+						//} else {
+						//	data["mttf"] = 0
+						//}
+						//data["count"] = count
+						centerMap[centerName] = append(centerMap[centerName], data)
+						//}
+						//data["pastureName"] = centerName
+						//respMap = append(respMap, data)
+					}
+				}
+			}
+
 			for n, item := range pastureList {
 				if len(respMap) >= pagecount {
 					break
@@ -550,12 +604,64 @@ func MaintainListPid(pastureName, eqClassId string, startTime, endTime time.Time
 						data["mttf"] = FloatRound((eqClassMap[pastureId]["allCount"]-eqClassMap[pastureId]["t2"]-eqClassMap[pastureId]["t3"])/eqClassMap[pastureId]["count"], 2)
 					}
 					data["count"] = eqClassMap[pastureId]["count"]
+					fmt.Println(eqClassMap[pastureId]["count"])
 					respMap = append(respMap, data)
 				}
 			}
 		}
 	}
-	return pastureCount * len(eqClassList1), respMap, nil
+
+	respMap1 := make([]map[string]interface{}, 0)
+	data := make(map[string]interface{})
+	if jtAllCount != 0 && jtCount != 0 {
+		data["mtbf"] = FloatRound(jtAllCount/jtCount, 2)
+	} else {
+		data["mtbf"] = 0
+	}
+	if (jtT3 != 0 || jtT2 != 0) && jtCount != 0 {
+		data["mttr"] = FloatRound((jtT2+jtT3)/jtCount, 2)
+	} else {
+		data["mttr"] = 0
+	}
+	if jtCount != 0 && jtAllCount != 0 {
+		data["mttf"] = FloatRound((jtAllCount-jtT2-jtT3)/jtCount, 2)
+	} else {
+		data["mttf"] = 0
+	}
+	data["count"] = jtCount
+	data["pastureName"] = "现代牧业"
+	respMap1 = append(respMap1, data)
+
+	for name, centerList := range centerMap {
+		data := make(map[string]interface{})
+		var allCount, count, t3, t2 float64
+		for _, center := range centerList {
+			allCount += center["allCount"]
+			count += center["count"]
+			t2 += center["t2"]
+			t3 += center["t3"]
+		}
+		if allCount != 0 && count != 0 {
+			data["mtbf"] = FloatRound(allCount/count, 2)
+		} else {
+			data["mtbf"] = 0
+		}
+		if (t2 != 0 || t3 != 0) && count != 0 {
+			data["mttr"] = FloatRound((t2+t3)/count, 2)
+		} else {
+			data["mttr"] = 0
+		}
+		if allCount != 0 && count != 0 {
+			data["mttf"] = FloatRound((allCount-t2-t3)/count, 2)
+		} else {
+			data["mttf"] = 0
+		}
+		data["count"] = count
+		data["pastureName"] = name
+		respMap1 = append(respMap1, data)
+	}
+	respMap1 = append(respMap1, respMap...)
+	return pastureCount*len(eqClassList1) + 3, respMap1, nil
 }
 
 func MaintainListEquipment(pastureName, eqClassId string, startTime, endTime time.Time, offset, pageSize int, eqName string) (int64, []map[string]interface{}, error) {

+ 0 - 1
apiserver/service/sap.go

@@ -132,7 +132,6 @@ func (s *Service) SyncSap(r http.SapDest, rp interface{}, data interface{}) (err
 	if err = s.http.Do(req, &rp); err != nil {
 		err = errors.Wrapf(err, "SyncSap")
 	}
-
 	//if r.GetUrl() != config.Conf.Http.Routing+"/SRM/MM018/PurchaseInfo" {
 	s.AddSapApiLog(r, rp, data, err)
 	//}

+ 2 - 0
apiserver/service/service.go

@@ -21,6 +21,7 @@ type Service struct {
 	d         *dao.Dao
 	http      *http.Client
 	sqlserver *dao.SqlServer
+	Conf      *http.Client
 }
 
 func New(conf *config.Config) *Service {
@@ -34,6 +35,7 @@ func New(conf *config.Config) *Service {
 		d:         d,
 		http:      c,
 		sqlserver: sqlserver,
+		Conf:      c,
 	}
 	return s
 }

+ 229 - 0
apiserver/service/stock.go

@@ -1 +1,230 @@
 package service
+
+import (
+	"github.com/360EntSecGroup-Skylar/excelize"
+	"github.com/astaxie/beego/logs"
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model"
+	"strings"
+	"time"
+)
+
+func (s *Service) GetStockList(req *model.GetStockListReq) (*model.GetStockListResp, error) {
+	resp := new(model.GetStockListResp)
+	tx := s.d.DB.Table("stock")
+	tx.Joins("JOIN pasture ON pasture.id = stock.pastureId")
+	tx.Joins("JOIN department ON department.id = stock.departmentId")
+	tx.Joins("JOIN equipment ON equipment.id = stock.eqId")
+	tx.Joins(" left JOIN emp ON emp.id = stock.checkTaker")
+
+	tx.Select("stock.id, stock.pastureId, stock.departmentId, stock.eqId, date_format(stock.rzdate ,'%Y-%m-%d') rzdate , stock.unit, " +
+		"stock.specification, stock.quantity, stock.yuanzhi, stock.count, stock.profit, stock.tag, " +
+		"date_format(stock.importdate ,'%Y-%m-%d %H:%i:%s')  importdate, date_format(stock.inventorydate ,'%Y-%m-%d %H:%i:%s') inventorydate, stock.checktaker, stock.remark,pasture.name,department.name departmentName ," +
+		"equipment.eqCode,equipment.eqName,equipment.assetCode,emp.empname empname")
+
+	if req.PastureId != "" && req.PastureId != "18" {
+		tx.Where(" stock.pastureId = ? ", req.PastureId)
+	}
+	if req.DepartmentId != "" {
+		tx.Where(" stock.departmentId = ? ", req.DepartmentId)
+	}
+	if req.StartDate != "" {
+		tx.Where(" stock.inventorydate between ? and ?  ", req.StartDate, req.EndDate)
+	}
+
+	stockAndPastureList := make([]*model.StockAndPasture, 0)
+	//tx.Limit(req.PageCount).Offset(req.Offset)
+	err := tx.Debug().Order(" importdate desc,id asc  ").Limit(req.Pagecount).Offset(req.Offset * 10).Find(&stockAndPastureList).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	tx1 := s.d.DB.Table("stock")
+	tx1.Joins("JOIN pasture ON pasture.id = stock.pastureId")
+	tx1.Joins("JOIN department ON department.id = stock.departmentId")
+	tx1.Joins("JOIN equipment ON equipment.id = stock.eqId")
+	tx1.Joins(" left JOIN emp ON emp.id = stock.checkTaker")
+	tx1.Select("stock.id, stock.pastureId, stock.departmentId, stock.eqId, date_format(stock.rzdate ,'%Y-%m-%d') rzdate , stock.unit, " +
+		"stock.specification, stock.quantity, stock.yuanzhi, stock.count, stock.profit, stock.tag, " +
+		"date_format(stock.importdate ,'%Y-%m-%d %H:%i:%s')  importdate, date_format(stock.inventorydate ,'%Y-%m-%d %H:%i:%s') inventorydate, stock.checktaker, stock.remark,pasture.name,department.name departmentName ," +
+		"equipment.eqCode,equipment.eqName,equipment.assetCode,emp.empname empname")
+
+	if req.PastureId != "" && req.PastureId != "18" {
+		tx1.Where(" stock.pastureId = ? ", req.PastureId)
+	}
+	if req.DepartmentId != "" {
+		tx1.Where(" stock.departmentId = ? ", req.DepartmentId)
+	}
+	if req.StartDate != "" {
+		tx1.Where(" stock.inventorydate between ? and ?  ", req.StartDate, req.EndDate)
+	}
+
+	var count int64
+	err = tx1.Count(&count).Error
+	if err != nil {
+		logs.Error(err)
+		return resp, err
+	}
+
+	stockList := make([]*model.StockInfo, 0)
+	for _, item := range stockAndPastureList {
+		s := new(model.StockInfo)
+		s.ID = item.Stock.ID
+		s.PastureId = item.Stock.PastureId
+		s.PastureName = item.Pasture.Name
+		s.DepartmentId = item.Stock.DepartmentId
+		s.DepartmentName = item.DepartmentName
+		s.EqId = item.EqId
+		s.EqCode = item.EqCode
+		s.EqName = item.EqName
+		s.AssetCode = item.AssetCode
+		s.RzDate = item.RzDate
+		s.Unit = item.Stock.Unit
+		s.Specification = item.Stock.Specification
+		s.Quantity = item.Stock.Quantity
+		s.Yuanzhi = item.Stock.Yuanzhi
+		s.Count = item.Count
+		s.Profit = item.Profit
+		s.Tag = item.Tag
+		s.ImportDate = item.ImportDate
+		s.InventoryDate = item.InventoryDate
+		s.CheckTaker = item.CheckTaker
+		s.CheckTakerName = item.Empname
+		s.Remark = item.Stock.Remark
+		if item.CheckTaker != "" {
+			s.Status = 1
+		}
+		stockList = append(stockList, s)
+	}
+	resp.StockList = stockList
+	resp.Count = count
+	return resp, nil
+}
+
+func (s *Service) StockExcel(c *gin.Context) map[string]interface{} {
+
+	if err := c.Request.ParseForm(); err != nil {
+		return nil
+	}
+
+	fileHeader, err := c.FormFile("file")
+	file, err := fileHeader.Open()
+	if err != nil {
+		return nil
+	}
+
+	xlsx1, err := excelize.OpenReader(file)
+
+	if err != nil {
+		return nil
+	}
+
+	rows := xlsx1.GetRows("资产盘点模板")
+	if len(rows) > 10000 {
+		rows = rows[:10000]
+	}
+	paramslist := []string{"牧场", "部门", "资产编号", "资产名称", "设备内部编号", "实物入账日期", "计量单位", "规格",
+		"资产数量", "资产原值", "实际盘点数", "盈亏量", "有无标签", "备注"}
+
+	ok := 0
+	error := 0
+	queryData := make([]interface{}, 0)
+	createdate := time.Now().Format("2006-01-02 15:04:05")
+	for i, row := range rows {
+		if i > 0 {
+			//s_params := make([]interface{}, 0)
+			//entry := make(map[string]string)
+			outentry := make(map[string]string)
+
+			for _, value := range paramslist {
+
+				for j, colCell := range rows[0] {
+					if strings.Trim(value, " ") == colCell {
+						for k, colCell1 := range row {
+							if j == k {
+								outentry[colCell] = colCell1
+								//entry[colCell] = colCell1
+								//inputdata = inputdata + colCell + ":" + colCell1 + ";"
+							}
+						}
+					}
+				}
+			}
+
+			sw, err := time.Parse("2006-01-02", outentry["实物入账日期"])
+			if err != nil {
+				logs.Error(err)
+				outentry["error_msg"] = err.Error()
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+
+			pasture := new(model.Pasture)
+			s.d.DB.Table("pasture").Where("name = ?", outentry["牧场"]).First(&pasture)
+			if pasture.ID == 0 {
+				outentry["error_msg"] = "牧场不存在!"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+			department := new(model.Department)
+			s.d.DB.Table("department").Where("name = ?", outentry["部门"]).Where("pastureId = ? ", pasture.ID).First(&department)
+			if department.ID == 0 {
+				outentry["error_msg"] = "部门不存在!"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+			equipment := new(model.Equipment)
+			s.d.DB.Table("equipment").Where("eqCode = ? ", outentry["设备内部编号"]).First(&equipment)
+			if department.ID == 0 {
+				outentry["error_msg"] = "资产不存在!"
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+
+			//paramslist := []string{"牧场", "部门", "资产编号", "资产名称", "设备内部编号", "实物入账日期", "计量单位", "规格",
+			//	"资产数量", "资产原值", "实际盘点数", "盈亏量", "有无标签", "备注"}
+			err = s.d.DB.Debug().Omit("inventorydate,checktaker").Create(&model.Stock{PastureId: pasture.ID,
+				DepartmentId:  department.ID,
+				EqId:          equipment.Id,
+				RzDate:        sw.Format("2006-01-02"),
+				Unit:          outentry["计量单位"],
+				Specification: outentry["规格"],
+				Quantity:      outentry["资产数量"],
+				Yuanzhi:       outentry["资产原值"],
+				Count:         outentry["实际盘点数"],
+				Profit:        outentry["盈亏量"],
+				Tag:           outentry["有无标签"],
+				ImportDate:    createdate,
+				Remark:        outentry["备注"],
+				CreateDate:    time.Now().Format("2006-01-02")}).Error
+
+			if err != nil {
+				logs.Error(err)
+				outentry["error_msg"] = err.Error()
+				error++
+				queryData = append(queryData, outentry)
+				continue
+			}
+		}
+	}
+
+	data := make(map[string]interface{})
+	data["result"] = queryData
+	data["success"] = ok
+	data["err_count"] = error
+	return data
+}
+
+func (s *Service) DelStockList(idList []string) error {
+	err := s.d.DB.Debug().Exec(`delete from stock  where id in(?) `, idList).Error
+	if err != nil {
+		logs.Error(err)
+		return err
+	}
+	return nil
+}

BIN
cmd/sh/eqserver


BIN
dist.zip


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/datas/myMap.json


BIN
dist/favicon.ico


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/index.html


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/css/app.a70a2a2f.css


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/css/chunk-elementUI.45ab9bc1.css


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/css/chunk-libs.2e418612.css


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


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


BIN
dist/static/img/1.1ddf085a.png


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


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


BIN
dist/static/img/cow.3495de2a.jpg


BIN
dist/static/img/login-bg.dfe7c90f.jpg


BIN
dist/static/img/login-bg1.1f1602f0.jpg


BIN
dist/static/img/login-bujian.8695940d.png


BIN
dist/static/img/logo.4a74cb8a.png


BIN
dist/static/img/logo1.d2343c0f.png


BIN
dist/static/img/logo_u3.34a9ffae.png


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/app.6e59e529.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/chunk-39889fb2.0f71ae7a.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/chunk-581b2547.c1efae40.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/chunk-d17f893e.56c4d12d.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/chunk-elementUI.1e8908f6.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
dist/static/js/chunk-libs.f5a7c3c5.js


+ 2 - 1
go.mod

@@ -9,11 +9,12 @@ replace (
 )
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20230911015439-26760b6ed829
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20240307085554-b5a26a4c8f7d
 	gitee.com/xuyiping_admin/pkg v0.0.0-20230816061144-c1f079802584
 	github.com/360EntSecGroup-Skylar/excelize v1.4.1
 	github.com/Anderson-Lu/gofasion v0.0.0-20190530065914-6a05b679ee48
 	github.com/BurntSushi/toml v1.2.1
+	github.com/EDDYCJY/fake-useragent v0.2.0 // indirect
 	github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
 	github.com/astaxie/beego v1.12.3
 	github.com/axetroy/go-fs v1.0.0

+ 6 - 0
go.sum

@@ -724,6 +724,8 @@ git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3p
 gitee.com/xuyiping_admin/go_proto v0.0.0-20230802054950-77dee3d12065/go.mod h1:cxbPefIf1o+cyQwvFaM3ndaoUeaK5aWzPV/eZQGJPgE=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20230911015439-26760b6ed829 h1:PSGdFkvEgiVn6CYvEwYm0PBbORAOhqKoOL7LzxZf5zY=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20230911015439-26760b6ed829/go.mod h1:x47UOU+lOkZnrtAENAsOGd7mZ5I8D2JRkMKMqLLRlVw=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240307085554-b5a26a4c8f7d h1:HG8wxR8/FUhYEStFIXuehCNCOExqjlHANuWDpt57CLA=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240307085554-b5a26a4c8f7d/go.mod h1:x47UOU+lOkZnrtAENAsOGd7mZ5I8D2JRkMKMqLLRlVw=
 gitee.com/xuyiping_admin/pkg v0.0.0-20230816061144-c1f079802584 h1:5RE5yrMMvnDITrnoX821mFl7dNYfsFA1osDobUV/TDo=
 gitee.com/xuyiping_admin/pkg v0.0.0-20230816061144-c1f079802584/go.mod h1:VQ7WztVDQRlXE1dUu/Yqo3ZdhKsfv7IGJtV+vqNqJVw=
 github.com/360EntSecGroup-Skylar/excelize v1.4.1 h1:l55mJb6rkkaUzOpSsgEeKYtS6/0gHwBYyfo5Jcjv/Ks=
@@ -741,6 +743,8 @@ github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi
 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
 github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno=
 github.com/CloudyKit/jet/v6 v6.2.0/go.mod h1:d3ypHeIRNo2+XyqnGA8s+aphtcVpjP5hPwP/Lzo7Ro4=
+github.com/EDDYCJY/fake-useragent v0.2.0 h1:Jcnkk2bgXmDpX0z+ELlUErTkoLb/mxFBNd2YdcpvJBs=
+github.com/EDDYCJY/fake-useragent v0.2.0/go.mod h1:5wn3zzlDxhKW6NYknushqinPcAqZcAPHy8lLczCdJdc=
 github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk=
 github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
 github.com/Joker/jade v1.1.3/go.mod h1:T+2WLyt7VH6Lp0TRxQrUYEs64nRc83wkMQrfeIQKduM=
@@ -750,6 +754,7 @@ github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go
 github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
 github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
 github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
+github.com/PuerkitoBio/goquery v1.5.1 h1:PSPBGne8NIUWw+/7vFBV+kG2J/5MOjbzc7154OaKCSE=
 github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
 github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
 github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
@@ -774,6 +779,7 @@ github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+Dx
 github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
 github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
 github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
+github.com/andybalholm/cascadia v1.2.0 h1:vuRCkM5Ozh/BfmsaTm26kbjm0mIOM3yS5Ek/F5h18aE=
 github.com/andybalholm/cascadia v1.2.0/go.mod h1:YCyR8vOZT9aZ1CHEd8ap0gMVm2aFgxBp0T0eFw1RUQY=
 github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
 github.com/apache/arrow/go/v10 v10.0.1/go.mod h1:YvhnlEePVnBS4+0z3fhPfUy7W1Ikj0Ih0vcRo/gZ1M0=

+ 167 - 37
middleware/jwt/jwt.go

@@ -1,55 +1,185 @@
+//package jwt
+//
+//import (
+//	//"strings"
+//
+//	"github.com/dgrijalva/jwt-go"
+//	"github.com/gin-gonic/gin"
+//	"kpt.xdmy/pkg/e"
+//	"kpt.xdmy/pkg/util"
+//	jwtGet "kpt.xdmy/pkg/util"
+//)
+//
+//func JWT() gin.HandlerFunc {
+//	return func(c *gin.Context) {
+//		var code int
+//		var data interface{}
+//
+//		code = e.SUCCESS
+//		//Authorization := c.GetHeader("Authorization")
+//		//token := strings.Split(Authorization, " ")
+//		Authorization := c.GetHeader("token")
+//		token := Authorization
+//		if Authorization == "" {
+//			code = e.INVALID_PARAMS
+//		} else {
+//			//_, err := util.ParseToken(token[1])
+//			_, err := util.ParseToken(token)
+//			if err != nil {
+//				switch err.(*jwt.ValidationError).Errors {
+//				case jwt.ValidationErrorExpired:
+//					code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
+//				default:
+//					code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
+//				}
+//			}
+//		}
+//
+//		if code != e.SUCCESS {
+//			c.JSON(e.SUCCESS, gin.H{
+//				"code": code,
+//				"msg":  "登录超时",
+//				"data": data,
+//			})
+//
+//			c.Abort()
+//			return
+//		}
+//
+//		t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
+//			return jwtGet.JwtSecret, nil
+//		})
+//		c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
+//		c.Next()
+//	}
+//}
+
 package jwt
 
 import (
-	//"strings"
-
+	"bytes"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"github.com/astaxie/beego/logs"
 	"github.com/dgrijalva/jwt-go"
 	"github.com/gin-gonic/gin"
+	"github.com/pkg/errors"
+	"io/ioutil"
 	"kpt.xdmy/pkg/e"
-	"kpt.xdmy/pkg/util"
 	jwtGet "kpt.xdmy/pkg/util"
+	"net/http"
+	"strings"
+
+	//"strings"
+	"kpt.xdmy/pkg/setting"
 )
 
+//var (
+//	svc *service.Service
+//)
+
+type Introspect struct {
+	Active   bool   `json:"active"`
+	UserName string `json:"user_name"`
+}
+
 func JWT() gin.HandlerFunc {
-	return func(c *gin.Context) {
-		var code int
-		var data interface{}
-
-		code = e.SUCCESS
-		//Authorization := c.GetHeader("Authorization")
-		//token := strings.Split(Authorization, " ")
-		Authorization := c.GetHeader("token")
-		token := Authorization
-		if Authorization == "" {
-			code = e.INVALID_PARAMS
-		} else {
-			//_, err := util.ParseToken(token[1])
-			_, err := util.ParseToken(token)
-			if err != nil {
-				switch err.(*jwt.ValidationError).Errors {
-				case jwt.ValidationErrorExpired:
-					code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
-				default:
-					code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
-				}
+	if setting.IDaaSSetting.IsDaaS == 1 {
+		return func(c *gin.Context) {
+			//s := new(service.Service)
+			fmt.Println(setting.IDaaSSetting)
+			authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(setting.IDaaSSetting.ClientId+":"+setting.IDaaSSetting.ClientSecret)))
+			fmt.Println(authorization)
+			//tokenData := make(map[string]string, 0)
+			//tokenData["token"] = c.GetHeader("token")
+			//tokenDataByte, _ := json.Marshal(tokenData)
+			tokenRespByte, _ := PostPush(setting.IDaaSSetting.Url+fmt.Sprintf("/api/v1/oauth2/introspect?token=%s", c.GetHeader("token")), nil, authorization)
+			IntrospectResp := new(Introspect)
+			json.Unmarshal(tokenRespByte, &IntrospectResp)
+
+			if !IntrospectResp.Active {
+				c.JSON(e.SUCCESS, gin.H{
+					"code": e.INVALID_PARAMS,
+					"msg":  "登录失效!",
+					"data": "",
+				})
+
+				c.Abort()
+				return
 			}
+
+			c.Set("jwt_username", IntrospectResp.UserName)
+			c.Next()
 		}
+	} else {
+		return func(c *gin.Context) {
+			var code int
+			var data interface{}
 
-		if code != e.SUCCESS {
-			c.JSON(e.SUCCESS, gin.H{
-				"code": code,
-				"msg":  "登录超时",
-				"data": data,
-			})
+			code = e.SUCCESS
+			//Authorization := c.GetHeader("Authorization")
+			//token := strings.Split(Authorization, " ")
+			Authorization := c.GetHeader("token")
+			token := Authorization
+			if Authorization == "" {
+				code = e.INVALID_PARAMS
+			} else {
+				//_, err := util.ParseToken(token[1])
+				_, err := jwtGet.ParseToken(token)
+				if err != nil {
+					switch err.(*jwt.ValidationError).Errors {
+					case jwt.ValidationErrorExpired:
+						code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
+					default:
+						code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
+					}
+				}
+			}
+
+			if code != e.SUCCESS {
+				c.JSON(e.SUCCESS, gin.H{
+					"code": code,
+					"msg":  "登录超时",
+					"data": data,
+				})
+
+				c.Abort()
+				return
+			}
 
-			c.Abort()
-			return
+			t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
+				return jwtGet.JwtSecret, nil
+			})
+			c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
+			c.Next()
 		}
+	}
+}
+
+func PostPush(url string, data []byte, authorization string) ([]byte, error) {
+
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	req.Header.Set("Authorization", authorization)
+
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
 
-		t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
-			return jwtGet.JwtSecret, nil
-		})
-		c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
-		c.Next()
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println(string(body))
+	if strings.Index(resp.Status, "200") == -1 {
+		return nil, errors.New(fmt.Sprintf("%s 请求失败!", resp.Status))
 	}
+	return body, nil
 }

+ 6 - 0
pkg/http/http.go

@@ -21,6 +21,7 @@ type Client struct {
 	client  *http.Client
 	sapAuth *Auth
 	srmAuth *Auth
+	Liugong *config.LiuGong
 }
 
 func NewClient(con *config.Config) *Client {
@@ -37,6 +38,11 @@ func NewClient(con *config.Config) *Client {
 			Username: con.Http.SrmName,
 			Password: con.Http.SrmPwd,
 		},
+		Liugong: &config.LiuGong{
+			UserName: con.LiuGong.UserName,
+			PassWord: con.LiuGong.PassWord,
+			Routing:  con.LiuGong.Routing,
+		},
 	}
 }
 

+ 10 - 0
pkg/setting/setting.go

@@ -105,9 +105,18 @@ type SQlServer struct {
 	Name     string
 }
 
+type IDaaS struct {
+	AppId        string
+	ClientId     string
+	ClientSecret string
+	Url          string
+	IsDaaS       int
+}
+
 var DatabaseSetting = &Database{}
 
 var SQlServerSetting = &SQlServer{}
+var IDaaSSetting = &IDaaS{}
 
 var cfg *ini.File
 
@@ -155,6 +164,7 @@ func Setup(dir string) {
 	mapTo("database", DatabaseSetting)
 	mapTo("comm", CommSetting)
 	mapTo("sqlserver", SQlServerSetting)
+	mapTo("idaas", IDaaSSetting)
 
 	AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024
 	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second

+ 37 - 22
pkg/util/mail.go

@@ -2363,7 +2363,8 @@ func DownloadEquipment(parammaps string) (string, error) {
 	}
 	f := excelize.NewFile()
 	Style, err := f.NewStyle("{\"Alignment\":{\"Vertical\": \"center\", \"Horizontal\":\"center\"}}")
-	columns := []string{"设备指标", "维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费", "生物质颗粒", "汽油用量", "煤炭用量"}
+	//columns := []string{"设备指标", "维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费", "生物质颗粒", "汽油用量", "煤炭用量"}
+	columns := []string{"设备指标", "维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费"}
 	columnsMap := make(map[string]string, 0)
 	columnsMap["设备指标"] = "万元"
 	columnsMap["维修费"] = "万元"
@@ -2409,14 +2410,21 @@ func DownloadEquipment(parammaps string) (string, error) {
 	}
 
 	sqlnames := []string{}
+	//if pastureId == "现代牧业" {
+	//	sqlnames = []string{"getChooseEqMonthBudgetListSumAll", "getChooseMonthWX", "getChooseWaterPrice", "getChooseElectricityPrice", "getChooseMonthiolPrice",
+	//		"getChooseMonthWater", "getChooseMonthElectricity", "getChooseMonthOilT", "getLgnitionChargePrice", "getChooseBiomassPrice", "getChooseGasolinePrice",
+	//		"getChooseCoalPrice"}
+	//} else {
+	//	sqlnames = []string{"getChooseEqMonthBudgetListSumAllByPasture", "getChooseMonthWXByPasture", "getChooseWaterPriceByPasture", "getChooseElectricityPriceByPasture", "getChooseMonthiolPriceByPasture",
+	//		"getChooseMonthWaterByPasture", "getChooseMonthElectricityByPasture", "getChooseMonthOilTByPasture", "getLgnitionChargePriceByPasture", "getChooseBiomassPriceByPasture", "getChooseGasolinePriceByPasture",
+	//		"getChooseCoalPriceByPasture"}
+	//}
 	if pastureId == "现代牧业" {
 		sqlnames = []string{"getChooseEqMonthBudgetListSumAll", "getChooseMonthWX", "getChooseWaterPrice", "getChooseElectricityPrice", "getChooseMonthiolPrice",
-			"getChooseMonthWater", "getChooseMonthElectricity", "getChooseMonthOilT", "getLgnitionChargePrice", "getChooseBiomassPrice", "getChooseGasolinePrice",
-			"getChooseCoalPrice"}
+			"getChooseMonthWater", "getChooseMonthElectricity", "getChooseMonthOilT", "getLgnitionChargePrice"}
 	} else {
 		sqlnames = []string{"getChooseEqMonthBudgetListSumAllByPasture", "getChooseMonthWXByPasture", "getChooseWaterPriceByPasture", "getChooseElectricityPriceByPasture", "getChooseMonthiolPriceByPasture",
-			"getChooseMonthWaterByPasture", "getChooseMonthElectricityByPasture", "getChooseMonthOilTByPasture", "getLgnitionChargePriceByPasture", "getChooseBiomassPriceByPasture", "getChooseGasolinePriceByPasture",
-			"getChooseCoalPriceByPasture"}
+			"getChooseMonthWaterByPasture", "getChooseMonthElectricityByPasture", "getChooseMonthOilTByPasture", "getLgnitionChargePriceByPasture"}
 	}
 
 	xx := 0
@@ -2452,7 +2460,9 @@ func DownloadEquipment(parammaps string) (string, error) {
 				if index := strings.Index(s, "."); index != -1 && len(s)-index-1 >= 2 {
 					s = s[:index+3]
 				}
-
+				if s != "" {
+					s = fmt.Sprintf("%s%%", s)
+				}
 				value := []interface{}{columnName, v["pastureName"], "全厂区", v["monthBudget"], v["sumPrice"],
 					v["asave"], s, v["oneCowSumPrice"]}
 				for a, b := range value {
@@ -2469,34 +2479,36 @@ func DownloadEquipment(parammaps string) (string, error) {
 	if pastureId == "现代牧业" {
 		sqlnamesDepartment = []string{
 			"getChooseMonthWX1",
-			"getChooseWaterPrice1",
-			"getChooseElectricityPrice1",
-			"getChooseMonthiolPrice1",
+			"getChooseWaterPrice",
+			"getChooseElectricityPrice",
+			"getChooseMonthiolPrice",
 			"getChooseMonthWater1",
 			"getChooseMonthElectricity1",
 			"getChooseMonthOilT1",
-			"getLgnitionChargePrice1",
-			"getChooseMonthBiomass1",
-			"getChooseMonthGasoline1",
-			"getChooseMonthCoal1"}
+			"getLgnitionChargePrice",
+			//"getChooseMonthBiomass1",
+			//"getChooseMonthGasoline1",
+			//"getChooseMonthCoal1"
+		}
 	} else {
 		sqlnamesDepartment = []string{
 			"getChooseMonthWX1ByPasture",
-			"getChooseWaterPrice1ByPasture",
-			"getChooseElectricityPrice1ByPasture",
-			"getChooseMonthiolPrice1ByPasture",
+			"getChooseWaterPriceByPasture",
+			"getChooseElectricityPriceByPasture",
+			"getChooseMonthiolPriceByPasture",
 			"getChooseMonthWater1ByPasture",
 			"getChooseMonthElectricity1ByPasture",
 			"getChooseMonthOilT1ByPasture",
-			"getLgnitionChargePrice1ByPasture",
-			"getChooseMonthBiomass1ByPasture",
-			"getChooseMonthGasoline1ByPasture",
-			"getChooseMonthCoal1ByPasture"}
+			"getLgnitionChargePriceByPasture",
+			//"getChooseMonthBiomass1ByPasture",
+			//"getChooseMonthGasoline1ByPasture",
+			//"getChooseMonthCoal1ByPasture"
+		}
 	}
 	// sqlnamesDepartment := []string{"getChooseMonthWXDepartment", "getChooseWaterPriceDepartment", "getChooseElectricityPriceDepartment", "getChooseMonthiolPriceDepartment",
 	// 	"getChooseMonthWaterDepartment", "getChooseMonthElectricityDepartment", "getChooseMonthOilTDepartment"}
-	columnss := []string{"维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费", "生物质颗粒", "汽油用量", "煤炭用量"}
-
+	//columnss := []string{"维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费", "生物质颗粒", "汽油用量", "煤炭用量"}
+	columnss := []string{"维修费", "水费", "电费", "柴油费", "水量", "电量", "柴油用量", "燃动费"}
 	for z, sqlname := range sqlnamesDepartment {
 		valuesMap, err := restful.MapStr("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", sqlname)
 		parammap := make(map[string]interface{}, 0)
@@ -2531,6 +2543,9 @@ func DownloadEquipment(parammaps string) (string, error) {
 				if index := strings.Index(s, "."); index != -1 && len(s)-index-1 >= 2 {
 					s = s[:index+3]
 				}
+				if s != "" {
+					s = fmt.Sprintf("%s%%", s)
+				}
 				value := []interface{}{v["sort"], v["pastureName"], v["deptname"], v["monthBudget"], v["sumPrice"],
 					v["asave"], s, v["oneCowSumPrice"]}
 				for a, b := range value {

+ 83 - 0
pkg/util/util.go

@@ -2,9 +2,18 @@ package util
 
 import (
 	"bytes"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"crypto/tls"
+	"encoding/base64"
 	"fmt"
+	"github.com/astaxie/beego/logs"
 	"io"
+	"io/ioutil"
 	"math"
+	"net"
+	"net/http"
 	"time"
 
 	"github.com/pkg/errors"
@@ -137,3 +146,77 @@ func NewMap(name string, value interface{}) map[string]interface{} {
 func Round(number float64, size int) float64 {
 	return math.Round(number*100) / 100
 }
+
+func PostPush(url string, data []byte) ([]byte, error) {
+
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
+
+	tr := &http.Transport{
+		TLSClientConfig: &tls.Config{
+			InsecureSkipVerify: true, // 注意:在生产环境中不要使用此选项,因为它会跳过证书验证
+		},
+	}
+	client := &http.Client{Transport: tr}
+
+	//req.Header.Set("host", "quiplink.liugong.com:443")
+	//req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
+	//client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		logs.Error(err)
+		return nil, err
+	}
+
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println(string(body))
+	return body, nil
+}
+
+func getHostIp() string {
+	addrList, err := net.InterfaceAddrs()
+	if err != nil {
+		fmt.Println("get current host ip err: ", err)
+		return ""
+	}
+	var ip string
+	for _, address := range addrList {
+		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
+			if ipNet.IP.To4() != nil {
+				ip = ipNet.IP.String()
+				break
+			}
+		}
+	}
+	return ip
+}
+
+// 加密
+func AesEncryptByECB(originalText string) string {
+	key := make([]byte, 16)
+	if _, err := io.ReadFull(rand.Reader, key); err != nil {
+		panic(err)
+	}
+
+	// 创建一个AES块密码(AES-128)
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		panic(err)
+	}
+
+	// 使用AES块密码创建一个CBC模式的加密器
+	cipherText := make([]byte, aes.BlockSize+len(originalText))
+	iv := cipherText[:aes.BlockSize]
+	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+		panic(err)
+	}
+	stream := cipher.NewCFBEncrypter(block, iv)
+	stream.XORKeyStream(cipherText[aes.BlockSize:], []byte(originalText))
+	return base64.StdEncoding.EncodeToString(cipherText)
+}

+ 13 - 2
pkg/util/wxwork.go

@@ -65,7 +65,7 @@ func CronWXwork() {
 		println("cron4 err", err.Error())
 	}
 	GetMsg()
-	_, err = c.AddFunc("@every 2m0s", GetMsg)          //* * * * *,  从分钟开始
+	_, err = c.AddFunc("@every 4m0s", GetMsg)          //* * * * *,  从分钟开始
 	_, err = c.AddFunc("00 00 07 * * *", GetPartsInfo) //* * * * *,  每天七点
 	cronMaintainPush()
 	c.AddFunc("@every 2m0s", cronMaintainPush)
@@ -198,6 +198,7 @@ func SendRun() {
 	defer func() {
 		if err := recover(); err != nil {
 			logging.Error("GetMsg pnic err", err)
+			SendRun()
 		}
 	}()
 
@@ -233,10 +234,20 @@ func SendRun() {
 
 				params := url.Values{}
 				params.Add("mobile", value["tel"])
+
+				if value["tel"] == "" {
+					continue
+				}
+				fmt.Println(value["tel"], "logs")
 				//params.Add("mobile", "18317742428")
 				req, _ := http.NewRequest(http.MethodGet, "/user/get_by_mobile?"+params.Encode(), nil)
 				resp, err := DingClient.Do(req)
 				if err != nil {
+					fmt.Println(err)
+					_, err = restful.Dbs.Exec(` update wxworkmsg set statue = 1 ,pushTime = now(),note = ?  where id =  ? `, err.Error(), value["wxworkmsgId"])
+					if err != nil {
+						fmt.Println(err)
+					}
 					continue
 				}
 				fmt.Println(value["111"], value["userid"], value["empId"])
@@ -277,8 +288,8 @@ func SendRun() {
 		}
 
 	}
-
 }
+
 func GetMsgv1() {
 	go GetMsgv2()
 }

+ 51 - 0
sap.sql

@@ -71,3 +71,54 @@ group by pastureId,date_format(date ,'%Y-%m')
 select pastureId,p.company_code,p.factory_code,"燃动费", date_format(selTime ,'%Y'),date_format(selTime ,'%m'),    sum(nowPrice) sumPrice, date_format(selTime ,'%Y-%m') from diesel  join pasture p on p.id = pastureId  where date_format(selTime ,'%Y') = '2022'
 group by pastureId,date_format(selTime ,'%Y-%m')
 
+
+ALTER TABLE `eq`.`equipment`
+    ADD COLUMN `deptId` varchar(30) NULL COMMENT '成本部门' AFTER `levelthreeTime`;
+
+
+ALTER TABLE `eq`.`maintain`
+    ADD COLUMN `remark` varchar(255) NULL COMMENT '备注' AFTER `outsourcing`;
+
+
+
+ALTER TABLE `equipment`
+    ADD COLUMN `duration` decimal(15, 2) NULL COMMENT '标准时长' AFTER `license`,
+ADD COLUMN `pushStatus` tinyint(1) NOT NULL DEFAULT 0 COMMENT ' 0 报废  1 新增 2 更新' AFTER `duration`
+
+-----------------------------------
+
+ALTER TABLE `partpurchase`
+    ADD COLUMN `reject` tinyint(1) NOT NULL DEFAULT 0 COMMENT ' 1 驳回' AFTER `ContractVarianceItem`,
+ADD COLUMN `departmentId` int NULL COMMENT '部门' AFTER `reject`
+
+
+
+ALTER TABLE `partpurchase`
+    ADD COLUMN `date` datetime NULL COMMENT '申购时间' AFTER `explain`
+
+ALTER TABLE `partpurchase`
+    ADD COLUMN `employeId` int NULL COMMENT '申购人' AFTER `date`
+
+
+
+
+
+ALTER TABLE `bigpartpurchase`
+    ADD COLUMN `positionId` int NULL COMMENT '职能中心' AFTER `financedate`,
+ADD COLUMN `positiondate` datetime NULL AFTER `positionId`
+
+
+ALTER TABLE `bigacceptance`
+    ADD COLUMN `remark` varchar(100) NULL COMMENT '备注' AFTER `isAcceptance`
+
+
+ALTER TABLE `bigpartpurchase`
+    ADD COLUMN `isMilk` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1 奶厅' AFTER `positiondate`;
+
+---------------------------
+ALTER TABLE `eq`.`equipment`
+    ADD COLUMN `work` varchar(30) NULL COMMENT '工作类别' AFTER `pushStatus`;
+
+
+ALTER TABLE buydetail
+    ADD COLUMN `reportery` decimal(12, 2) NOT NULL DEFAULT 0 COMMENT '库存' AFTER `rowNumber`;

Vissa filer visades inte eftersom för många filer har ändrats