123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666 |
- package service
- import (
- "cold-delivery/app/admin/model"
- "cold-delivery/app/admin/service/dto"
- "cold-delivery/common/actions"
- cDto "cold-delivery/common/dto"
- "cold-delivery/common/global"
- "cold-delivery/common/lib"
- model2 "cold-delivery/common/model"
- "cold-delivery/common/nats/nats_server"
- "errors"
- "fmt"
- "gogs.baozhida.cn/zoie/OAuth-core/service"
- "gorm.io/gorm"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- type CoolerBox struct {
- service.Service
- }
- // GetPage 获取CoolerBox列表
- func (e *CoolerBox) GetPage(c *dto.CoolerBoxGetPageReq, list *[]model.CoolerBox, count *int64, p *actions.DataPermission) error {
- var err error
- var data model.CoolerBox
- if c.PageSize == 9999 {
- err = e.Orm.Model(&data).
- Scopes(
- actions.Permission(data.TableName(), p),
- ).
- Find(list).Limit(-1).Offset(-1).
- Count(count).Error
- } else {
- err = e.Orm.Model(&data).
- Scopes(
- cDto.MakeCondition(c.GetNeedSearch()),
- cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
- actions.Permission(data.TableName(), p),
- ).
- Find(list).Limit(-1).Offset(-1).
- Count(count).Error
- }
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.GetFailedErr
- }
- if c.ShowTemp {
- // 获取公司秘钥
- var company model.SysDept
- company, err = model.GetCompanyById(p.DeptId)
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return model.GetCompanyKeyErr
- }
- for i := 0; i < len(*list); i++ {
- deviceData, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey((*list)[i].Sn, company.ColdKey)
- if len(deviceData) > 0 {
- (*list)[i].DeviceData = deviceData[0].T_DeviceSensorData
- }
- }
- }
- for i, _ := range *list {
- var dataIce model.IceRaft
- var dataIces []model.IceRaft
- err := e.Orm.Model(&dataIce).
- Scopes(
- actions.Permission(dataIce.TableName(), p),
- IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusUsing),
- IceRaftNameRecordCoolerBoxIdScopes((*list)[i].Id),
- ).
- Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
- Preload("IceRaftRecord").
- Find(&dataIces).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.GetFailedErr
- }
- (*list)[i].IceRaft = dataIces
- }
- return nil
- }
- // Get 获取CoolerBox对象
- func (e *CoolerBox) Get(d *dto.CoolerBoxGetReq, CoolerBoxModel *model.CoolerBox, p *actions.DataPermission) error {
- err := e.Orm.
- Scopes(actions.Permission(CoolerBoxModel.TableName(), p)).
- First(CoolerBoxModel, d.GetId()).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.GetNotFoundOrNoPermissionErr
- }
- return global.GetFailedErr
- }
- return nil
- }
- // Insert 创建CoolerBox对象
- func (e *CoolerBox) Insert(c *dto.CoolerBoxInsertReq, p *actions.DataPermission) error {
- var err error
- var data model.CoolerBox
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- var k int64
- err = tx.Model(&data).Where("sn = ?", c.Sn).Count(&k).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- if k > 0 {
- err = errors.New("该Sn已绑定!")
- e.Log.Errorf("db error: %s", err)
- return err
- }
- //var device nats_server.Device
- //var company model.SysDept
- //device, err = nats_server.Cold_ReadDeviceByT_sn(c.Sn)
- //if err != nil {
- // err = errors.New("获取SN信息失败,请检查SN是否正确!")
- // e.Log.Errorf("db error: %s", err)
- // return err
- //}
- //company, err = model.GetCompanyById(p.DeptId)
- //if err != nil {
- // e.Log.Errorf("db error: %s", err)
- // return err
- //}
- //if device.T_pid != company.Id {
- // err = errors.New("获取SN信息失败,请检查SN是否正确!")
- // e.Log.Errorf("获取SN信息失败,device.T_pid != company.Id")
- // return err
- //}
- // 添加保温箱
- c.Generate(&data)
- data.HistorySn = []string{data.Sn}
- err = tx.Create(&data).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- c.Id = data.Id
- return nil
- }
- func (e *CoolerBox) BatchInsert(c *dto.CoolerBoxBatchInsertReq) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- for _, coolerBox := range c.List {
- var data model.CoolerBox
- var k int64
- err = tx.Model(&data).Where("sn = ?", coolerBox.Sn).Count(&k).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- if k > 0 {
- //err = errors.New("该Sn已绑定!")
- continue
- }
- // 添加保温箱
- coolerBox.CreateBy = c.CreateBy
- coolerBox.DeptId = c.DeptId
- coolerBox.Status = c.Status
- coolerBox.Generate(&data)
- data.HistorySn = []string{data.Sn}
- err = tx.Create(&data).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- }
- return nil
- }
- // Update 修改CoolerBox对象
- func (e *CoolerBox) Update(c *dto.CoolerBoxUpdateReq, p *actions.DataPermission) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- var CoolerBoxModel = model.CoolerBox{}
- // 查询保温箱是否存在
- err = e.Orm.Scopes(actions.Permission(CoolerBoxModel.TableName(), p)).
- First(&CoolerBoxModel, c.GetId()).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.UpdateNotFoundOrNoPermissionErr
- }
- return global.UpdateFailedErr
- }
- if CoolerBoxModel.Sn != c.Sn && len(c.Sn) > 0 {
- var k int64
- var data = model.CoolerBox{}
- err = tx.Model(&data).Where("sn = ?", c.Sn).Count(&k).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- if k > 0 {
- err = errors.New("该Sn已绑定!")
- e.Log.Errorf("db error: %s", err)
- return err
- }
- //var device nats_server.Device
- //var company model.SysDept
- //device, err = nats_server.Cold_ReadDeviceByT_sn(c.Sn)
- //if err != nil {
- // err = errors.New("获取SN信息失败,请检查SN是否正确!")
- // e.Log.Errorf("db error: %s", err)
- // return err
- //}
- //company, err = model.GetCompanyById(p.DeptId)
- //if err != nil {
- // e.Log.Errorf("db error: %s", err)
- // return err
- //}
- //if device.T_pid != company.Id {
- // err = errors.New("获取SN信息失败,请检查SN是否正确!")
- // e.Log.Errorf("获取SN信息失败,device.T_pid != company.Id")
- // return err
- //}
- CoolerBoxModel.HistorySn = append(CoolerBoxModel.HistorySn, c.Sn)
- }
- c.Generate(&CoolerBoxModel)
- err = tx.Save(&CoolerBoxModel).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- c.Id = CoolerBoxModel.Id
- return nil
- }
- // Remove 删除CoolerBox
- func (e *CoolerBox) Remove(c *dto.CoolerBoxDeleteReq, p *actions.DataPermission) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- var iceRaftModel model.IceRaft
- var count int64
- err = e.Orm.Model(&iceRaftModel).
- Scopes(
- actions.Permission(iceRaftModel.TableName(), p),
- IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusUsing),
- IceRaftNameRecordCoolerBoxIdScopes(c.Id),
- ).
- Where("ice_raft.status = '2'").
- Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
- Count(&count).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.DeleteFailedErr
- }
- if count > 0 {
- err = errors.New("该保温箱下有冰排正在使用中,无法删除!")
- return err
- }
- var CoolerBoxModel model.CoolerBox
- // 查询保温箱是否存在
- err = e.Orm.Scopes(actions.Permission(CoolerBoxModel.TableName(), p)).
- First(&CoolerBoxModel, c.GetId()).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.DeleteNotFoundOrNoPermissionErr
- }
- return global.DeleteFailedErr
- }
- db := tx.Delete(&CoolerBoxModel)
- if err = db.Error; err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.DeleteFailedErr
- }
- if db.RowsAffected == 0 {
- return global.DeleteNotFoundOrNoPermissionErr
- }
- return nil
- }
- // GetHistory 获取保温箱历史信息
- func (e *CoolerBox) GetHistory(c *dto.CoolerBoxBatchReqSN, p *actions.DataPermission) ([]dto.HistoricalData, error) {
- var err error
- var taskList []model.WaybillTask
- var historical []dto.HistoricalData
- if c.Page == 0 {
- c.Page = 1
- }
- if c.PageZ == 0 {
- c.PageZ = 10
- }
- // 查询运单任务信息
- err = e.Orm.Model(&model.WaybillTask{}).
- Where("cooler_box_id = ?", c.Id).
- Find(&taskList).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return nil, errors.New("获取运单任务信息失败")
- }
- // 获取公司秘钥
- var dataDept model.SysDept
- var Depts []model.SysDept
- err = e.Orm.Model(&dataDept).
- Scopes(
- CompanyIdScopesUser(p.DeptId),
- ).
- Find(&Depts).Limit(-1).Offset(-1).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return nil, model.GetCompanyKeyErr
- }
- //company, err := model.GetCompanyById(p.DeptId)
- //if err != nil {
- // e.Log.Errorf("db error: %s", err)
- // return nil, model.GetCompanyKeyErr
- //}
- // 限制并发请求数量
- const maxConcurrentRequests = 10
- semaphore := make(chan struct{}, maxConcurrentRequests)
- var deviceSensorList []nats_server.DeviceSensor_R
- var wg sync.WaitGroup
- for _, task := range taskList {
- wg.Add(1)
- go func(task model.WaybillTask) {
- defer wg.Done()
- semaphore <- struct{}{}
- defer func() { <-semaphore }()
- for _, v := range Depts {
- deviceSensorList, _, _ = nats_server.Cold_CompanyDeviceSensor_List_ByKey(task.Sn, v.ColdKey)
- if len(deviceSensorList) > 0 {
- historical = append(historical, dto.HistoricalData{
- Sn: task.Sn,
- T_id: strconv.Itoa(deviceSensorList[0].T_id) + "|",
- StartTime: task.StartTime.String(),
- EndTime: task.EndTime.String(),
- CompanyName: v.Name,
- })
- break
- }
- }
- if len(deviceSensorList) == 0 {
- return
- }
- if err != nil {
- e.Log.Errorf("nats 获取轨迹信息失败: %s", err)
- return
- }
- }(task)
- }
- wg.Wait()
- sort.Slice(historical, func(i, j int) bool {
- if historical[i].StartTime < historical[j].StartTime {
- return true
- }
- return false
- })
- startIndex := (c.Page - 1) * c.PageZ
- endIndex := startIndex + c.PageZ
- if endIndex > len(historical) {
- endIndex = len(historical)
- }
- pageHistory := historical[startIndex:endIndex]
- return pageHistory, nil
- }
- // GetNewLocus 获取最新轨迹
- func (e *CoolerBox) GetNewLocus(c *dto.CoolerBoxReq, list *[]nats_server.DeviceData_) error {
- // 获取公司秘钥
- var dataDept model.SysDept
- var Depts []model.SysDept
- atoi, _ := strconv.Atoi(c.Id)
- err := e.Orm.Model(&dataDept).
- Scopes(
- CompanyIdScopesUser(atoi),
- ).
- Find(&Depts).Limit(-1).Offset(-1).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.GetFailedErr
- }
- var deviceSensorList []nats_server.DeviceSensor_R
- for _, v := range Depts {
- deviceSensorList, _, _ = nats_server.Cold_CompanyDeviceSensor_List_ByKey(c.T_sn, v.ColdKey)
- if len(deviceSensorList) > 0 {
- break
- }
- }
- if len(deviceSensorList) == 0 {
- return errors.New("该设备不属于该公司")
- }
- data, err := nats_server.Read_DeviceTask_List_By_Condition(c.T_sn)
- if err != nil {
- e.Log.Errorf("设备未开启监控: %s", err)
- return errors.New("设备未开启监控")
- }
- // 当最新设备状态为1时,证明设备正在启动中,查询大于开始时间的所有轨迹,设备状态为2时,查询开始时间到结束时间的轨迹
- if data.T_State == 1 {
- deviceData, err := nats_server.Read_Start_Time_DeviceData(c.T_sn, deviceSensorList[0].T_id, data.T_Ut_start.Format("2006-01-02 15:04:05"), "")
- if err != nil {
- e.Log.Errorf("获取设备轨迹失败: %s", err)
- return errors.New("获取设备轨迹失败")
- }
- *list = appendUniqueDeviceData(*list, deviceData)
- } else if data.T_State == 2 {
- deviceData, err := nats_server.Read_Start_Time_DeviceData(c.T_sn, deviceSensorList[0].T_id, data.T_Ut_start.Format("2006-01-02 15:04:05"), data.T_Ut_end.Format("2006-01-02 15:04:05"))
- if err != nil {
- e.Log.Errorf("获取设备轨迹失败: %s", err)
- return errors.New("获取设备轨迹失败")
- }
- *list = appendUniqueDeviceData(*list, deviceData)
- }
- return nil
- }
- // 去重并追加设备数据
- func appendUniqueDeviceData(list []nats_server.DeviceData_, newData []nats_server.DeviceData_) []nats_server.DeviceData_ {
- uniqueMap := make(map[time.Time]bool)
- for _, d := range list {
- //split := strings.Split(list[i].T_site, ",")
- //defer func() {
- // if r := recover(); r != nil {
- // fmt.Println("数组下标越界:", r)
- // }
- //}()
- //Lng := split[0]
- //Lat := split[1]
- //Lngs, _ := strconv.ParseFloat(Lng, 64)
- //Lats, _ := strconv.ParseFloat(Lat, 64)
- //mLng, mLat := lib.Wgs84ToGcj02(Lngs, Lats)
- //list[i].T_site = fmt.Sprintf("%v,%v", mLng, mLat)
- uniqueMap[d.T_time] = true
- }
- for _, d := range newData {
- if !uniqueMap[d.T_time] {
- split := strings.Split(d.T_site, ",")
- defer func() {
- if r := recover(); r != nil {
- fmt.Println("数组下标越界:", r)
- }
- }()
- Lng := split[0]
- Lat := split[1]
- Lngs, _ := strconv.ParseFloat(Lng, 64)
- Lats, _ := strconv.ParseFloat(Lat, 64)
- mLng, mLat := lib.Wgs84ToGcj02(Lngs, Lats)
- d.T_site = fmt.Sprintf("%v,%v", mLng, mLat)
- list = append(list, d)
- }
- }
- //排序
- sort.Slice(list, func(i, j int) bool {
- return list[i].T_time.After(list[j].T_time)
- })
- return list
- }
- // GetCoolerBoxIce 获取保温箱下的所有历史冰排
- func (e *CoolerBox) GetCoolerBoxIce(c *dto.GetCoolerBoxIce, list *[]model.IceRaftRecord, p *actions.DataPermission, count *int64) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- //查询保温箱是否存在
- var icerecord model.IceRaftRecord
- err = e.Orm.Scopes(
- cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
- actions.Permission(icerecord.TableName(), p)).
- Where("cooler_box_id=?", c.CoolerBoxId).
- Preload("IceLocker").
- Preload("CoolerBox").
- Find(&list).Count(count).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.GetFailedErr
- }
- return global.GetFailedErr
- }
- return nil
- }
- // GetCoolerBoxIceAll 获取保温箱所有历史记录
- func (e *CoolerBox) GetCoolerBoxIceAll(c *dto.GetCoolerBoxIceAll, list *[]model.CoolerBoxRecord, p *actions.DataPermission, count *int64) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- //查询保温箱是否存在
- var cooler model.CoolerBoxRecord
- if c.PageSize == 9999 {
- err = e.Orm.Scopes(
- cDto.MakeCondition(c.GetNeedSearch()),
- actions.Permission(cooler.TableName(), p),
- CollerStartTimeAndEndTimeScopes(c.StartTime, c.EndTime),
- ).
- Where("status = ?", 2).
- Find(&list).
- Count(count).Error
- } else {
- err = e.Orm.Scopes(
- cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
- cDto.MakeCondition(c.GetNeedSearch()),
- actions.Permission(cooler.TableName(), p),
- CollerStartTimeAndEndTimeScopes(c.StartTime, c.EndTime),
- ).
- Where("status = ?", 2).
- Find(&list).
- Count(count).Error
- }
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.GetFailedErr
- }
- return global.GetFailedErr
- }
- return nil
- }
- // CoolerBoxStarTime 保温箱开始释冷
- //
- // func (e *CoolerBox) CoolerBoxStarTime(c *dto.IceStartbleForColfTimReq, p *actions.DataPermission) error {
- // var err error
- //
- // tx := e.Orm.Begin()
- // defer func() {
- // if err != nil {
- // tx.Rollback()
- // } else {
- // tx.Commit()
- // }
- // }()
- // //查询冰排是否存在
- // for _, v := range c.Id {
- // var iceRaftRecordModel model.IceRaftRecord
- // err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
- // First(&iceRaftRecordModel, v).Error
- // if err != nil {
- // e.Log.Errorf("db error: %s", err)
- // if errors.Is(err, gorm.ErrRecordNotFound) {
- // return global.UpdateNotFoundOrNoPermissionErr
- // }
- // return global.UpdateFailedErr
- // }
- // iceRaftRecordModel.CoolerBoxStarTime = model2.Time(time.Now())
- // updates := tx.Where("id = ?", iceRaftRecordModel.Id).Updates(&iceRaftRecordModel)
- // if err = updates.Error; err != nil {
- // e.Log.Errorf("db error: %s", err)
- // return global.UpdateFailedErr
- // }
- // }
- // return nil
- // }
- func (e *CoolerBox) CoolerBoxStarTime(c *dto.IceStartbleForColfTimReq, p *actions.DataPermission) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- var user model.SysUser
- first := e.Orm.Model(&model.SysUser{}).Where("id = ?", p.UserId).First(&user)
- if first.Error != nil {
- return global.GetFailedErr
- }
- //添加保温箱记录
- for _, v := range c.Id {
- var cooler model.CoolerBoxRecord
- var coolerBox model.CoolerBox
- err = e.Orm.Model(&model.CoolerBox{}).Where("id = ?", v).First(&coolerBox).Error
- if err != nil {
- e.Log.Errorf("获取保温箱信息失败: %s", err)
- return errors.New("获取保温箱信息失败")
- }
- cooler.CoolerBoxStarTime = model2.Time(time.Now())
- cooler.CoolerColdUsers = user.NickName
- cooler.CoolerColdAddress = coolerBox.ColdSpots
- cooler.ColdTemperatures = coolerBox.ColdTemperatures
- cooler.Status = "1" //保温箱使用状态变为使用中
- CoolerBoxId, _ := strconv.Atoi(v)
- cooler.CoolerBoxId = CoolerBoxId
- cooler.DeptId = p.DeptId
- cooler.Sn = coolerBox.Sn
- cooler.Name = coolerBox.Name
- err = e.Orm.Create(&cooler).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.CreateFailedErr
- }
- }
- return nil
- }
|