package com.sooka.sponest.monitor.util;

import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/******************************
 * 海康订阅事件
 * @author yanhongliang
 * @date 2021-03-26 12:26
 ******************************/

public class HikSubscription {
    private static final Logger log = LoggerFactory.getLogger(HikSubscription.class);

    static {
//        ArtemisConfig.host = "218.27.1.154:54321";// 代理API网关nginx服务器ip端口
//        ArtemisConfig.appKey = "22654202";// 秘钥appkey
//        ArtemisConfig.appSecret = "d7HlmRIaiXp3MQBmsuUg";// 秘钥appSecret
        ArtemisConfig.host = "36.49.108.22:1443";// 代理API网关nginx服务器ip端口
        ArtemisConfig.appKey = "24699060";// 秘钥appkey
        ArtemisConfig.appSecret = "tt1pMbsrlwGZUWucdAPw";// 秘钥appSecret
    }

    /**
     * 能力开放平台的网站路径
     * TODO 路径不用修改，就是/artemis
     */
    private static final String ARTEMIS_PATH = "/artemis";


    /**
     * 调用POST请求类型(application/json)接口，这里以入侵报警事件日志为例
     * https://open.hikvision.com/docs/918519baf9904844a2b608e558b21bb6#e6798840
     *
     * @return
     */
    public static String callPostStringApi() {
        /**
         * http://10.33.47.50/artemis/api/scpms/v1/eventLogs/searches
         * 根据API文档可以看出来，这是一个POST请求的Rest接口，而且传入的参数值为一个json
         * ArtemisHttpUtil工具类提供了doPostStringArtemis这个函数，一共六个参数在文档里写明其中的意思，因为接口是https，
         * 所以第一个参数path是一个hashmap类型，请put一个key-value，query为传入的参数，body为传入的json数据
         * 传入的contentType为application/json，accept不指定为null
         * header没有额外参数可不传,指定为null
         *
         */
        final String getCamsApi = ARTEMIS_PATH + "/api/scpms/v1/eventLogs/searches";
        Map<String, String> path = new HashMap<>();
        path.put("https://", getCamsApi);//根据现场环境部署确认是http还是https
        path.put("http://", getCamsApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();

        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 3);
        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);// post请求application/json类型参数
        return result;
    }

    /**
     * 调用POST请求下载图片类型接口，这里以获取访客记录中的图片接口为例
     * https://open.hikvision.com/docs/a0a1a0a24701a00aa904f7b151f97410#f11f3208
     *
     * @return
     */
    public static void callPostImgStringApi() {
        /**
         * http://10.33.47.50/api/visitor/v1/record/pictures
         * 根据API文档可以看出来，这是一个POST请求的Rest接口，而且传入的参数值为一个json
         * ArtemisHttpUtil工具类提供了doPostStringImgArtemis这个函数，一共六个参数在文档里写明其中的意思，因为接口是https，
         * 所以第一个参数path是一个hashmap类型，请put一个key-value，query为传入的参数，body为传入的json数据
         * 传入的contentType为application/json，accept不指定为null
         * header没有额外参数可不传,指定为null
         *
         */
        final String VechicleDataApi = ARTEMIS_PATH + "/api/visitor/v1/record/pictures";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("svrIndexCode", "8907fd9d-d090-43d3-bb3a-3a4b10dd7219");
        jsonBody.put("picUri", "/pic?0dd453i3c-e*046456451175m6ep=t=i2p*i=d1s*i3d0d*=*1b8i81f4747059503--bdf90a-855s5721z3b9i=1=");
        String body = jsonBody.toJSONString();
        System.out.println("body: " + body);
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, body, null, null, "application/json", null);
        try {
            HttpResponse resp = result;
            if (200 == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
//                Tools.savePicToDisk(in, "d:/", "test4.jpg");
                System.out.println("下载成功");
            } else {
                System.out.println("下载出错");
            }

        } catch (Exception e) {

            log.error(e.getMessage());
        }
    }


    /**
     * 按事件类型订阅事件
     */
    public static int eventSubscriptionByEventTypes(long[] types,String eventDest) {
        int res = 0;
        final String VechicleDataApi = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionByEventTypes";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("eventTypes", types);

        jsonBody.put("eventDest", eventDest);
        jsonBody.put("subType", 0);
        //jsonBody.put("eventLvl", 3);
        String body = jsonBody.toJSONString();
        System.out.println("body: " + body);
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, body, null, null, "application/json", null);
        System.out.println("reslut ::" + result);
        try {
            HttpResponse resp = result;
            if (200 == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String str = br.readLine();
                System.out.println("str="+str);
                System.out.println("订阅成功:");
                res = 1;
            } else {
                System.out.println("订阅出错");
            }

        } catch (Exception e) {

            log.error(e.getMessage());
        }
        return res;
    }


    /**
     * 查询订阅事件
     * @return
     */
    public static String eventSubscriptionView() {
        final String VechicleDataApi = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionView";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

//		JSONObject jsonBody = new JSONObject();
//		jsonBody.put("eventTypes", "169001001L");
//		jsonBody.put("eventDest", "http://121.89.200.81:9090/business/app/hikc/cameraHik/");
//		jsonBody.put("subType", "0");
//		jsonBody.put("eventLvl", "3");
//		String body = jsonBody.toJSONString();
//		System.out.println("body: "+body);
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, null, null, null, "application/json", null);
        System.out.println("reslut ::" + result);
        String str = null;
        try {
            HttpResponse resp = result;
            if (200 == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                str = br.readLine();
                System.out.println("str="+str);
//                System.out.println("in length :"+in.available());
                int a = in.read();
                while(a != -1){
                    System.out.println(a+"*");
                    a = in.read();
                }
//                byte[] b = new byte[in.available()];
//                in.read(b);
//                System.out.println("查询成功:" + b.length);
            } else {
                System.out.println("查询出错");
            }

        } catch (Exception e) {

            log.error(e.getMessage());
        }
        return str;
    }



    public static String eventUnSubscriptionByEventTypes(long[] types){
        final String VechicleDataApi = ARTEMIS_PATH + "/api/eventService/v1/eventUnSubscriptionByEventTypes";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("eventTypes", types);
        //jsonBody.put("eventLvl", 3);
        String body = jsonBody.toJSONString();
        System.out.println("body: " + body);
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, body, null, null, "application/json", null);
        System.out.println("reslut ::" + result);
        String str = null;
        try {
            HttpResponse resp = result;
            if (200 == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                str = br.readLine();
                System.out.println("str="+str);
                System.out.println("取消订阅成功:");
            } else {
                System.out.println("取消订阅出错");
            }

        } catch (Exception e) {

            log.error(e.getMessage());
        }
        return str;
    }


    public static String playbackURLs(String cameraId,String begintime,String endtime,String protocol) {
        //api/video/v2/cameras/playbackURLs
        final String VechicleDataApi = ARTEMIS_PATH + "/api/video/v2/cameras/playbackURLs";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraId);
        jsonBody.put("beginTime", begintime+"+08:00");
        jsonBody.put("endTime", endtime+"+08:00");
