package service

import (
	"errors"
	systemService "iot_manager_service/app/system/service"
	"iot_manager_service/app/warn/dao"
	"iot_manager_service/app/warn/model"
	"strconv"
)

//业务 策略 告警 TODO: 这里需要对接边缘接口
var BusinessTacticsService = new(businessTacticsService)

type businessTacticsService struct{}

func (s businessTacticsService) GetList(tenantId string, filter model.RequestBusinessTacticFilter) ([]dao.BusinessTactics, int64, error) {
	tactics := dao.BusinessTactics{TenantId: tenantId}
	businessTactics, i, err := tactics.Gets(filter)
	for i2, tactic := range businessTactics {
		idStr := strconv.Itoa(tactic.DeviceType)
		businessTactics[i2].DeviceTypeName = systemService.DictService.GetCacheDict("device_type"+idStr, "device_type", tactic.DeviceType)
		id2Str := strconv.Itoa(tactic.AlarmType)
		businessTactics[i2].AlarmTypeName = systemService.DictService.GetCacheDict("business_alarm_type2"+id2Str, "business_alarm_type2", tactic.AlarmType)
	}
	return businessTactics, i, err
}

func (s businessTacticsService) SaveOrUpdate(tenantId string, d model.RequestBusinessSubmit) error {
	MaxValue, _ := strconv.ParseFloat(d.MaxValue, 64)
	MinValue, _ := strconv.ParseFloat(d.MinValue, 64)
	Duration, _ := strconv.Atoi(d.Duration)
	tactics := dao.BusinessTactics{
		AlarmType:    d.AlarmType,
		DeviceType:   d.DeviceType,
		BusinessName: d.BusinessName,
		MaxValue:     MaxValue,
		MinValue:     MinValue,
		Duration:     Duration,
		IsEnable:     1,
		TenantId:     tenantId,
	}
	err := errors.New("default")
	if d.ID == 0 {
		err = tactics.Create()
	} else {
		if d.Status == 2 {
			tactics.IsEnable = 2
		}
		err = tactics.Update(d.ID)
	}
	return err
}

func (s businessTacticsService) Remove(tenantId string, id int) error {
	tactics := dao.BusinessTactics{TenantId: tenantId}
	return tactics.Delete(id)
}
