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

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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 lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class VideoEquipmentInfoServiceImpl extends ServiceImpl<VideoEquipmentInfoMapper, VideoEquipmentInfo> implements VideoEquipmentInfoService {

    @Resource
    private VideoInfoService videoInfoService;

    @Resource
    private RestTemplate restTemplate;

    private static final String TOKEN_URL = "http://dgs-servicebusgate2.zww.yjcloud.cn/oauth/token";
    private static final String previewURLs = "http://dgs-servicebusgate2.zww.yjcloud.cn/service/api/artemis/api/video/v1/cameras/previewURLs";

    private static final String CLIENT_ID = "8a7b785f08d04d439b71bc2b415cb685";
    private static final String CLIENT_SECRET = "OA!Bq_P!";
    private static final String CONTENT_TYPE = "application/json";

    @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
        log.info("获取视频地址");
        String token = getAccessToken();
        cn.hutool.json.JSONObject newRequestBody = JSONUtil.createObj();
        newRequestBody.set("cameraIndexCode", videoCode);
        newRequestBody.set("protocol", "wss");

        String rootBody = HttpUtil.createPost(previewURLs)
                .header("client_id", CLIENT_ID)
                .header("access_token", token)
                .body(newRequestBody.toString())
                .execute().body();
        /**
         * {
         * 	"code": "0",
         * 	"msg": "SUCCESS",
         * 	"data": {
         * 		"url": "wss://10.210.114.45:6014/proxy/10.210.114.45:559/openUrl/r8jroqY"
         *        }
         * }
         */



        String url = "";

        cn.hutool.json.JSONObject data = JSONUtil.parseObj(rootBody).getJSONObject("data");



        if (data != null) {
            String wsUrl = data.getStr("url");
            String replace = wsUrl;

            // 解决院网不能播放视频问题
            replace = replace.replace("10.210.114.45", "splw1.mem.cegn.cn");
            replace = replace.replace("10.210.114.46", "splw2.mem.cegn.cn");
            replace = replace.replace("10.210.114.47", "splw3.mem.cegn.cn");

            // 地址转换 10.18.18.53 -> 59.255.61.78
             //replace = wsUrl.replace("10.18.18.53:6014", "splw2.mem.cegn.cn:6014");

            url = replace;
        }
        return MessageInfo.ok(new JSONObject().set("url", url));

    }

    private String getAccessToken() {


        String body = HttpUtil.createGet(TOKEN_URL)
                .header("client_id", CLIENT_ID)
                .header("client_secret", CLIENT_SECRET)
                .header("Content-Type", CONTENT_TYPE)

                .execute().body();

        cn.hutool.json.JSONObject tokenBody = JSONUtil.parseObj(body);
        return tokenBody.getStr("access_token");
    }
}
