package dao

import (
	"errors"
	"gorm.io/gorm"
)

// NoticeSet 告警通知设置
type NoticeSet struct {
	gorm.Model
	TenantId            string `gorm:"comment:租户;default:0" json:"_"`                     //租户
	DeviceType          int    `gorm:"comment:设备类型;default:0" json:"deviceType"`          //设备类型1-15
	DeviceId            int    `gorm:"comment:设备ID;default:0" json:"deviceId"`            //设备ID
	DeviceSn            string `gorm:"comment:设备sn;" json:"sn"`                           //设备sn
	RType               int    `gorm:"comment:发送类型：0 - 全部 1按设备 2设备ID;" json:"deviceType"` //发送类型：0 - 全部设备 1 按设备类型 2按设备ID
	DevUserIds          string `gorm:"comment:运维通知人员;" json:"devUserIds"`                 //运维通知人员
	BusinessUserIds     string `gorm:"comment:业务通知人员;" json:"businessUserIds"`            //业务通知人员
	DevUserNoticeModes  string `gorm:"comment:运维通知方式;" json:"devUserNoticeModes"`         //运维通知方式 1短信 2邮件
	BusinessNoticeModes string `gorm:"comment:业务通知方式;" json:"businessNoticeModes"`        //业务通知方式 1短信 2邮件+

	DevUserNoticeModesName  string `json:"showOperationTypeName"`
	BusinessNoticeModesName string `json:"showBusinessTypeName"`
	DevUserIdsName          string `json:"noticeOperationName"`
	BusinessUserIdsName     string `json:"noticeBusinessName"`
}

func (NoticeSet) TableName() string {
	return "warn_notice_set"
}

func (s *NoticeSet) UpdateOrSave() error {
	noticeSet := NoticeSet{}
	db := Db.Debug().Model(&noticeSet)
	var err error
	switch s.RType {
	case 1:
		err = db.Where(&NoticeSet{RType: 1, TenantId: s.TenantId}).First(&noticeSet).Error
	case 2:
		err = db.Where(&NoticeSet{RType: 2, TenantId: s.TenantId, DeviceType: s.DeviceType}).First(&noticeSet).Error
	case 3:
		err = db.Where(&NoticeSet{RType: 3, TenantId: s.TenantId, DeviceType: s.DeviceType, DeviceId: s.DeviceId}).First(&noticeSet).Error
	default:
		return errors.New("没有Rtype")
	}
	if noticeSet.ID == 0 {
		err = Db.Debug().Model(&noticeSet).Save(s).Error
	} else {
		err = Db.Debug().Model(&noticeSet).Updates(s).Error
	}
	return err
}

func (s NoticeSet) GetList() ([]NoticeSet, error) {
	var list []NoticeSet
	err := Db.Debug().Model(&s).Where(&NoticeSet{TenantId: s.TenantId}).Find(&list).Error
	return list, err
}

func (s NoticeSet) GetById() (NoticeSet, error) {
	var data NoticeSet
	err := Db.Debug().Model(&s).Where(&NoticeSet{DeviceSn: s.DeviceSn}).First(&data).Error
	return data, err
}

func (s *NoticeSet) Delete() error {
	err := Db.Debug().Where(&NoticeSet{
		DeviceSn: s.DeviceSn,
	}).Delete(&s).Error
	return err
}

// GetNoticeList 返回告警接收人全部信息
func (s NoticeSet) GetNoticeList(deviceType int, sn string) ([]NoticeSet, error) {
	var list []NoticeSet
	err := Db.Debug().Where("device_sn=999999").Or("device_type=?", deviceType).Or("device_sn=?", sn).Find(&list).Error
	//fmt.Printf("err = %v \n", err)
	return list, err
}
