package service

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

var AlarmService = new(alarmService)

type alarmService struct{}

func (s alarmService) GetDayList(tenantId string, req model.RequestAlarmFilter) ([]model.ResponseAlarm, error) {
	return s.getData("day", tenantId, req)
}

func (s alarmService) GetMonthList(tenantId string, req model.RequestAlarmFilter) ([]model.ResponseAlarm, error) {
	return s.getData("month", tenantId, req)
}

func (s alarmService) getData(method string, tenantId string, req model.RequestAlarmFilter) ([]model.ResponseAlarm, error) {
	alarmDao := dao.Alarm{TenantId: tenantId}
	alarms, err := alarmDao.Gets(req) //取报警数据

	var countDates []string
	if method == "month" {
		countDates = common.GetTimeMonths(req.StartTime, req.EndTime) //时间范围 月
	} else {
		countDates = common.GetTimeDays(req.StartTime, req.EndTime) //时间范围 天
	}
	//fmt.Printf("alarms = %v \n", alarms)
	//数据按时间范围 填充
	var list []model.ResponseAlarm
	for _, countDate := range countDates {
		//初始化所需数据
		var deviceType, count, notHandlerCount int
		for _, alarm := range alarms {
			date := alarm.CountTime
			if method == "month" {
				date = alarm.CountTime + "-01"
			}
			//如果是当当天数据，则赋值
			if date == countDate {
				deviceType = alarm.DeviceType
				count = alarm.Count
				notHandlerCount = alarm.NotHandlerCount
			}
		}
		list = append(list, model.ResponseAlarm{
			CountTime:    countDate,
			DeviceType:   strconv.Itoa(deviceType),
			CountT:       count,
			CountUnsolve: notHandlerCount,
			CountSolve:   count - notHandlerCount,
		})
	}
	if err != nil {
		return nil, err
	}
	return list, nil
}
