package service

import (
	"errors"
	"fmt"
	"iot_manager_service/app/warn/dao"
	"iot_manager_service/config"
	"iot_manager_service/util/notify"
)

var TaskWarnService = new(taskWarnService)

// 定时任务处理的service
type taskWarnService struct {
}

// HandlingAlarms 报警处理
func (receiver taskWarnService) HandlingAlarms() {
	/*
		1. 查出平台 platformAlarmService.go 最近3天的 status = 0 未处理的 报警记录
		2. 根据报警 sn 查出设置的报警人相关信息，可能是多个报警方式
		3. 执行发短信或邮件逻辑，发送内容
		4. 保存相关日志到 noticeRecordService.go 下
	*/
	alarm, _ := PlatformAlarmService.GetNotNotifyAlarm(3)
	for _, platformAlarm := range alarm {
		sn := platformAlarm.ArmDeviceSn
		deviceType := platformAlarm.ArmDeviceType
		armSource := 1
		receiveList, _ := NoticeSetService.GetReceiveList(deviceType, sn, armSource)
		armSourceName := "运维"
		if armSource == 2 {
			armSourceName = "业务"
		}
		for _, receive := range receiveList {
			//告警内容拼装
			sendMsgFormat := "%v,您好：%v的%v于%v检测到%v,请确认并执行维护。"
			name := "【" + platformAlarm.LampPoleName + "】" + platformAlarm.ArmDeviceName
			sendMsg := fmt.Sprintf(sendMsgFormat, receive.UserName, platformAlarm.LampPoleLocation, name, platformAlarm.ArmTime, platformAlarm.ArmContent)
			sendErr := errors.New("")
			//去发送消息
			SendTypeName := "邮件"
			switch receive.NoticeMode {
			case 1:
				SendTypeName = "短信"
				sendErr = notify.SendTencentSms([]string{"+86" + receive.NoticeReceiveAccount}, config.Instance().MonitNotice.Sms.Tencent.WarnSmsTemplateID, []string{platformAlarm.LampPoleName, platformAlarm.LampPoleSn, platformAlarm.ArmContent})
			case 2:
				sendErr = notify.SendEmail(sendMsg, armSourceName+"通知", receive.NoticeReceiveAccount)
			}
			sendStatus := 1
			if sendErr != nil {
				sendStatus = 0
			}
			//保存消息记录
			dao.NoticeRecord{
				NoticeSetId:     receive.NoticeSetId,
				ArmClassify:     armSource,
				Content:         sendMsg,
				Status:          sendStatus,
				SendType:        receive.NoticeMode,
				SendTypeName:    SendTypeName,
				SendValue:       receive.NoticeReceiveAccount,
				SendName:        receive.UserName,
				PlatformAlarmId: platformAlarm.ID,
			}.Create()
			//标记已发送
			dao.PlatformAlarm{ID: platformAlarm.ID, Status: 1}.Update()
		}
	}
}
