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

// CaptureReportService 报表统计
var CaptureReportService = new(captureReportService)

type captureReportService struct{}

func (s captureReportService) GetList(tenantId string, req model.RequestCaptureReportFilter) ([]model.ResponseCaptureReport, error) {
	var list []model.ResponseCaptureReport
	//按日期  或 时段把每个类型的汇总 展示 出来
	flag, record, err := s.getData(tenantId, req)
	nlist := make(map[string]int)
	allTypes := []int{14, 26, 17, 10, 33, 25, 146, 8, 9}
	qcTypes := []int{14, 26, 17, 10, 33, 25, 146}
	allTotal := make(map[string]int)
	value8Total := make(map[string]int)
	for _, data := range record {
		key := data.Time[:10]
		if flag == 2 {
			key = data.Time[11:13]
		}
		vtype := strconv.Itoa(data.Vtype)
		nlist[key+vtype] += data.Total
		if common.InIntArr(data.Vtype, qcTypes) {
			value8Total[key] += data.Total
		}
		if common.InIntArr(data.Vtype, allTypes) {
			allTotal[key] += data.Total
		}
	}
	var countTimes []string
	if flag == 0 {
		//日
		countTimes = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	} else if flag == 2 {
		for i := 0; i < 24; i++ {
			ii := strconv.Itoa(i)
			if len(ii) < 2 {
				ii = "0" + ii
			}
			countTimes = append(countTimes, ii)
		}
	}
	//fmt.Printf("nlist = %v \n", nlist)
	//fmt.Printf("countTimes = %v \n", countTimes)
	//	types := []int{14, 26, 17, 10, 33, 25, 146, 8, 9}
	for _, countTime := range countTimes {
		list = append(list, model.ResponseCaptureReport{
			CountTime: countTime,
			Value1:    nlist[countTime+"14"],
			Value2:    nlist[countTime+"26"],
			Value3:    nlist[countTime+"17"],
			Value4:    nlist[countTime+"10"],
			Value5:    nlist[countTime+"33"],
			Value6:    nlist[countTime+"25"],
			Value7:    nlist[countTime+"146"],
			Value8:    value8Total[countTime],
			Value9:    nlist[countTime+"8"],
			Value10:   nlist[countTime+"9"],
			AllTotal:  allTotal[countTime],
		})
	}
	return list, err
}

//得到边缘接口 时间范围数据
func (s captureReportService) getData(tenantId string, req model.RequestCaptureReportFilter) (int, []edge_service.ForCaptureItsData, error) {
	//区分按月或按日
	flag := 1 //月
	if req.QueryType == 1 {
		flag = 2 //时
	}
	if req.QueryType == 2 {
		flag = 0 //日
	}

	//查出抓拍单元sn
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       req.CaptureId,
	}
	unit.GetDevice()
	var codes []string
	codes = append(codes, unit.CaptureSn)

	forCaptureIts := edge_service.ForCaptureIts{}
	var forData []edge_service.ForCaptureItsData
	var err error
	forData, err = forCaptureIts.Vehicletypeex(edge_service.ForCaptureItsReq{
		Codes: codes,
		Start: req.StartTime,
		End:   req.EndTime,
		Flag:  flag,
	})
	return flag, forData, err
}
