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

// 中间件管理服务
var CameraService = new(cameraService)

type cameraService struct{}

func (s *cameraService) CreateOrUpdate(userId int64, tenantId string, req *model.CameraDetail) *common.Errors {
	device := req.CameraDevice
	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
			device.GroupId = lampPole.GroupId
		} 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.DeviceTypeCamera, common.GetDeviceObject(device.ID, device.DeviceName), 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.DeviceTypeCamera, common.GetDeviceObject(device.ID, device.DeviceName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

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

	detail := &model.CameraDetail{CameraDevice: *device}
	if device.CameraType == model.CameraTypeBall {
		detail.CameraTypeName = model.CameraTypeBallName
	} else if device.CameraType == model.CameraTypeGun {
		detail.CameraTypeName = model.CameraTypeGunName
	}

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

func (s *cameraService) List(searchValue, cameraType string, current, size int) ([]model.CameraDetail, int64, *common.Errors) {
	var details []model.CameraDetail
	device := dao.CameraDevice{}

	if searchValue != "" {
		device.DeviceSN = searchValue
	}
	if cameraType != "" {
		t, _ := strconv.Atoi(cameraType)
		device.CameraType = t
	} else {
		device.CameraType = -1
	}

	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 {
		endTime, state := cache.GetDeviceState(d.DeviceSN)
		details = append(details, model.CameraDetail{
			CameraDevice: d,
			RunState:     state,
			NetworkState: state,
			EndLineTime:  endTime,
		})
	}

	return details, total, nil
}

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

func (s *cameraService) GetList(tenantId string, ) ([]dao.CameraDevice, *common.Errors) {
	device := &dao.CameraDevice{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err := device.GetAllDevices()
	var results []dao.CameraDevice
	// todo 不要返回多余字段，只需要id和name
	for _, device := range devices {
		results = append(results, dao.CameraDevice{ID: device.ID, DeviceName: device.DeviceName + "(" + device.DeviceSN + ")"})
	}
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}

	return results, nil
}

func (s *cameraService) Enable(id, status int) *common.Errors {
	// 创建查询实例
	device := &dao.CameraDevice{
		ID:       id,
		IsEnable: status,
	}

	err := device.UpdateEnable()
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return nil
}

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

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

func (s *cameraService) GetByLampPoleGroup(id int) []dao.CameraDevice {
	// 创建查询实例
	device := &dao.CameraDevice{
		GroupId: id,
	}
	return device.GetDevicesByLampPoleGroup()
}
