package service import ( "encoding/json" "fmt" "github.com/astaxie/beego/logs" "kpt.xdmy/apiserver/model" "kpt.xdmy/apiserver/model/liugong" "kpt.xdmy/pkg/util" "strconv" "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) //OperateCenterName string `json:"operateCenterName"` //运营中心 //AreaName string `json:"areaName"` //大区 //RanchName string `json:"ranchName"` //牧场 for _, pasture := range pastureList { if pasture.ID == eq.PastureId { arg.RanchName = pasture.Name arg.AreaCode = fmt.Sprintf("%d", pasture.RegionID) arg.AreaName = pasture.Region center := 0 if pasture.Center == "一中心" { center = 1 } else if pasture.Center == "二中心" { center = 2 } else if pasture.Center == "三中心" { center = 3 } arg.OperationCode = fmt.Sprintf("%d", center) arg.OperateCenterName = pasture.Center break } } arg.RancheCode = 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 if eq.Statue == 19 { arg.Status = 0 } else if strings.Index(eq.License, "-") >= 0 { arg.Status = 3 fmt.Println(strings.Index(eq.License, "-")) eq.License = strings.Replace(eq.License, "-", "", -1) fmt.Println(eq.License) } 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 } func (s *Service) GetRunningRateDetail(date, pastureId, eqCode string, offset, pagecount int) ([]map[string]interface{}, error) { dataList := make([]map[string]interface{}, 0) 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) and (e.pastureId = ? or ? = 18) and ( eqCode like concat('%',?,'%') or ? ='' ) limit ?,? `, pastureId, pastureId, eqCode, eqCode, offset, pagecount).Find(&eqList).Error if err != nil { logs.Error(err) return dataList, nil } vehicleList := make([]*liugong.Vehicle, 0) var eqIdList []int for _, eq := range eqList { eqIdList = append(eqIdList, eq.Id) } err = s.d.DB.Debug().Table(new(liugong.Vehicle).TableName()).Select("pastureName,eqId,license,date_format(date ,'%Y-%m-%d') date,hour,duration"). Where(" date_format(date ,'%Y-%m') = ? ", date).Where(" eqId in (?) ", eqIdList).Find(&vehicleList).Error if err != nil { logs.Error(err) return dataList, nil } now := time.Now() var dateList []string firstDay := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) nextMonthFirstDay := firstDay.AddDate(0, 1, 0) lastDay := nextMonthFirstDay.Add(-24 * time.Hour) for t := firstDay; !t.After(lastDay); t = t.AddDate(0, 0, 1) { fmt.Println(t.Format("2006-01-02")) dateList = append(dateList, t.Format("2006-01-02")) } num, err := strconv.Atoi(now.Format("02")) if err != nil { fmt.Printf("转换出错: %v\n", err) return dataList, nil } for _, eq := range eqList { data := make(map[string]interface{}, 0) data["id"] = eq.Id data["eqName"] = eq.EqName data["eqCode"] = eq.EqCode data["eqClassName"] = eq.EqClassName data["duration"] = eq.Duration data["license"] = eq.License var hour float64 for i, date := range dateList { data[fmt.Sprintf("%d", i+1)] = 0 for _, vehicle := range vehicleList { if vehicle.EqId == fmt.Sprintf("%d", eq.Id) && vehicle.Date == date { data["pastureName"] = vehicle.PastureName data["license"] = vehicle.License data[fmt.Sprintf("%d", i+1)] = vehicle.Hour float64Value, err := strconv.ParseFloat(vehicle.Hour, 64) if err != nil { return nil, err } hour += float64Value } } } if hour > 0 && num > 0 && eq.Duration > 0 { data["runningRate"] = util.Round(hour/float64(num*eq.Duration)*100, 2) } else { data["runningRate"] = 0 } dataList = append(dataList, data) } return dataList, nil }