package service

import (
	"errors"
	device "iot_manager_service/app/device/dao"
	"iot_manager_service/app/operation/dao"
	"iot_manager_service/app/operation/model"
	"iot_manager_service/util/common"
	"time"
)

var AepCallbackRecordService = new(aepCallbackRecordService)

type aepCallbackRecordService struct{}

func (s *aepCallbackRecordService) Save(data model.AepCallbackPayload, timestamp int64) error {
	datatime := time.Unix(timestamp/1000, 0)
	imei := data.IMEI
	deviceId, err := device.ManholeCover{}.FindDeviceIdByImei(imei)
	if err != nil {
		return errors.New("没有添加这个imei的设备" + imei)
	}

	record := dao.ManholeCoverDao{
		CSQ:          data.CSQ,
		IMEI:         data.IMEI,
		ICCID:        data.ICCID,
		Temperature:  data.Temperature,
		LeanAngle:    data.LeanAngle,
		BatteryLevel: data.BatteryLevel,
	}
	record.DeviceId = deviceId
	record.PostTime = common.Time(datatime)
	record.CreateDate = datatime.Format("2006-01-02")

	manholeCover := device.ManholeCover{
		ID:           deviceId,
		Temperature:  data.Temperature,
		LeanAngle:    data.LeanAngle,
		BatteryLevel: data.BatteryLevel,
		Csq:          data.CSQ,
		LastPostTime: common.Time(datatime),
	}
	err = manholeCover.Update()
	if err != nil {
		return errors.New(imei + "更新井盖的参数失败" + err.Error())
	}
	return record.Save()
}

func (s *aepCallbackRecordService) GetByDeviceId(deviceId int) (dao.ManholeCoverDao, error) {
	var record dao.ManholeCoverDao
	record.DeviceId = deviceId
	err := record.Get()
	if err != nil {
		return dao.ManholeCoverDao{}, err
	}
	return record, nil
}

func (s *aepCallbackRecordService) GetHistoryList(deviceId int, queryStartDate, queryEndDate, queryType string) ([]model.ManholeHistoryList, error) {
	var record dao.ManholeCoverDao
	record.DeviceId = deviceId
	records, err := record.GetList(queryStartDate, queryEndDate)
	if err != nil {
		return nil, err
	}
	var list []model.ManholeHistoryList
	for _, coverDao := range records {
		var value interface{}
		if queryType == "temp" {
			value = coverDao.Temperature
		} else if queryType == "battery" {
			value = coverDao.BatteryLevel
		} else if queryType == "csq" {
			value = coverDao.CSQ
		} else if queryType == "lean_angle" {
			value = coverDao.LeanAngle
		}
		list = append(list, model.ManholeHistoryList{
			Name:  coverDao.CreateDate,
			Value: value,
		})
	}

	return list, nil
}
