package service

import (
	"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 AlarmTerminalService = new(alarmTerminalService)

type alarmTerminalService struct{}

func (s *alarmTerminalService) Get(id int) (*model.AlarmTerminalDetail, *common.Errors) {
	// 创建查询实例
	device := &dao.AlarmTerminal{
		ID: id,
	}
	err := device.GetDevice()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	endTime, state := cache.GetDeviceState(device.TerminalSN)
	return &model.AlarmTerminalDetail{
		AlarmTerminal: *device,
		RunState:      state,
		NetworkState:  state,
		EndLineTime:   endTime,
	}, nil
}

func (s *alarmTerminalService) CreateOrUpdate(userId int64, tenantId string, req dao.AlarmTerminal) *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.DeviceTypeAlarmTerminal, common.GetDeviceObject(device.ID, device.TerminalName), common.OperationSuccess)
		return common.SuccessResponse(common.Succeeded, nil)
	}

	if device.IsExistedByNameAndCode() {
		logger.Logger.Errorf("Update IsExistedByNameAndCode \n")
		return common.ParamsInvalidResponse(model.RepeatedName, nil)
	}

	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.DeviceTypeAlarmTerminal, common.GetDeviceObject(device.ID, device.TerminalName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

func (s *alarmTerminalService) List(poleGroupName string, current, size int) ([]model.AlarmTerminalDetail, int64, *common.Errors) {
	// 创建查询实例
	device := &dao.AlarmTerminal{}
	offset := (current - 1) * size
	limit := size
	devices, total, err := device.GetDevices(offset, limit)
	if err != nil {
		return nil, 0, common.FailResponse(err.Error(), nil)
	}
	var details []model.AlarmTerminalDetail
	for _, d := range devices {
		endTime, state := cache.GetDeviceState(d.TerminalSN)
		details = append(details, model.AlarmTerminalDetail{
			AlarmTerminal: d,
			RunState:      state,
			NetworkState:  state,
			EndLineTime:   endTime,
		})
	}
	return details, total, nil
}

func (s *alarmTerminalService) Remove(userId int64, tenantId string, id int) *common.Errors {
	// 创建查询实例
	device := &dao.AlarmTerminal{
		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.DeviceTypeAlarmTerminal, common.GetDeviceObject(device.ID, device.TerminalName), common.OperationSuccess)
	return nil
}

func (s *alarmTerminalService) GetByGateway(id int) []dao.AlarmTerminal {
	// 创建查询实例
	device := &dao.AlarmTerminal{
		GatewayId: id,
	}
	return device.GetDevicesByGateway()
}

func (s *alarmTerminalService) GetByLampPole(id int) []dao.AlarmTerminal {
	// 创建查询实例
	device := &dao.AlarmTerminal{
		LampPoleId: id,
	}
	return device.GetDevicesByLampPole()
}
