package com.yeejoin.precontrol.controller.hk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectCamera;
import com.yeejoin.precontrol.common.entity.ProjectDevice;
import com.yeejoin.precontrol.common.entity.hk.model.dto.HKRequestDto;
import com.yeejoin.precontrol.common.entity.hk.model.vo.VideoTreeVo;
import com.yeejoin.precontrol.common.entity.hk.model.vo.VideoVo;
import com.yeejoin.precontrol.common.service.IProjectCameraService;
import com.yeejoin.precontrol.common.service.IProjectDeviceService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.hk.HkPlatFormService;
import com.yeejoin.precontrol.common.utils.PlatformUtils;
import com.yeejoin.precontrol.common.vo.hik.HKResult;
import com.yeejoin.precontrol.common.vo.hik.Online;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: songLei
 * @Description: 视频监控控制器
 * @Date: 2021/5/10 9:19
 * @Version: 1.0
 */
@RequestMapping("/videoSurveillance")
@RestController
public class VideoSurveillanceController {
	@Autowired
	private IProjectService projectService;
	@Autowired
	private HkPlatFormService hkPlatFormService;
	@Autowired
	PlatformUtils platformUtils;
	@Autowired
	private IProjectCameraService projectCameraService;

	@GetMapping("/projectIPage")
	public IPage<Project> projectIPage(Page page, String name) {
		String orgCode = platformUtils.getOrgCode();
		LambdaQueryWrapper<Project> wapper = new QueryWrapper<Project>().lambda().isNotNull(Project::getProjectRegion)
				.like(Project::getName, name).orderByAsc(Project::getName);
		if (orgCode != null) {
			wapper.likeRight(Project::getOrgCode, orgCode);
		}
		return projectService.page(page, wapper);
	}

