package dao

import "iot_manager_service/app/operation/model"

type Alarm struct {
	TenantId        string
	DeviceType      int    `gorm:"column:arm_device_type"` //设备类型
	Count           int    //总数
	NotHandlerCount int    //未处理报警
	CountTime       string `json:"countTime"` //统一时间
}

func (a Alarm) TableName() string {
	return "warn_platform_alarm"
}

func (a Alarm) Gets(req model.RequestAlarmFilter) ([]Alarm, error) {
	var list []Alarm
	countTimeFormat := "%Y-%m-%d"
	if req.QueryType == "month" {
		countTimeFormat = "%Y-%m"
	}
	deviceType := ""
	if a.rewirteDeviceType(req.QueryDeviceType) != "" {
		deviceType = " arm_device_type as device_type,"
	}
	sql := "SELECT count(*) AS count, date_format( arm_time, '" + countTimeFormat + "' ) AS count_time, " + deviceType + " sum(if(arm_handle=1, 1,0)) as not_handler_count FROM warn_platform_alarm WHERE "
	where := " arm_time>=? and arm_time<=?"
	if a.rewirteDeviceType(req.QueryDeviceType) != "" {
		where = " arm_time>=? and arm_time<=? and arm_device_type=" + a.rewirteDeviceType(req.QueryDeviceType)
	}
	sql += where
	group := " group by count_time"
	if a.rewirteDeviceType(req.QueryDeviceType) != "" {
		group = " GROUP BY count_time,device_type"
	}
	sql += group
	sql += " order by count_time desc"
	err := Db.Debug().Raw(sql, req.StartTime, req.EndTime).Scan(&list).Error
	return list, err
}

//重写前端传过来的数据，由于前端修改工程大，先这样处理了
func (a Alarm) rewirteDeviceType(queryDeviceType string) string {
	switch queryDeviceType {
	case "count":
		return ""
	case "camera":
		return "1" //摄像机
	case "gateway":
		return "2" //网关
	case "lightcontrol":
		return "3" //灯控
	case "infoboard":
		return "5" //信息屏
	case "sensor":
		return "6" //环境监测
	case "zigbee":
		return "7" //集控器
	case "terminal":
		return "8" //一键告警终端
	case "capture":
		return "12" //抓拍单元
	case "bridgesensor": //雪水传感器
		return "13"
	case "ipcast":
		return "14" //IP音柱
	}
	return ""
}
