package com.lutao.cloud.oil.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.StringUtil;
import com.lutao.cloud.oil.mapper.VideoEquipmentInfoMapper;
import com.lutao.cloud.oil.pojo.entity.VideoInfo;
import com.lutao.cloud.oil.pojo.param.BaseParam;
import com.lutao.cloud.oil.pojo.vo.*;
import com.lutao.cloud.oil.service.VideoEquipmentInfoService;
import com.lutao.cloud.oil.service.VideoInfoService;
import com.lutao.entity.VideoEquipmentInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VideoEquipmentInfoServiceImpl extends ServiceImpl<VideoEquipmentInfoMapper, VideoEquipmentInfo> implements VideoEquipmentInfoService {

    @Resource
    private VideoInfoService videoInfoService;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public MessageInfo<List<VideoEquipmentInfoTreeVO>> queryVideoEquipmentInfoTree() {

        List<VideoEquipmentInfoTreeVO> videoEquipmentInfoTreeVOS = new ArrayList<>();

        List<VideoEquipmentInfoBaseVO> videoEquipmentInfoBaseVOS = this.baseMapper.queryVideoEquipmentInfoTree();
        //构造树
        videoEquipmentInfoBaseVOS.stream().collect(Collectors.groupingBy(VideoEquipmentInfoBaseVO::getAppName)).forEach((k, v) -> {
            List<PlatformVideoVO> platformVideoVOS = new ArrayList<>();
            VideoEquipmentInfoTreeVO videoEquipmentInfoTreeVO = new VideoEquipmentInfoTreeVO();
            videoEquipmentInfoTreeVO.setAppName(k);


            v.stream().filter(item -> item.getPlatformName() != null).collect(Collectors.groupingBy(VideoEquipmentInfoBaseVO::getPlatformName)).forEach((k1, v1) -> {
                List<CameraVO> cameraNames = new ArrayList<>();
                PlatformVideoVO platformVideoVO = new PlatformVideoVO();
                platformVideoVO.setPlatformName(k1);
                v1.forEach(videoEquipmentInfoBaseVO -> {
                    CameraVO cameraVO = new CameraVO();
                    cameraVO.setId(videoEquipmentInfoBaseVO.getId());
                    cameraVO.setCameraName(videoEquipmentInfoBaseVO.getCameraName());
                    cameraVO.setCameraIndex(videoEquipmentInfoBaseVO.getCameraIndex());
                    cameraVO.setOnlineStatus(videoEquipmentInfoBaseVO.getOnlineStatus());
                    cameraNames.add(cameraVO);
                });
                platformVideoVO.setCameraNames(cameraNames);
                platformVideoVOS.add(platformVideoVO);
            });

            videoEquipmentInfoTreeVO.setPlatformVideoVOS(platformVideoVOS);
            videoEquipmentInfoTreeVOS.add(videoEquipmentInfoTreeVO);
        });

        return MessageInfo.ok(videoEquipmentInfoTreeVOS);
    }

    @Override
    public MessageInfo<List<VideoEquipmentInfoTreeVO>> queryVideoEquipmentInfoTreeV2() {
        List<VideoEquipmentInfoBaseVO> videoEquipmentInfoBaseVOS = this.baseMapper.queryVideoEquipmentInfoTree();
        return null;
    }

    @Override
    public MessageInfo<List<VideoInfoNode>> queryVideoEquipmentInfoTreeNew(BaseParam param) {


        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("zhonghaiyou", "中海油");
        paramMap.put("zhongshiyou", "中石油");
        paramMap.put("zhongshihua", "中石化");
        String appName = paramMap.get(param.getAppId());

        //所有视频信息
        List<VideoInfo> videoInfos = videoInfoService.list();

        Map<String, VideoInfoNode> nodeMap = new HashMap<>();
        List<VideoInfoNode> rootNodes = new ArrayList<>();
        Map<String, List<VideoInfo>> cameraMap = new HashMap<>();

        // 创建所有的节点并存入 map
        for (VideoInfo videoInfo : videoInfos) {
            if (videoInfo.getIndexCode() != null) {
                VideoInfoNode node = new VideoInfoNode();
                node.setVideoInfo(videoInfo);
                node.setChildren(new ArrayList<>());
                nodeMap.put(videoInfo.getIndexCode(), node);
            } else if (videoInfo.getCameraIndexCode() != null) {
                String parentIndexCode = videoInfo.getParentIndexCode();
                if (!cameraMap.containsKey(parentIndexCode)) {
                    cameraMap.put(parentIndexCode, new ArrayList<>());
                }
                cameraMap.get(parentIndexCode).add(videoInfo);
            }
        }

        // 将视频信息添加到对应的平台节点下
        for (Map.Entry<String, List<VideoInfo>> entry : cameraMap.entrySet()) {
            String parentIndexCode = entry.getKey();
            List<VideoInfo> cameras = entry.getValue();
            VideoInfoNode parentNode = nodeMap.get(parentIndexCode);
            if (parentNode != null) {
                for (VideoInfo camera : cameras) {
                    VideoInfoNode cameraNode = new VideoInfoNode();
                    cameraNode.setVideoInfo(camera);
                    parentNode.getChildren().add(cameraNode);
                }
            }
        }

        // 构建树形结构
        for (VideoInfoNode node : nodeMap.values()) {
            VideoInfoNode parentNode = nodeMap.get(node.getVideoInfo().getParentIndexCode());
            if (parentNode == null) {
                if (StringUtil.isNotBlank(appName)){
                    if (appName.equals(node.getVideoInfo().getName())){
                        rootNodes.add(node);
                    }
                }else {
                    rootNodes.add(node);
                }
            } else {
                parentNode.getChildren().add(node);
            }
        }

        return MessageInfo.ok(rootNodes);
    }

    @Override
    public MessageInfo getVideoUrl(String videoCode) {
        // 获取token
        String url = "http://10.18.17.85:9090/oauth/token?client_id=2d24b314552f460ab74a5e3b891b1646&client_secret=cbb8b46a7f014b158eefb3542ec66c2d";
        Map<String, String> map = restTemplate.getForObject(url, Map.class);
        System.out.println("map:" + map);
        String token = map.get("access_token");

        // 请求数据
        String url2 = "http://10.18.17.85:9090/service/api/api/v1/cameras/previewURLs?client_id=2d24b314552f460ab74a5e3b891b1646&access_token=" + token;
        Map<String, String> parameters = new LinkedHashMap<>();
        parameters.put("cameraIndexCode", videoCode);
        parameters.put("protocol", "ws");
        MessageInfo result = restTemplate.postForObject(url2, JSONObject.toJSONString(parameters), MessageInfo.class);
        // ws地址转化，从10段到59段
//        Map<String, String> data = result.getData();
//        if (data != null) {
//            String wsUrl = data.get("url");
//            String replace;
//
//            // 解决院网不能播放视频问题
//            replace = wsUrl.replace("10.18.18.53:559", "59.255.61.152:80/ws");
//
//            // 地址转换 10.18.18.53 -> 59.255.61.78
//            // replace = wsUrl.replace("10.18.18.53", "59.255.61.78");
//
//            data.put("url", replace);
//            result.setData(data);
//        }
        return result;

    }
}
