package service

import (
	"fmt"
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/device/model"
	"iot_manager_service/app/system/service"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"iot_manager_service/util/logger"
	"time"
)

// 中间件管理服务
var AlarmService = new(alarmService)

type alarmService struct{}

func (s *alarmService) Get(id int) (*dao.Alarm, *common.Errors) {
	// 创建查询实例
	device := &dao.Alarm{
		ID: id,
	}
	err := device.GetDevice()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	device.CountRel = int(dao.AlarmTerminal{}.GetTerminalCount(device.ID))
	return device, nil
}

func (s *alarmService) CreateOrUpdate(userId int64, tenantId string, req dao.Alarm) *common.Errors {
	device := req
	device.TenantId = tenantId
	device.UpdateUser = userId
	device.UpdateTime = time.Now()

	if req.ID == 0 {
		device.CreateTime = time.Now()
		device.CreateUser = userId

		if device.IsExistedBySN() {
			logger.Logger.Errorf("Create IsExistedBySN \n")
			return common.ParamsInvalidResponse(model.RepeatedName, nil)
		}
		if err := device.Create(); err != nil {
			logger.Logger.Errorf("Create err = %s \n", err.Error())
			return common.FailResponse(err.Error(), nil)
		}
		service.OperationHisService.Save(userId, tenantId, common.OperationCreate, common.ModuleTypeDevice,
			common.DeviceTypeAlarmServer, common.GetDeviceObject(device.ID, device.ServeName), common.OperationSuccess)
		return common.SuccessResponse(common.Succeeded, nil)
	}

	if device.IsExistedByNameAndCode() {
		logger.Logger.Errorf("Update IsExistedByNameAndCode \n")
		return common.ParamsInvalidResponse(model.RepeatedName, nil)
	}
	fmt.Printf("device = %v", device)
	if err := device.Update(); err != nil {
		logger.Logger.Errorf("Update err = %s \n", err.Error())
		return common.FailResponse(err.Error(), nil)
	}

	service.OperationHisService.Save(userId, tenantId, common.OperationUpdate, common.ModuleTypeDevice,
		common.DeviceTypeAlarmServer, common.GetDeviceObject(device.ID, device.ServeName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

func (s *alarmService) List(poleGroupName string, current, size int) ([]dao.Alarm, int64, *common.Errors) {
	// 创建查询实例
	device := &dao.Alarm{}
	offset := (current - 1) * size
	limit := size
	devices, total, err := device.GetDevices(offset, limit)
	if err != nil {
		return nil, 0, common.FailResponse(err.Error(), nil)
	}
	for i, alarm := range devices {
		devices[i].CountRel = int(dao.AlarmTerminal{}.GetTerminalCount(alarm.ID))
	}
	return devices, total, nil
}

func (s *alarmService) Remove(userId int64, tenantId string, id int) *common.Errors {
	// 创建查询实例
	device := &dao.Alarm{
		ID:         id,
		IsDeleted:  1,
		UpdateUser: userId,
		UpdateTime: time.Now(),
	}
	err := device.Delete()
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	service.OperationHisService.Save(userId, tenantId, common.OperationRemove, common.ModuleTypeDevice,
		common.DeviceTypeAlarmServer, common.GetDeviceObject(device.ID, device.ServeName), common.OperationSuccess)
	return nil
}

func (s *alarmService) GetList(tenantId string, ) ([]*dao.Alarm, *common.Errors) {
	var devices []*dao.Alarm
	err := cache.Redis.Get(getAlarmListRedisKey(tenantId)).Scan(&devices)
	if err == nil {
		return devices, nil
	}
	device := &dao.Alarm{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err = device.GetAllDevices()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	_ = cache.Redis.Set(getAlarmListRedisKey(tenantId), devices, 0).Err()
	return devices, nil
}

func getAlarmListRedisKey(tenantId string, ) string {
	return fmt.Sprintf(model.AlarmList, tenantId)
}
