package dao

import (
	"errors"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"iot_manager_service/app/warn/model"
	"iot_manager_service/util/common"
	"time"
)

// PlatformAlarm 平台所有告警-来源边缘端接口
type PlatformAlarm struct {
	ID                int         `gorm:"comment:ID" json:"ID"`
	ArmClassify       int         `gorm:"column:arm_classify;type:int(11);comment:告警分类1运维2业务" json:"armClassify"` // 告警分类 1运维 2业务
	ArmDeviceType     int         `gorm:"column:arm_device_type;type:int(11);comment:设备类型1" json:"armDeviceType"` // 告警设备类型1摄像头2网关3灯控4配电5信息屏...15
	ArmDeviceTypeName string      `gorm:";comment:设备类型1" json:"armDeviceTypeName"`
	ArmDeviceId       int         `gorm:"column:arm_device_id;type:int(11);comment:设备id" json:"armDeviceId"`                // 告警设备id
	ArmDeviceName     string      `gorm:"column:arm_device_name;type:varchar(64);comment:设备名称" json:"armDeviceName"`        // 告警设备名称
	ArmDeviceSn       string      `gorm:"column:arm_device_sn;type:varchar(60);comment:设备编码" json:"armDeviceSn"`            // 告警设备编码
	LampPoleId        int         `gorm:"column:lamp_pole_id;type:int(11);comment:灯杆ID" json:"lampPoleId"`                  // 所属灯杆ID
	LampPoleName      string      `gorm:"column:lamp_pole_name;type:varchar(64);comment:灯杆名称" json:"lampPoleName"`          // 所属灯杆名称
	LampPoleSn        string      `gorm:"column:lamp_pole_sn;type:varchar(60);comment:灯杆唯一编码" json:"lampPoleSn"`            // 灯杆唯一编码
	LampPoleLocation  string      `gorm:"column:lamp_pole_location;type:varchar(255);comment:灯杆地址" json:"lampPoleLocation"` // 灯杆地址
	ArmSource         int         `gorm:"column:arm_source;type:int(11);comment:告警来源 1运维2业务" json:"armSource"`
	ArmTime           common.Time `gorm:"column:arm_time;type:datetime;comment:告警开始时间" json:"armTime"`                  // 告警开始时间
	ArmEndTime        common.Time `gorm:"column:arm_end_time;type:datetime;comment:告警结束时间" json:"armEndTime"`           // 告警结束时间
	ArmHandle         int         `gorm:"column:arm_handle;type:int(11);comment:当前处理状态1待处理2忽略3已处理4其他" json:"armHandle"` // 当前处理状态1待处理2忽略3已处理4其他
	ArmLevel          int         `gorm:"column:arm_level;type:int(11);comment: 告警类型 1紧急2严重3普通" json:"armLevel"`        // 告警类型 1紧急2严重3普通
	ArmContent        string      `gorm:"column:arm_content;type:varchar(255);comment:告警内容" json:"armContent"`          // 告警内容
	ArmUrl            string      `gorm:"column:arm_url;type:varchar(1000);comment:运维告警图片地址" json:"armUrl"`             // 运维告警图片地址
	ArmHanleRemark    string      `gorm:"column:arm_handle_remark;type:text;comment:处理内容" json:"armHanleRemark"`
	ArmHandleTime     common.Time `gorm:"column:arm_handle_time;type:datetime" json:"armHandleTime"` // 告警处理时间
	Status            int         `gorm:"column:status;type:int(11);comment:通知发送 1已发送 0未发送" json:"status"`
	TenantId          string      `gorm:"column:tenant_id;type:varchar(12);comment:租户ID" json:"tenantId"`                       // 租户ID
	ProcessInstanceId string      `gorm:"column:process_instance_id;type:varchar(255);comment:流程实例主键" json:"processInstanceId"` // 流程实例主键
	BusinessId        string      `gorm:"column:business_id;type:varchar(64);comment:流程实例主键ID" json:"businessId"`               // 流程实例主键ID
	Threshold         float64     `gorm:"column:threshold;type:float(11,2);comment:阈值-业务告警" json:"threshold"`                   // 阈值-业务告警
	Value             float64     `gorm:"column:value;type:float(11,2);comment:告警时的值-业务告警" json:"value"`                        // 告警时的值-业务告警
	Sid               int         `gorm:"column:sid;type:int(11);comment:物模型sid" json:"sid"`                                    // 物模型sid
	Cid               uint        `gorm:"column:cid;type:int(10) unsigned;comment:告警策略编号" json:"cid"`                           // 告警策略编号
	Cname             string      `gorm:"column:cname;type:varchar(100);comment:告警策略名称" json:"cname"`                           // 告警策略名称
	ExtendId          int         `gorm:"column:extend_id;type:int(11);comment:扩展id"json:"extendId"`                            // 扩展id
}

func (PlatformAlarm) TableName() string {
	return "warn_platform_alarm"
}

func (a PlatformAlarm) Gets(filter model.RequestPlatFormAlartFilter) ([]PlatformAlarm, int64, error) {
	var list []PlatformAlarm
	db := Db.Debug().Model(&a).Where(&PlatformAlarm{TenantId: a.TenantId})
	db = db.Scopes(common.Paginate(filter.Current, filter.Size))
	if filter.ArmHandle > 0 {
		handle := filter.ArmHandle
		db = db.Where(&PlatformAlarm{ArmHandle: handle})
	}
	if filter.ArmDeviceType > 0 {
		db = db.Where(&PlatformAlarm{ArmDeviceType: filter.ArmDeviceType})
	}
	if filter.ArmDeviceName != "" {
		db = db.Where(&PlatformAlarm{ArmDeviceName: filter.ArmDeviceName})
	}
	if filter.ArmSource != 0 {
		db = db.Where(&PlatformAlarm{ArmSource: filter.ArmSource})
	}
	err := db.Order("id desc").Find(&list).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	var count int64
	db.Count(&count)
	//fmt.Printf("count = %v", count)
	return list, count, err
}

func (a PlatformAlarm) GetMaxIdAndUpDateTime() (int64, string) {
	var platformAlarm PlatformAlarm
	Db.Debug().Where(&PlatformAlarm{TenantId: a.TenantId}).Last(&platformAlarm)
	return int64(platformAlarm.ID), platformAlarm.ArmTime.String()
}

func (a PlatformAlarm) BatchCreate(his []PlatformAlarm) error {
	db := Db.Debug()
	db = db.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "ID"}}, //  这里的列必须是唯一的，比如主键或是唯一索引
	})
	return db.CreateInBatches(his, 1000).Error
}

func (a PlatformAlarm) Update() error {
	err := Db.Debug().Model(&a).Updates(a).Error
	return err
}

func (a PlatformAlarm) GetWarnCount() (int64, error) {
	var count int64
	nowTime := time.Now()
	getTime := nowTime.AddDate(0, 0, -30)
	err := Db.Debug().Model(&a).Where(&PlatformAlarm{
		TenantId:      a.TenantId,
		ArmDeviceType: a.ArmDeviceType,
		ArmHandle:     1,
	}).Where("arm_time>?", getTime).Count(&count).Error
	return count, err
}

func (a PlatformAlarm) GetsAlarmByTime(start string) ([]PlatformAlarm, error) {
	var list []PlatformAlarm
	err := Db.Debug().Model(&a).Where("status=0 and arm_time>?", start).Find(&list).Order("id desc").Error
	return list, err
}
