package service

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

var LightingRateService = new(lightingRateService)

type lightingRateService struct{}

func (s lightingRateService) GetDayList(tenantId string, req model.RequestLightingRateFilter) ([]model.ResponseLightingRate, error) {
	return s.getData("day", tenantId, req)
}

func (s lightingRateService) GetMonthList(tenantId string, req model.RequestLightingRateFilter) ([]model.ResponseLightingRate, error) {
	return s.getData("month", tenantId, req)
}

// 公用请求边缘端数据，月和日
func (s lightingRateService) getData(method string, tenantId string, req model.RequestLightingRateFilter) ([]model.ResponseLightingRate, error) {
	lightControl := dao.Operation{
		TenantId: tenantId,
	}
	codes, err := lightControl.GetSnList()
	if err != nil {
		return nil, err
	}
	flag := 1  //能耗请求类型：按天
	flag2 := 0 //亮灯率请求类型：按天
	if method == "month" {
		flag = 2  //能耗请求类型：按天
		flag2 = 1 //亮灯率请求类型：按月
	}
	//能耗
	forLightEnergy := edge_service.ForLightEnergy{}
	lightEnergys, err := forLightEnergy.GetLightEnergy(edge_service.ForLightEnergyReq{
		Codes: codes,
		Start: req.StartTime,
		End:   req.EndTime,
		Flag:  flag,
	})
	if err != nil {
		return nil, err
	}
	//亮灯率
	forLightRate := edge_service.ForLightRate{}
	lightRates, err := forLightRate.GetLightRate(edge_service.ForLightRateReq{
		Tenant: tenantId,
		Start:  req.StartTime,
		End:    req.EndTime,
		Flag:   flag2,
	})
	if err != nil {
		return nil, err
	}
	var list []model.ResponseLightingRate
	//fmt.Printf("LightEnergys = %v", LightEnergys)
	var months []string
	if method == "month" {
		months = common.GetTimeMonths(req.StartTime, req.EndTime) //时间范围 月
	} else {
		months = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	}
	//fmt.Printf("months = %v \n", months)
	for _, month := range months {
		// 能耗数据汇总
		var monthEnergyNum float64 //能耗
		for _, LightEnergy := range lightEnergys {
			for _, data := range LightEnergy {
				if month == data.Date {
					monthEnergyNum += data.Difference
				}
			}
		}
		//亮灯率
		var lightingRate float64
		var lightControlNum, lightingNum int
		for _, rate := range lightRates {
			date := rate.Date
			if method == "month" {
				date = rate.Month + "-01"
			}
			if date == month {
				lightingRate += rate.Rate     //亮灯率
				lightControlNum += rate.Total //灯数
				lightingNum += rate.Number    //亮灯数
			}
		}
		//组合数据到前端接口展示
		list = append(list, model.ResponseLightingRate{
			CountTime:       month,
			EnergyNum:       common.Decimal(monthEnergyNum),
			LightingRate:    common.Decimal(lightingRate),
			LightControlNum: lightControlNum,
			LightingNum:     lightingNum,
		})
	}
	return list, nil
}
