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 CaptureUintService = new(captureUintService)

type captureUintService struct{}

func (s *captureUintService) CaptureSubmit(userId int64, tenantId string, req *model.CaptureDetail) *common.Errors {
	device := req.CaptureUnit
	device.TenantId = tenantId
	device.UpdateUser = userId
	device.UpdateTime = time.Now()
	if gateway, err := GatewayService.GetOne(device.GatewayId); err == nil {
		device.GatewayName = gateway.GatewayName
		device.GatewaySn = gateway.GatewaySn
	}

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

func (s *captureUintService) GetCapture(id int) (*model.CaptureDetail, *common.Errors) {
	// 创建查询实例
	device := &dao.CaptureUnit{
		ID: id,
	}
	err := device.GetDevice()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	detail := &model.CaptureDetail{CaptureUnit: *device}
	endTime, state := cache.GetDeviceState(device.CaptureSn)
	detail.NetworkState = state
	detail.EndLineTime = endTime

	return detail, nil
}

func (s *captureUintService) CaptureList(searchValue string, current, size int) ([]model.CaptureDetail, int64, *common.Errors) {
	var details []model.CaptureDetail
	device := dao.CaptureUnit{}

	if searchValue != "" {
		device.CaptureSn = 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 {
		endTime, state := cache.GetDeviceState(d.CaptureSn)
		details = append(details, model.CaptureDetail{
			CaptureUnit:  d,
			EndLineTime:  endTime,
			NetworkState: state,
		})
	}

	return details, total, nil
}

func (s *captureUintService) CaptureGetList(tenantId string, ) ([]*dao.CaptureUnit, *common.Errors) {
	device := &dao.CaptureUnit{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err := device.GetAllDevices()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	for _, d := range devices {
		d.CaptureName = d.CaptureName + "(" + d.CaptureSn + ")"
	}
	return devices, nil
}

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

	return device, nil
}

func (s *captureUintService) PointSubmit(userId int64, tenantId string, req *dao.CheckPoint) *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.DeviceTypePoint, common.GetDeviceObject(device.ID, device.PointName), 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.DeviceTypePoint, common.GetDeviceObject(device.ID, device.PointName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

func (s *captureUintService) PointList(searchValue string, current, size int) ([]dao.CheckPoint, int64, *common.Errors) {
	device := dao.CheckPoint{}
	if searchValue != "" {
		device.PointSN = 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)
	}
	return devices, total, nil
}

func (s *captureUintService) PointGetList(tenantId string, ) ([]*dao.CheckPoint, *common.Errors) {
	device := &dao.CheckPoint{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err := device.GetAllDevices()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	for _, d := range devices {
		d.PointName = d.PointName + "(" + d.PointSN + ")"
	}
	return devices, nil
}

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

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

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

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