package service

import (
	"fmt"
	"iot_manager_service/app/data/dao"
	"iot_manager_service/app/data/service"
	dataService "iot_manager_service/app/data/service"
	deviceService "iot_manager_service/app/device/service"
	"iot_manager_service/app/operation/model"
	"iot_manager_service/util/common"
	"time"
)

var EnvironmentService = new(environmentService)

type environmentService struct{}

func (s *environmentService) EnvironmentList(tenantId string) ([]model.EnvironmentDetail, *common.Errors) {
	var result []model.EnvironmentDetail
	devices := deviceService.OptoSensorService.GetByTenant(tenantId)
	for _, d := range devices {
		detail := model.EnvironmentDetail{CreateDate: d.CreateTime, Name: d.Name, Sn: d.Sn}
		data := dataService.EnvironmentDataService.Get(d.ID)
		detail.CreateDate = data.PostTime
		if data != nil {
			detail.EnvironmentData = *data
		}
		lampPole, _ := deviceService.LampPoleService.GetOne(d.LampPoleId)
		if lampPole != nil {
			detail.LampPoleLocation = lampPole.InstallLocation
			detail.LampLat = fmt.Sprintf("%f", lampPole.PoleLat)
			detail.LampLng = fmt.Sprintf("%f", lampPole.PoleLng)

			detail.RealTimeWindSpeed = common.CalculateSpeed(fmt.Sprintf("%.2f", detail.WindSpeed/100)) //风力等级
		}
		result = append(result, detail)
	}
	return result, nil
}

func (s *environmentService) Get(id int) (model.EnvironmentDetail, *common.Errors) {
	var result model.EnvironmentDetail
	device := deviceService.OptoSensorService.GetOne(id)
	if device == nil {
		return result, nil
	}
	detail := model.EnvironmentDetail{CreateDate: device.CreateTime, Name: device.Name, Sn: device.Sn, LampPoleLocation: device.LampPoleLocation}
	data := dataService.EnvironmentDataService.Get(device.ID)
	if data != nil {
		detail.EnvironmentData = *data
	}

	return detail, nil
}

func (s *environmentService) GetHistoryData(id int, scope string, queryType int, start,
	end time.Time) ([]dao.EnvironmentData, error) {
	isDay := 0
	if scope == "day" {
		isDay = 1
	}
	data, err := service.EnvironmentDataService.GetData(id, isDay, start, end)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (s *environmentService) GetScopeData(id int, scope string, queryType int) (interface{}, error) {
	isDay := 0
	if scope == "day" {
		isDay = 1
	}
	data, err := service.EnvironmentDataService.GetScopeData(id, isDay, queryType)
	if err != nil {
		return nil, err
	}
	return data, nil
}
