package service

import (
	system "iot_manager_service/app/system/dao"
	"iot_manager_service/app/warn/dao"
	edgeService "iot_manager_service/app/warn/edge_service"
	"iot_manager_service/app/warn/model"
	"iot_manager_service/util/common"
	"time"
)

var PlatformAlarmService = new(platformAlarmService)

type platformAlarmService struct{}

// GetList 报警列表
func (s platformAlarmService) GetList(tenantId string, filter model.RequestPlatFormAlartFilter) ([]model.PlatFormAlartData, int64, error) {
	var list []model.PlatFormAlartData
	dao := dao.PlatformAlarm{
		TenantId: tenantId,
	}
	levelArr := make(map[int]string)
	levelArr[1] = "紧急"
	levelArr[2] = "严重"
	levelArr[3] = "普通"
	gets, i, err := dao.Gets(filter)
	for _, alart := range gets {
		list = append(list, model.PlatFormAlartData{
			ID:                alart.ID,
			ArmDeviceName:     alart.ArmDeviceName,
			ArmDeviceSn:       alart.ArmDeviceSn,
			ArmDeviceTypeName: alart.ArmDeviceTypeName,
			ArmContent:        alart.ArmContent,
			LampPoleName:      alart.LampPoleName,
			LampPoleSn:        alart.LampPoleSn,
			ArmTime:           alart.ArmTime.String(),
			ArmEndTime:        alart.ArmEndTime.String(),
			ArmLevel:          alart.ArmLevel,
			ArmLevelName:      levelArr[alart.ArmLevel],
			LampPoleLocation:  alart.LampPoleLocation,
			ArmHandleTime:     alart.ArmHandleTime.String(),
			OpsStatus:         alart.ArmHandle,
		})
	}
	return list, i, err
}

func (s platformAlarmService) SyncAlarm() {
	//抓取数据
	tenant := system.Tenant{}
	tenants, _, _ := tenant.GetTenants(0, 1000)
	for _, t := range tenants {
		s.Refresh(t.TenantId)
	}
}

// Refresh 同步边缘接口报警数据
func (s platformAlarmService) Refresh(tenantId string) error {
	viewDao := dao.ViewsAllCode{TenantId: tenantId}
	alls, err := viewDao.GetAlls()
	if err != nil {
		return err
	}
	newAllCode := make(map[string]dao.ViewsAllCode)
	for _, viewsAllCode := range alls {
		if viewsAllCode.Sn != "" {
			newAllCode[viewsAllCode.Sn] = viewsAllCode
		}
	}
	edgeService := edgeService.RecordAlarmRecord{}
	maxId, maxUpDateTime := dao.PlatformAlarm{}.GetMaxIdAndUpDateTime()
	list, err := edgeService.SyncAlartRecord(maxId, maxUpDateTime)
	if err != nil {
		return err
	}
	alarms := []dao.PlatformAlarm{}
	for _, data := range list {
		viewInfo := newAllCode[data.Code]
		parse := common.TimeStringToGoTime(data.Tend)
		ArmTime := common.TimeStringToGoTime(data.Tstart)
		ArmSource := 1
		if data.Cid != 0 {
			ArmSource = 2
		}
		alarms = append(alarms, dao.PlatformAlarm{
			ID:                data.ID,
			TenantId:          tenantId,
			ArmDeviceType:     viewInfo.DeviceType,
			ArmDeviceTypeName: viewInfo.DeviceTypeName,
			ArmDeviceId:       viewInfo.DeviceId,
			ArmDeviceName:     viewInfo.DeviceName,
			ArmDeviceSn:       data.Code,
			LampPoleId:        viewInfo.LampPoleId,
			LampPoleName:      viewInfo.LampPoleName,
			LampPoleSn:        viewInfo.LampPoleSn,
			LampPoleLocation:  viewInfo.Address,
			ArmSource:         ArmSource,
			ArmEndTime:        common.Time(parse),
			ArmTime:           common.Time(ArmTime),
			ArmHandle:         1,
			ArmLevel:          data.Level,
			ArmContent:        data.Content,
			Status:            0, //告警发送
			Cid:               uint(data.Cid),
			Cname:             data.Cname,
			Sid:               data.Sid,
			Threshold:         float64(data.Threshold),
		})
	}
	err = dao.PlatformAlarm{}.BatchCreate(alarms)
	return err

}

// HandleAlarm 告警处理
func (s platformAlarmService) HandleAlarm(tenant_id string, id int, armHandle int, remark string) error {
	dao := dao.PlatformAlarm{
		ID:             id,
		ArmHandle:      armHandle,
		ArmHanleRemark: remark,
		ArmHandleTime:  common.Time(time.Now()),
	}
	return dao.Update()
}

// GetWarnCount 根据设备类型 取
func (s platformAlarmService) GetWarnCount(tenantId string, deviceType int) (int64, error) {
	alarm := dao.PlatformAlarm{TenantId: tenantId, ArmDeviceType: deviceType}
	return alarm.GetWarnCount()
}

// GetNotNotifyAlarm 返回最近几天没有发送告警通知的警告
func (s platformAlarmService) GetNotNotifyAlarm(day int) ([]dao.PlatformAlarm, error) {
	start := time.Now().AddDate(0, 0, -day).Format("2006-01-02- 15:04:05")
	return dao.PlatformAlarm{}.GetsAlarmByTime(start)
}
