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"
	"strconv"
)

// CaptureCarRecordService 货车记录
var CaptureCarRecordService = new(captureCarRecordService)

type captureCarRecordService struct{}

var (
	MediumTruckVType int = 26 //中型货车
	BigTruckVType    int = 17 //大型货车
)

func (s captureCarRecordService) GetCarRecordCount(tenantId string, req model.RequestCarRecordCountFilter) (*model.ResponseCarRecordAll, error) {
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       req.CaptureId,
	}
	unit.GetDevice()
	var codes []string
	codes = append(codes, unit.CaptureSn)
	forCaptureIts := edge_service.ForCaptureIts{}
	vtypes := []int{MediumTruckVType, BigTruckVType}
	if req.CarModel == 1 {
		vtypes = []int{MediumTruckVType}
	} else if req.CarModel == 2 {
		vtypes = []int{BigTruckVType}
	}
	forData, err := forCaptureIts.Vehicleplate(
		edge_service.ForCaptureItsReq{
			Types: vtypes, //中型货车 大货车
			Codes: codes,
			Start: req.StartTime,
			End:   req.EndTime,
		})
	if err != nil {
		return nil, err
	}
	var countTimes []string
	if req.QueryType == "month" {
		countTimes = common.GetTimeMonths(req.StartTime, req.EndTime) //时间范围 月
	} else {
		countTimes = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	}
	data := make(map[string]int)
	for _, datum := range forData {
		key := string(datum.Time[:10])
		if req.QueryType == "month" {
			key = string(datum.Time[:7]) + "-01"
		}
		vtype := strconv.Itoa(datum.Vtype)
		data[key+vtype] += 1
	}
	var list []model.ResponseCarRecordCount
	var totalCountN, totalCountT int
	for _, countTime := range countTimes {
		key := countTime
		vtype26 := strconv.Itoa(MediumTruckVType)
		vtype17 := strconv.Itoa(BigTruckVType)
		list = append(list, model.ResponseCarRecordCount{
			NowDate: countTime,
			CountN:  data[key+vtype17],
			CountT:  data[key+vtype26],
		})
		totalCountN += data[key+vtype17]
		totalCountT += data[key+vtype26]
	}
	return &model.ResponseCarRecordAll{
		CarRecordCount: list,
		CarModelCount:  model.ResponseCarModelCount{totalCountN, totalCountT},
		Details:        forData,
	}, nil
}
