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"
	"strconv"
	"time"
)

// 中间件管理服务
var OnDemandGroupService = new(onDemandGroupService)

type onDemandGroupService struct{}

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

	return device, nil
}

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

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

		if device.IsExistedBySN() {
			logger.Logger.Errorf("Create IsExistedBySN \n")
			return common.ParamsInvalidResponse(model.RepeatedPrompts, nil)
		}
		logger.Logger.Errorf("device = %+v \n", device)
		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.PoleGroupName), common.OperationSuccess)
		return common.SuccessResponse(common.Succeeded, 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.DeviceTypeAlarmServer, common.GetDeviceObject(device.ID, device.PoleGroupName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

func (s *onDemandGroupService) List(searchValue string, current, size int) ([]dao.OnDemandGroup, *common.Errors) {
	device := dao.OnDemandGroup{}

	if searchValue != "" {
		device.PoleGroupName = searchValue
	}

	offset := (current - 1) * size
	limit := size
	devices, err := device.GetDevices(offset, limit)
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	return devices, nil
}

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

func (s *onDemandGroupService) GetList(tenantId string, ) ([]*dao.OnDemandGroup, *common.Errors) {
	var devices []*dao.OnDemandGroup
	err := cache.Redis.Get(getOnDemandGroupListRedisKey(tenantId)).Scan(&devices)
	if err == nil {
		return devices, nil
	}

	device := &dao.OnDemandGroup{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err = device.GetAllDevices()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	_ = cache.Redis.Set(getOnDemandGroupListRedisKey(tenantId), devices, 0).Err()

	return devices, nil
}

func getOnDemandGroupListRedisKey(tenantId string, ) string {
	return fmt.Sprintf(model.OnDemandGroupList, tenantId)
}

func (s *onDemandGroupService) GroupNumberList(id int) ([]model.RspOnDemandGroupNumber, *common.Errors) {
	// 创建查询实例
	device := &dao.OnDemandGroup{
		ID: id,
	}
	err := device.GetDevice()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	var list []model.RspOnDemandGroupNumber
	for i := 1; i <= device.LampPoleCount; i++ {
		list = append(list, model.RspOnDemandGroupNumber{Name: strconv.Itoa(i), Value: i})
	}

	return list, nil
}
