package service

import (
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/device/edge_service"
	"iot_manager_service/app/device/model"
	"iot_manager_service/app/system/service"
	"iot_manager_service/util/common"
	"iot_manager_service/util/logger"
	"time"
)

var IpBroadcastService = new(ipBroadcastService)

type ipBroadcastService struct{}

func (s *ipBroadcastService) Get(id int) (*model.IpBroadcastDetail, *common.Errors) {
	// 创建查询实例
	device := &dao.IpBroadcast{
		ID: id,
	}
	err := device.GetDevice()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	terms, err := edge_service.IpCastControlService{}.GetTermIds()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}
	//endTime, state := cache.GetDeviceState(device.CastSn)
	info, ok := terms[device.CastSn]
	state := "2"
	if ok {
		device.PlayState = "不在线"
		if info.Online == 1 {
			state = "1"
			device.SoundVolume = info.Vol
			device.IPAddress = info.IP
			device.PlayState = "空闲"
			if info.State == 2 {
				device.PlayState = "文件广播[" + info.From + "]"
			}
		}
	}

	return &model.IpBroadcastDetail{
		IpBroadcast:  *device,
		RunState:     state,
		NetworkState: state,
		//EndLineTime:  endTime,
	}, nil
}

func (s *ipBroadcastService) CreateOrUpdate(userId int64, tenantId string, req dao.IpBroadcast) *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 GetDeviceID err \n")
			return common.ParamsInvalidResponse("编码不能重复，请重新填写！", 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.DeviceTypeIPBroadcast, common.GetDeviceObject(device.ID, device.CastName), common.OperationSuccess)
		return common.SuccessResponse(common.Succeeded, nil)
	}
	if device.IsExistedByNameAndCode() {
		return common.ParamsInvalidResponse("编码不能重复，请重新填写！", 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.DeviceTypeIPBroadcast, common.GetDeviceObject(device.ID, device.CastName), common.OperationSuccess)
	return common.SuccessResponse(common.Succeeded, nil)
}

func (s *ipBroadcastService) List(searchValue string, current, size int) ([]model.IpBroadcastDetail, int64, *common.Errors) {
	device := dao.IpBroadcast{}
	terms, err := edge_service.IpCastControlService{}.GetTermIds()
	if err != nil {
		return nil, 0, nil
	}
	if searchValue != "" {
		device.CastSn = searchValue
		device.CastName = 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)
	}
	var details []model.IpBroadcastDetail
	for _, d := range devices {
		//endTime, state := cache.GetDeviceState(d.CastSn)
		info, ok := terms[d.CastSn]
		state := "2"
		if ok {
			d.PlayState = "不在线"
			if info.Online == 1 {
				state = "1"
				d.SoundVolume = info.Vol
				d.IPAddress = info.IP
				d.PlayState = "空闲"
				if info.State == 2 {
					d.PlayState = "文件广播[" + info.From + "]"
				}
			}
		}
		details = append(details, model.IpBroadcastDetail{
			IpBroadcast:  d,
			RunState:     state,
			NetworkState: state,

			//EndLineTime:  endTime,
		})
	}
	return details, total, nil
}

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

func (s *ipBroadcastService) GetList(tenantId string) ([]dao.IpBroadcast, *common.Errors) {
	device := &dao.IpBroadcast{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	devices, err := device.GetAllDevices()
	if err != nil {
		return nil, common.FailResponse(err.Error(), nil)
	}

	return devices, nil
}

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

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

func (s *ipBroadcastService) GetAll(tenantId string) []dao.IpBroadcast {
	device := &dao.IpBroadcast{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	return device.GetAll()
}

func (s *ipBroadcastService) GetByIds(tenantId string, ids string) []dao.IpBroadcast {
	device := &dao.IpBroadcast{
		TenantId:  tenantId,
		IsDeleted: 0,
	}
	return device.GetByIds(ids)
}
