package dao

import (
	"fmt"
	"gorm.io/gorm"
	"iot_manager_service/app/warn/model"
	"iot_manager_service/util/common"
)

// NoticeRecord 告警通知记录
type NoticeRecord struct {
	gorm.Model
	NoticeSetId     int `gorm:"comment:告警通知设置ID;" json:"noticeSetId"`
	NoticeSet       NoticeSet
	ArmClassify     int    `gorm:"comment:告警类型：1运维，2业务;" json:"classify"`
	Content         string `gorm:"comment:发送内容;" json:"content"`
	Status          int    `gorm:"comment:发送状态;" json:"status"`
	SendType        int    `gorm:"comment:发送方式1短信2邮件" json:"sendType"`
	SendTypeName    string `gorm:"comment:发送方式" json:"SendTypeName"`
	SendValue       string `gorm:"comment:手机号或邮件" json:"sendValue"`
	SendName        string `gorm:"comment:收件人" json:"sendName"`
	PlatformAlarmId int
	PlatformAlarm   PlatformAlarm
}

func (NoticeRecord) TableName() string {
	return "warn_notice_record"
}

func (r NoticeRecord) GetList(filter model.RequestNoticeRecordFilter) ([]NoticeRecord, int64, error) {
	var list []NoticeRecord
	var total int64
	db := Db.Debug().Model(&r)
	// 告警类型
	if filter.ClassifyName != 0 {
		db = db.Where(&NoticeRecord{ArmClassify: filter.ClassifyName})
	}
	//发送状态
	if filter.SendValue != 0 {
		if filter.SendValue == 2 { //1成功 2为失败
			filter.SendValue = 0
		}
		db = db.Where(&NoticeRecord{Status: filter.SendValue})
	}
	//发送方式
	if filter.SendType != 0 {
		db = db.Where(&NoticeRecord{SendType: filter.SendType})
	}
	//时间范围
	if filter.StartTime != "" {
		db = db.Where("created_at>=? and created_at<=?", filter.StartTime, filter.EndTime)
	}
	//发送人
	if filter.SendName != "" {
		db = db.Where("send_name=?", filter.SendName)
	}
	db.Count(&total)
	db = db.Scopes(common.Paginate(filter.Current, filter.Size)).Preload("NoticeSet")

	err := db.Preload("PlatformAlarm").Order("id desc").Find(&list).Error

	fmt.Printf("total = %v", total)
	return list, total, err
}

func (r NoticeRecord) Create() error {
	err := Db.Debug().Create(&r).Error
	return err
}
