package cn.cecep.talroad.util;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.rmi.ServerException;
import java.util.HashMap;
import java.util.Map;

/**
 * 萤石云视屏工具类*/
public class VideoUtil {

    public static class ResultVo {
        private Map data;
        private String code;
        private String msg;

        public Map getData() {
            return data;
        }

        public void setData(Map data) {
            this.data = data;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

    /**
     * 获取Access_token
     *
     * @return
     */
    public static String getAccess_token(String appKey, String secret) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String access_token = "";
        String url = Ys7Common.YS7_DOMAIN_URL + "/api/lapp/token/get?appKey=" + appKey + "&appSecret=" + secret;
        String result = getData(url);
        if (result != null && !"".equals(result)) {
            ResultVo accessToken = gson.fromJson(result, ResultVo.class);
            return (String) accessToken.getData().get("accessToken");
        }
        return null;
    }

    /**
     * 设置 https 请求
     *
     * @throws Exception
     */
    private static void trustAllHttpsCertificates() throws Exception {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String str, SSLSession session) {
                return true;
            }
        });
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }


    //设置 https 请求证书
    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
            return;
        }
    }

    /**
     * POST请求
     *
     * @param url
     * @return
     */
    public static String getData(String url) throws IOException {
        BufferedReader reader = null;
        try {
            trustAllHttpsCertificates(); // 跳过证书认证
        } catch (Exception e) {
            throw new ServerException("跳过证书认证失败");
        }
        HttpURLConnection connection = null;
        String result = "";
        try {
            //创建连接
            URL url2 = new URL(url);
            connection = (HttpURLConnection) url2.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                String s = lines.replaceAll("%", "");
                lines = URLDecoder.decode(s, "utf-8");
                sb.append(lines);
            }
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert reader != null;
            reader.close();
            // 断开连接
            connection.disconnect();
        }
        return result;
    }

    /**
     * 开始云台控制
     * direction  操作命令：0-上，-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     * speed   云台速度：0-慢，1-适中，2-快
     *
     * @return
     * @throws IOException
     */
    public static Map<String, String> getStart(int direction, int speed, String access_token, String deviceSerial, Integer channelNo) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String url = Ys7Common.YS7_DOMAIN_URL + "/api/lapp/device/ptz/start?accessToken=" + access_token + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo + "&direction=" + direction + "&speed=" + speed;
        String result = getData(url);
        Map<String, String> map = new HashMap<>();
        if (result != null && !"".equals(result)) {
            ResultVo accessToken = gson.fromJson(result, ResultVo.class);
            map.put("msg", accessToken.getMsg());
            map.put("code", accessToken.getCode());
        } else {
            map.put("msg", "控制失败！");
            map.put("code", "0");
        }
        return map;
    }

    /**
     * 停止云台控制
     * direction  操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     *
     * @return
     * @throws IOException
     */
    public static String getStop(int direction, String access_token, String deviceSerial, Integer channelNo) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String url = Ys7Common.YS7_DOMAIN_URL + "/api/lapp/device/ptz/stop?accessToken=" + access_token + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo + "&direction=" + direction;
        String result = getData(url);
        if (result != null && !"".equals(result)) {
            ResultVo accessToken = gson.fromJson(result, ResultVo.class);
            return accessToken.getMsg();
        }
        return "控制失败！";
    }

    /**
     * 获取单个设备信息
     * deviceSerial  设备序列号,存在英文字母的设备序列号，字母需为大写
     *
     * @return
     * @throws IOException
     */
    public static Map getDeviceInfo(String access_token, String deviceSerial) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        if (StringUtils.isNotEmpty(access_token) && StringUtils.isNotEmpty(deviceSerial)) {
            String url = Ys7Common.YS7_IP_URL + "/api/lapp/device/info?accessToken=" + access_token + "&deviceSerial=" + deviceSerial;
            String result = getData(url);
            if (result != null && !"".equals(result)) {
                ResultVo accessToken = gson.fromJson(result, ResultVo.class);
                System.out.println(accessToken);
                if (accessToken.getCode().equals("200")) {
                    return accessToken.getData();
                }
            }
        }
        return null;
    }

    /**
     * 添加设备
     * accessToken   授权过程获取的access_token
     * deviceSerial  设备序列号,存在英文字母的设备序列号，字母需为大写
     * validateCode   	设备验证码，设备机身上的六位大写字母
     *
     * @return
     * @throws IOException
     */
    public static Map addDeviceInfo(String access_token, String deviceSerial, String validateCode) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String url = Ys7Common.YS7_IP_URL + "/api/lapp/device/add?accessToken=" + access_token + "&deviceSerial=" + deviceSerial + "&validateCode=" + validateCode;
        String result = getData(url);
        System.out.println("添加设备：" + result);
        if (result != null && !"".equals(result)) {
            ResultVo accessToken = gson.fromJson(result, ResultVo.class);
            System.out.println(accessToken);
            if (accessToken.getCode().equals("200")) {
                return accessToken.getData();
            }
        }
        return null;
    }

    /**
     * 获取子账户信息列表
     * accessToken   授权过程获取的access_token
     * deviceSerial  设备序列号,存在英文字母的设备序列号，字母需为大写
     * validateCode   	设备验证码，设备机身上的六位大写字母
     *
     * @return
     * @throws IOException
     */
    public static Map getAccountList(String access_token, int pageStart, int pageSize) throws IOException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String url = Ys7Common.YS7_IP_URL + "/api/lapp/device/list?" + access_token + "&pageStart=" + pageStart + "&pageSize=" + pageSize;
        String result = getData(url);
        if (result != null && !"".equals(result)) {
            ResultVo accessToken = gson.fromJson(result, ResultVo.class);
            System.out.println(accessToken);
            if (accessToken.getCode().equals("200")) {
                return accessToken.getData();
            }
        }
        return null;
    }

    public static void main1(String[] args) throws IOException {
        String t = getAccess_token("dfd1623a053540e8a89b2a87b87d00fd", "ed3d14e99e892680b3fe2d79594b59d7");
        //getDeviceInfo(t,"E43167007");
        //getStart(10,0,t,"E44386072",1);          验证码：
        //Map map = getAccountList(t,0,10);//getDeviceInfo(t,"E84566865","NTBRKJ");
        System.out.println(t);
    }
}
