package org.springblade.device.controller;

import cn.hutool.core.collection.CollUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.device.entity.Gb28181Device;
import org.springblade.device.entity.GbDeviceChannel;
import org.springblade.device.service.IGbDeviceChannelService;
import org.springblade.device.service.IGbDeviceService;
import org.springblade.device.vo.GbDeviceStatisticsVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 监控设备统计
 * @author cy-computer
 */
@RestController
@AllArgsConstructor
@RequestMapping("/gbdevicestatistics")
@Api(value = "", tags = "接口")
public class GbDeviceStatisticsController extends BladeController {

	private final IGbDeviceService gbDeviceService;
	private final IGbDeviceChannelService gbDeviceChannelService;

	/**
	 * 监控设备统计【web端智能安防】
	 */
	@GetMapping("/stat")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "监控设备统计")
	public R<GbDeviceStatisticsVO> stat(BladeUser bladeUser){
		List<Gb28181Device> gbDeviceList = gbDeviceService.list();
		int deviceCnt = 0;
		int channelCnt = 0;
		int deviceOnlineCnt = 0;
		int deviceOfflineCnt = 0;
		int channelAlarmCnt = 0;
		deviceCnt = gbDeviceList.size();
		List<GbDeviceChannel> deviceChannelList = gbDeviceChannelService.selectByDeviceIds(gbDeviceList.stream().map(Gb28181Device::getDeviceId).collect(Collectors.toList()));
		channelCnt = deviceChannelList.size();
		List<Gb28181Device> deviceOnlineList = gbDeviceList.stream().filter(device -> device.getOnline() == 1).collect(Collectors.toList());
		List<Gb28181Device> deviceOfflineList = gbDeviceList.stream().filter(device -> device.getOnline() == 2).collect(Collectors.toList());
		deviceOnlineCnt = deviceOnlineList.size();
		deviceOfflineCnt = deviceOfflineList.size();
		List<GbDeviceChannel> channelAlarmList = deviceChannelList.stream().filter(channel -> channel.getIsAlarm() == 1).collect(Collectors.toList());
		channelAlarmCnt = channelAlarmList.size();
		return R.data(GbDeviceStatisticsVO.builder()
			.deviceCnt(deviceCnt)
			.channelCnt(channelCnt)
			.deviceOnlineCnt(deviceOnlineCnt)
			.deviceOfflineCnt(deviceOfflineCnt)
			.channelAlarmCnt(channelAlarmCnt)
			.build());
	}

}
