package com.huimv.video.dhicc.controller.ClientController;

import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.http.IccTokenResponse;
import com.dahuatech.icc.oauth.profile.IccProfile;
import com.huimv.common.utils.StringUtilsWork;
import com.huimv.video.dhicc.icc.CommonConstant;
import com.huimv.video.dhicc.test.manager.IOauthIntegrationManager;
import com.huimv.video.dhicc.test.response.GetTokenResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import static com.huimv.video.dhicc.icc.CommonConstant.IPAndPort;
import static com.huimv.video.dhicc.icc.CommonConstant.Sg_IPAndPort;


@RestController
@RequestMapping("/picture")
public class GetPicture {
    @Autowired
    private IOauthIntegrationManager oauthIntegrationManager;
    @RequestMapping("/get")
    public void getCarRecord(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(name = "fileUrl", required = false) String fileUrl,
                             @RequestParam(name = "alarmPicture", required = false) String alarmPicture,
                             @RequestParam(name = "path", required = false) String path,
                             @RequestParam(name = "farmId") Integer farmId
    ) throws IOException, ClientException {
        String url = "";
        if (farmId == 1){
            GetTokenResponse tokenTest01 = oauthIntegrationManager.getTokenTest01();
            String access_token = tokenTest01.getData().getAccess_token();
            //如果 fileURL不为空  就认为是拿摄像头抓拍图片
            if (StringUtilsWork.isNotEmpty(fileUrl)) {
                url = Sg_IPAndPort + "/evo-apigw/" + fileUrl;
            } else if (StringUtilsWork.isNotEmpty(path)) {
                //档案的图片
                url = Sg_IPAndPort + "/evo-pic/" + path + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Document_Oss_Addr;
            } else {
                //事件的图片
                url = Sg_IPAndPort + "/evo-pic/" + alarmPicture + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Shijian_Oss_Addr;
            }
        }else if (farmId == 22){
            GetTokenResponse tokenTest02 = oauthIntegrationManager.getTokenTest02();
            String access_token = tokenTest02.getData().getAccess_token();
            //如果 fileURL不为空  就认为是拿摄像头抓拍图片
            //目前只有曙光照片
            if (StringUtilsWork.isNotEmpty(fileUrl)) {
                url = Sg_IPAndPort + "/evo-apigw/" + fileUrl;
            } else if (StringUtilsWork.isNotEmpty(path)) {
                //档案的图片
                url = Sg_IPAndPort + "/evo-pic/" + path + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Document_Oss_Addr;
            } else {
                //事件的图片
                url = Sg_IPAndPort + "/evo-pic/" + alarmPicture + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Shijian_Oss_Addr;
            }
        }else if (farmId == 21){
            GetTokenResponse tokenTest03 = oauthIntegrationManager.getTokenTest03();
            String access_token = tokenTest03.getData().getAccess_token();
            //如果 fileURL不为空  就认为是拿摄像头抓拍图片
            //目前只有曙光照片
            if (StringUtilsWork.isNotEmpty(fileUrl)) {
                url = Sg_IPAndPort + "/evo-apigw/" + fileUrl;
            } else if (StringUtilsWork.isNotEmpty(path)) {
                //档案的图片
                url = Sg_IPAndPort + "/evo-pic/" + path + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Document_Oss_Addr;
            } else {
                //事件的图片
                url = Sg_IPAndPort + "/evo-pic/" + alarmPicture + "?token=" + access_token + "&oss_addr=" + CommonConstant.Sg_Shijian_Oss_Addr;
            }
        }
        HttpResponse httpResponse = null;
        try {
            CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
            System.setProperty("jsse.enableSNIExtension", "false");
            HttpGet httpGet = new HttpGet(url);
            httpResponse = buildSSLCloseableHttpClient.execute(httpGet);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        System.out.println("返回图片");
        //response.setContentLength(285390);
        response.setHeader("Content-Type", " image/jpeg");
        response.setHeader("Accept-Ranges", "bytes");
        InputStream content = httpResponse.getEntity().getContent();
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = content.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static CloseableHttpClient buildSSLCloseableHttpClient()
            throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[]{"TLSv1.2"}, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

}