	@GetMapping("/getTree")
	public Object getTree(Boolean isOnLine, Long projectId) {
		String orgCode = platformUtils.getOrgCode();
		LambdaQueryWrapper<Project> warpper;
		if (StringUtils.isBlank(orgCode)) {
			warpper = new QueryWrapper<Project>().lambda().isNotNull(Project::getProjectRegion)
					.orderByAsc(Project::getName);
		} else {
			warpper = new QueryWrapper<Project>().lambda().likeRight(Project::getOrgCode, orgCode)
					.isNotNull(Project::getProjectRegion).orderByAsc(Project::getName);
		}
		if (!StringUtils.isEmpty(orgCode)) {
			warpper.like(Project::getOrgCode, orgCode);
		}
		if (projectId != null) {
			warpper.like(Project::getId, projectId);
		}
		List<Project> projects = projectService.list(warpper);
		List<VideoTreeVo> treeVoList = new ArrayList<>();
		VideoTreeVo vo = new VideoTreeVo();
		vo.setType("-1");
		vo.setCode("0");
		vo.setId(0l);
		vo.setName("项目列表");
		List<VideoTreeVo> treeVos = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(projects)) {
			projects.stream().forEach(item -> {
				VideoTreeVo treeVo = new VideoTreeVo();
				treeVo.setName(item.getName());
				treeVo.setCode(item.getProjectNum());
				treeVo.setId(item.getId());
				treeVo.setParentId("-1");
				treeVo.setType("1");
				List<ProjectCamera> projectDevices = projectCameraService.list(new QueryWrapper<ProjectCamera>()
						.lambda().eq(ProjectCamera::getRegionIndexCode, item.getProjectRegion())
						.orderByAsc(ProjectCamera::getChannelNo));
				HKRequestDto dtoV = new HKRequestDto();
				dtoV.setPageNo(1);
				dtoV.setPageSize(1000);
				dtoV.setRegionIndexCode(item.getProjectRegion());
				List<HKResult> hkResults = (List<HKResult>) hkPlatFormService.getMonitoringPointChildren(dtoV);
				List<String> indexCodes = new ArrayList<>();
				projectDevices.stream().forEach(pc -> {
					pc.setCameraName(
							hkResults.stream().filter(y -> y.getCameraIndexCode().equals(pc.getCameraIndexCode()))
									.findFirst().get().getCameraName());
					indexCodes.add(pc.getCameraIndexCode());
				});
				HKRequestDto dto = new HKRequestDto();
				dto.setPageNo(1);
				dto.setPageSize(1000);
				dto.setIndexCodes(indexCodes);
				List<Online> onlines = hkPlatFormService.getIsOnline(dto);
				List<VideoTreeVo> treeVosChildren = new ArrayList<>();
				if (CollectionUtils.isNotEmpty(projectDevices)) {
					projectDevices.stream().forEach(O -> {
						VideoTreeVo tree = new VideoTreeVo();
						tree.setName(O.getCameraName());
						tree.setCode(O.getCameraIndexCode());
						tree.setId(O.getId());
						tree.setParentId(item.getId().toString());
						tree.setType("2");
						Integer on = onlines.stream().filter(x -> x.getIndexCode().equals(O.getCameraIndexCode()))
								.findFirst().get().getOnline();
						tree.setOnline(on);
						if (isOnLine && 1 != tree.getOnline()) {

						} else {
							treeVosChildren.add(tree);
						}
					});
				}
				treeVo.setChildren(treeVosChildren);
				treeVos.add(treeVo);
			});
			vo.setChildren(treeVos);
			treeVoList.add(vo);
		}
		return treeVoList;
	}

	@GetMapping("/videoPage")
	public IPage<VideoVo> videoPage(Page page, VideoTreeVo vo) {
		String orgCode = platformUtils.getOrgCode();
		List<Project> projects = projectService.list(
				new QueryWrapper<Project>().lambda().eq(StringUtils.isNotBlank(orgCode), Project::getOrgCode, orgCode)
						.isNotNull(Project::getProjectRegion));
		String projectRegion = projects.stream().filter(a -> StringUtils.isNotBlank(a.getProjectRegion())).findFirst()
				.get().getProjectRegion();
		IPage<VideoVo> videoVoIPage = new Page<>();
		IPage<ProjectCamera> cameraIPage;
		if (StringUtils.isNotBlank(vo.getType())) {
			if (vo.getType().equals("-1")) {
				cameraIPage = projectCameraService.page(page, new QueryWrapper<ProjectCamera>().lambda()
						.eq(ProjectCamera::getRegionIndexCode, projectRegion));
			} else if (vo.getType().equals("1")) {
				Project project = projectService.getById(vo.getId());
				cameraIPage = projectCameraService.page(page, new QueryWrapper<ProjectCamera>().lambda()
						.eq(ProjectCamera::getRegionIndexCode, project.getProjectRegion()));
			} else {
				cameraIPage = projectCameraService.page(page,
						new QueryWrapper<ProjectCamera>().lambda().eq(ProjectCamera::getId, vo.getId()));
			}
		} else {
			cameraIPage = projectCameraService.page(page,
					new QueryWrapper<ProjectCamera>().lambda().eq(ProjectCamera::getRegionIndexCode, projectRegion));
		}

		if (CollectionUtils.isNotEmpty(cameraIPage.getRecords())) {
			List<VideoVo> videoVos = new ArrayList<>();

			Map<String, List<HKResult>> hkMap = new HashMap<>();

			cameraIPage.getRecords().stream().forEach(item -> {
				HKRequestDto dtoV = new HKRequestDto();
				dtoV.setPageNo(1);
				dtoV.setPageSize(1000);
				dtoV.setRegionIndexCode(item.getRegionIndexCode());
				List<HKResult> hkResults = hkMap.get(item.getRegionIndexCode());
				if (hkResults == null) {
					hkResults = (List<HKResult>) hkPlatFormService.getMonitoringPointChildren(dtoV);
					hkMap.put(item.getRegionIndexCode(), hkResults);
				}
				HKRequestDto dto = new HKRequestDto();
				dto.setCameraIndexCode(item.getCameraIndexCode());
				Map<String, String> path = (Map<String, String>) hkPlatFormService.getMonitoringPointPreviewURL(dto);
				String url = path.get("url");
				VideoVo videoVo = new VideoVo();
				videoVo.setCode(item.getCameraIndexCode());
				videoVo.setId(item.getId());
				videoVo.setName(hkResults.stream().filter(y -> y.getCameraIndexCode().equals(item.getCameraIndexCode()))
						.findFirst().get().getCameraName());
				// https://img.jinsom.cn/user_files/14871/publish/video/14794405_1619619953.mp4
				videoVo.setUrl(url);
				videoVo.setToken("true");
				Integer on = hkResults.stream().filter(x -> x.getCameraIndexCode().equals(videoVo.getCode()))
						.findFirst().get().getOnline();
				if (vo.getOnline() == 1 && on != 1) {

				} else {
					videoVos.add(videoVo);
				}
			});
			BeanUtils.copyProperties(cameraIPage, videoVoIPage);
			videoVoIPage.setRecords(videoVos);
		}
		return videoVoIPage;
	}
}
