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 GatewayService = new(gatewayService)

type gatewayService struct{}

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

	detail := &model.GatewayDetail{Gateway: *device}

	relation, e := GatewayRelationService.Get(id)
	if e == nil {
		detail.CountLampPole = relation.Total
	} else {
		logger.Logger.Errorf("GatewayRelationService.Get err = %v", err)
	}

	endTime, state := cache.GetDeviceState(device.GatewaySn)
	detail.RunState = state
	detail.EndLineTime = endTime
	detail.NetworkState = state
	return detail, nil
}

func (s *gatewayService) CreateOrUpdate(userId int64, tenantId string, req *model.GatewayDetail) *common.Errors {
	device := req.Gateway
	device.TenantId = tenantId
	device.UpdateUser = userId
	device.UpdateTime = time.Now()
	if device.LampPoleId != 0 {
		lampPole, err := LampPoleService.GetOne(device.LampPoleId)
		if err == nil {
			device.LampLat = lampPole.PoleLat
			device.LampLng = lampPole.PoleLng
			device.LampPoleName = lampPole.PoleName
			device.LampPoleSn = lampPole.PoleSN
			device.LampPoleLocation = lampPole.InstallLocation
		} else {
			logger.Logger.Errorf("LampPoleService.GetOne err = %v \n", err)
		}
	}

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

func (s *gatewayService) List(searchValue string, current, size int) ([]model.GatewayDetail, int64, *common.Errors) {
	var details []model.GatewayDetail
	device := dao.Gateway{}

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

	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 _, d := range devices {
		detail := model.GatewayDetail{Gateway: d}
		relation, _ := GatewayRelationService.Get(d.ID)

		//fmt.Printf("d.ID = %v", d.ID)
		//查数据
		relation2 := dao.GatewayRelation{
			ID: d.ID,
		}
		relation2.Update() //临时 处理

		if relation != nil {
			detail.CountLampPole = relation.Total
		}

		endTime, state := cache.GetDeviceState(d.GatewaySn)
		detail.RunState = state
		detail.EndLineTime = endTime
		detail.NetworkState = state
		details = append(details, detail)
	}
	return details, total, nil
}

func (s *gatewayService) Remove(userId int64, tenantId string, id int) *common.Errors {
	// 创建查询实例
	device := &dao.Gateway{
		ID:         id,
		IsDeleted:  1,
		UpdateUser: userId,
		UpdateTime: time.Now(),
	}

	if relation, _ := GatewayRelationService.Get(id); relation != nil && relation.Total > 0 {
		return common.OperationInvalidResponse(model.GatewayHasRelation, nil)
	}

	err := device.Delete()
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	service.OperationHisService.Save(userId, tenantId, common.OperationRemove, common.ModuleTypeDevice,
		common.DeviceTypeGateway, common.GetDeviceObject(device.ID, device.GatewayName), common.OperationSuccess)
	return nil
}

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

	device := &dao.Gateway{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err = device.GetAllDevices()
	for _, device := range devices {
		device.GatewayName = device.GatewayName + "(" + device.GatewaySn + ")"
	}
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	_ = cache.Redis.Set(getGatewayListRedisKey(tenantId), devices, 0).Err()

	return devices, nil
}

func getGatewayListRedisKey(tenantId string, ) string {
	return fmt.Sprintf(model.GatewayList, tenantId)
}

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

	return &model.GatewayDetail{
		Gateway:           *device,
		AlarmTerminalList: AlarmTerminalService.GetByGateway(device.ID),
		CameraList:        CameraService.GetByGateway(device.ID),
		CaptureUnitList:   CaptureUintService.GetCaptureByGateway(device.ID),
		InfoBoardList:     InfoBoardService.GetByGateway(device.ID),
		IpBroadcastList:   IpBroadcastService.GetByGateway(device.ID),
		LightControlList:  LightControlService.GetByGateway(device.ID),
		OptoSensorList:    OptoSensorService.GetByGateway(device.ID),
		ZigbeeList:        ZigbeeService.GetByGateway(device.ID),
	}, nil
}

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

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