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
		err = e.Orm.Model(&model.CoolerBoxRecord{}).Where("cooler_box_id = ?", (*list)[i].Id).Where("status = ?", 1).First(&(*list)[i].CoolerBoxRecords).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				continue
			} else {
				e.Log.Errorf("查询保温箱记录失败: %s", err)
				return global.GetFailedErr
			}
		}
	}
	//排序
	sort.SliceStable(*list, func(i, j int) bool {
		return len((*list)[i].IceRaft) > len((*list)[j].IceRaft)
	})
	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
	if len(c.Sn) > 0 {
		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
	//fmt.Println("公司ID=================", c.Id)
	err := e.Orm.Model(&dataDept).Where("id = ?", c.Id).Or("parent_id =?", c.Id).Find(&Depts).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 {
		uniqueMap[d.T_time] = true
	}
	for _, d := range newData {
		if !uniqueMap[d.T_time] {
			if len(d.T_site) > 0 && d.T_site != "0,0" {
				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),
		).
			Find(&list).Limit(-1).Offset(-1).Order("cooler_user_time asc").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),
		).
			Find(&list).Limit(-1).Offset(-1).Order("cooler_user_time asc").Count(count).
			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()
		}
	}()
	var user model.SysUser
	first := tx.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 = tx.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
		cooler.ForColdCoolerTime = coolerBox.ForColdCoolerTime
		err = tx.Create(&cooler).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
		//更新保温箱状态为遇冷中
		if coolerBox.UseStatus != 0 {
			e.Log.Errorf("保温箱已经预冷，不能重复预冷: %s", err)
			return errors.New("保温箱已经预冷，不能重复预冷")
		}
		err = tx.Model(&model.CoolerBox{}).Where("id =?", v).Update("use_status", 1).Error
		if err != nil {
			e.Log.Errorf("更新保温箱状态失败: %s", err)
			return errors.New("更新保温箱状态失败")
		}
	}
	return nil
}

// CoolerBoxEndUse 保温箱结束使用
func (e *CoolerBox) CoolerBoxEndUse(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 coolerRecord model.CoolerBoxRecord
		var coolerBox model.CoolerBox
		err = tx.Model(&model.CoolerBox{}).Where("id = ?", v).First(&coolerBox).Error
		if err != nil {
			e.Log.Errorf("获取保温箱信息失败: %s", err)
			return errors.New("获取保温箱信息失败")
		}
		//if coolerBox.UseStatus != 2 {
		//	e.Log.Errorf("保温箱未开始使用使用，不能结束使用: %s", err)
		//	return errors.New("保温箱未开始使用使用，不能结束使用")
		//}
		//err := tx.Model(&model.CoolerBoxRecord{}).Where("cooler_box_id = ?", v).Where("status = ?", 1).First(&cooler).Error
		//if err != nil {
		//	if errors.Is(err, gorm.ErrRecordNotFound) {
		//		return errors.New("保温箱未开始使用使用，不能结束使用")
		//	} else {
		//		e.Log.Errorf("查询保温箱记录失败: %s", err)
		//		return errors.New("查询保温箱记录失败")
		//	}
		//}
		err = tx.Model(&model.CoolerBoxRecord{}).Where("cooler_box_id = ?", v).Where("status = ?", 1).First(&coolerRecord).Error
		if err != nil {
			e.Log.Errorf("获取保温箱记录失败: %s", err)
			return errors.New("保温箱未开始使用不能结束使用")
		}
		if len(coolerRecord.CoolerUserTime.String()) == 0 {
			err = tx.Model(&model.CoolerBoxRecord{}).Where("cooler_box_id = ?", v).Where("status = ?", 1).Delete(&coolerRecord).Error
			if err != nil {
				e.Log.Errorf("删除保温箱记录失败: %s", err)
				return errors.New("删除保温箱记录失败")
			}
			//更新保温箱信息为默认未使用状态
			err = tx.Model(&model.CoolerBox{}).Where("id = ?", v).Update("use_status", 0).Error
			if err != nil {
				e.Log.Errorf("保温箱状态更新失败: %s", err)
				return errors.New("保温箱状态更新失败")
			}
		} else {
			//保温箱使用状态变为结束使用
			coolerRecord.CoolerEndUseTime = model2.Time(time.Now())
			coolerRecord.Status = "2"
			err = tx.Model(&coolerRecord).Where("cooler_box_id = ?", v).Updates(&coolerRecord).Error
			if err != nil {
				e.Log.Errorf("db error: %s", err)
				return global.CreateFailedErr
			}
			//更新保温箱状态为默认状态  0
			err = tx.Model(&model.CoolerBox{}).Where("id =?", v).Update("use_status", 0).Error
			if err != nil {
				e.Log.Errorf("更新保温箱状态失败: %s", err)
				return errors.New("更新保温箱状态失败")
			}
		}
	}
	return nil
}
