package service

import (
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/operation/edge_service"
	"iot_manager_service/app/operation/model"
	"iot_manager_service/util/common"
)

// CaptureService 车流统计
var CaptureService = new(captureService)

type captureService struct{}

// GetDayVehicleTotal 车流统计 日
func (s captureService) GetDayVehicleTotal(tenantId string, req model.RequestCaptureFilter) ([]model.ResponseCaptureVehicleTotal, error) {
	return s.getVehicleTotalData(0, tenantId, req)
}

// GetMonthVehicleTotal 车流统计 月
func (s captureService) GetMonthVehicleTotal(tenantId string, req model.RequestCaptureFilter) ([]model.ResponseCaptureVehicleTotal, error) {
	return s.getVehicleTotalData(1, tenantId, req)
}

// 车流统计公用方法
func (s captureService) getVehicleTotalData(flag int, tenantId string, req model.RequestCaptureFilter) ([]model.ResponseCaptureVehicleTotal, error) {
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       req.CaptureId,
	}
	unit.GetDevice()
	var codes []string
	codes = append(codes, unit.CaptureSn)
	var list []model.ResponseCaptureVehicleTotal
	forCaptureIts := edge_service.ForCaptureIts{}
	forData, err := forCaptureIts.VehicleTotal(edge_service.ForCaptureItsReq{
		Codes: codes,
		Start: req.StartTime,
		End:   req.EndTime,
		Flag:  flag,
	})
	//fmt.Printf("forData = %v \n", forData)
	var countTimes []string
	if flag == 1 {
		countTimes = common.GetTimeMonths(req.StartTime, req.EndTime) //时间范围 月
	} else {
		countTimes = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	}
	for _, countTime := range countTimes {
		var countT int
		for _, datum := range forData {
			time := datum.Time
			if flag == 1 {
				time += "-01"
			}
			if time == countTime {
				countT = datum.Total
				continue
			}
		}
		list = append(list, model.ResponseCaptureVehicleTotal{
			CountTime: countTime,
			CountT:    countT,
		})
	}
	if err != nil {
		return nil, err
	}
	return list, nil
}

// GetSuggestSpeed 从数据库查抓拍单元风向
func (s captureService) GetSuggestSpeed(tenantId string, captureId int) (*dao.CaptureUnit, error) {
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       captureId,
	}
	if err := unit.GetDevice(); err != nil {
		return nil, err
	}
	return &unit, nil
}