//        jsonBody.put("beginTime", "2021-03-24T00:08:00.000+08:00");
//        jsonBody.put("endTime", "2021-03-24T00:18:05.000+08:00");
        jsonBody.put("protocol", protocol);
//        jsonBody.put("cameraIndexCode", "");
//        jsonBody.put("cameraIndexCode", "");
        //jsonBody.put("eventLvl", 3);
        String body = jsonBody.toJSONString();
        System.out.println("body: " + body);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        System.out.println("reslut ::" + result);
//        try {
//            HttpResponse resp = result;
//            if (200 == resp.getStatusLine().getStatusCode()) {
//                HttpEntity entity = resp.getEntity();
//                InputStream in = entity.getContent();
//                BufferedReader br = new BufferedReader(new InputStreamReader(in));
//                str = br.readLine();
//                System.out.println("str=" + str);
//                System.out.println("视频查询成功:");
//            } else {
//                System.out.println("视频查询出错");
//            }
//
//        } catch (Exception e) {
//
//        }
        return result;
    }


    public static String previewURLs(String cameraId, String protocol) {
        //api/video/v2/cameras/playbackURLs
        final String VechicleDataApi = ARTEMIS_PATH + "/api/video/v1/cameras/previewURLs";
        Map<String, String> path = new HashMap<>();
        path.put("https://", VechicleDataApi);//根据现场环境部署确认是http还是https
        path.put("http://", VechicleDataApi);//根据现场环境部署确认是http还是https

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraId);
        jsonBody.put("protocol", protocol);
        jsonBody.put("streamType", 0);
        String body = jsonBody.toJSONString();
        System.out.println("body: " + body);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        System.out.println("reslut ::" + result);

        return result;
    }

    public static void main(String[] args) {



        String result = previewURLs("87c547d83f26407d83251199ba75af66","ws");
        //2023-01-02T08:37:08.000
        //2023-01-02T08:39:08.000
//        String result = playbackURLs("2e7051ca74b34cb1b816f5c41c4ebf66","2023-01-02T08:37:08.000","2023-01-02T08:39:08.000","hls");
        System.out.println("-=-=-=-=-=-=-="+result);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        Object a = jsonObject.get("code");
//        System.out.println(a.toString());

//        /api/video/v1/cameras/previewURLs


        //*

        //订阅

//        火
//        long[] subscription = {169001001L};
//        String url = "http://36.49.108.22:10003/AlarmEventController/haikang@insertFireEvent";

        //城管
//        long[] subscription = {7617069059L};
//        String url = "http://36.49.108.22:10003/AlarmEventController/haikang@insertCityEvent";
//
//        eventSubscriptionByEventTypes(subscription,url);

        //取消订阅
//        long[] unSubscription = {7617069059L};
//        eventUnSubscriptionByEventTypes(unSubscription);

        //查询已经订阅的事件
//        eventSubscriptionView();

        //*/

        //订阅警戒头事件
//        eventSubscriptionByEventTypes(131588,"https://192.168.10.15:9090/business/app/hikc/cameraHikByEventRcv/");

//        eventUnSubscriptionByEventTypes(131588);

        //查看历史回放
//        {"protocol":"hls","beginTime":"2021-03-26T11:10:50.000+08:00","endTime":"2021-03-26T11:12:50.000+08:00","cameraIndexCode":"a0b060ae228b463785d72102339b88e5"}
//        playbackURLs("d6819d298c0f422a9f871e94edb568f3",
//                "2021-03-26T11:10:50.000",
//                "2021-03-26T11:12:50.000",
//                "rtsp"
//        );
//        eventSubscriptionView();
    }

}
