package service

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

var CaptureSpeedService = new(captureSpeedService)

type captureSpeedService struct{}

// GetList 车速统计
func (s captureSpeedService) GetList(tenantId string, req model.RequestCaptureFilter) (map[string]interface{}, error) {
	//sectionSpeed 区间车速数据
	data := make(map[string]interface{})
	speed, err := s.getSectionSpeed(tenantId, req)
	data["sectionSpeed"] = s.viewData(req, speed, "sectionSpeed")
	//overSpeed //超速数据
	speed, err = s.getOverSpeed(tenantId, req)
	data["overSpeed"] = s.viewData(req, speed, "overSpeed")
	return data, err
}

// 区间车速数据
func (s captureSpeedService) getSectionSpeed(tenantId string, req model.RequestCaptureFilter) ([]edge_service.ForCaptureItsData, error) {
	//区分按月或按日
	flag := 0
	if req.QueryType == "month" {
		flag = 1
	}
	//查出抓拍单元sn
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       req.CaptureId,
	}
	unit.GetDevice()
	var codes []string
	codes = append(codes, unit.CaptureSn)
	forCaptureIts := edge_service.ForCaptureIts{}
	speedTotal, err := forCaptureIts.VehicleSpeedTotal(edge_service.ForCaptureItsReq{
		Codes: codes,
		Start: req.StartTime,
		End:   req.EndTime,
		Flag:  flag,
	})
	if err != nil {
		return nil, err
	}
	return speedTotal, nil
}

// 超速数据
func (s captureSpeedService) getOverSpeed(tenantId string, req model.RequestCaptureFilter) ([]edge_service.ForCaptureItsData, error) {
	//区分按月或按日
	flag := 0
	if req.QueryType == "month" {
		flag = 1
	}
	//查出抓拍单元sn
	unit := dao.CaptureUnit{
		TenantId: tenantId,
		ID:       req.CaptureId,
	}
	unit.GetDevice()
	var codes []string
	codes = append(codes, unit.CaptureSn)
	forCaptureIts := edge_service.ForCaptureIts{}
	speedTotal, err := forCaptureIts.VehicleOverSpeedTotal(edge_service.ForCaptureItsReq{
		Codes: codes,
		Start: req.StartTime,
		End:   req.EndTime,
		Flag:  flag,
	})
	if err != nil {
		return nil, err
	}
	return speedTotal, nil
}

// 前端数据格式渲染
func (s captureSpeedService) viewData(req model.RequestCaptureFilter, speeds []edge_service.ForCaptureItsData, cate string) []model.ResponseCaptureSpeed {
	//区分按月或按日
	flag := 0
	if req.QueryType == "month" {
		flag = 1
	}
	data := make(map[string]int)
	for _, speed := range speeds {
		time := speed.Time
		if flag == 1 {
			time += "-01"
		}
		sflag := strconv.Itoa(speed.Sflag)
		data[time+"--"+sflag] += speed.Total
	}
	//时间范围内的月份或天的明细列表
	var countTimes []string
	if flag == 1 {
		countTimes = common.GetTimeMonths(req.StartTime, req.EndTime) //时间范围 月
	} else {
		countTimes = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	}
	var list []model.ResponseCaptureSpeed
	for _, time := range countTimes {
		if cate == "sectionSpeed" {
			list = append(list, model.ResponseCaptureSpeed{
				CountTime: time,
				V1:        data[time+"--0"],
				V2:        data[time+"--1"],
				V3:        data[time+"--2"],
				V4:        data[time+"--3"],
				V5:        data[time+"--4"],
				V6:        data[time+"--5"],
				V7:        data[time+"--6"],
			})
		} else {
			list = append(list, model.ResponseCaptureSpeed{
				CountTime: time,
				V11:       data[time+"--100"],
				V13:       data[time+"--101"],
				V14:       data[time+"--102"],
				V15:       data[time+"--103"],
				V16:       data[time+"--104"],
			})
		}
	}
	return list
}

// SyncOverSpeedRecord 同步超速车牌记录
func (s captureSpeedService) SyncOverSpeedRecord(start, end string) error {
	speed := operationDao.CaptureOverSpeed{}
	maxId, maxTime := speed.GetMaxIdAndUpDateTime()
	forCaptureIts := edge_service.ForCaptureIts{}
	record, err := forCaptureIts.SyncOverSpeedRecord(maxId, maxTime, start, end)
	if err != nil {
		return err
	}
	var list []operationDao.CaptureOverSpeed
	for _, data := range record {
		list = append(list, operationDao.CaptureOverSpeed{
			ID:        data.ID,
			CaptureSn: data.Code,
			Time:      common.Time(common.TimeStringToGoTime(data.Time)),
			Vtype:     data.Vtype,
			Plate:     data.Plate,
			Speed:     data.Speed,
			Sflag:     data.Flag,
		})
	}
	return speed.BatchCreate(list)
}

func (s captureSpeedService) GetOverSpeedRecord(req model.RequestCaptureOverSpeed) (*model.ResponseCaptureOverSpeedRecord, error) {
	//查出抓拍单元sn
	unit := dao.CaptureUnit{
		ID: req.CaptureId,
	}
	if req.Size <= 0 {
		req.Size = 10
	}
	unit.GetDevice()
	speed := operationDao.CaptureOverSpeed{}
	records, total, err := speed.Gets(unit.CaptureSn, req)
	if err != nil {
		return nil, err
	}
	pages := math.Ceil(float64(total) / float64(req.Size))
	return &model.ResponseCaptureOverSpeedRecord{
		Records: records,
		Current: req.Current,
		Size:    req.Size,
		Total:   total,
		Pages:   int(pages),
	}, nil
}
