package com.njcn.roma.controller;

import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * roma
 * 设备台账控制
 * @author cdf
 * @date 2024/8/21
 */
@RestController
@RequiredArgsConstructor
public class DeviceController {


    @Value("${roma.acceptIp}")
    private String acceptIp;

    @Value("${roma.sendIp}")
    private String sendIp;

    @Value("${roma.appId}")
    private String appId;

    @Value("${roma.appKey}")
    private String appKey;


    /**
     * 查询设备信息
     * @author cdf
     * @date 2024/8/21
     */
    @GetMapping("queryDevice")
    public String queryDeviceById(@RequestParam String devId){
        try {
            queryDeviceInfo(devId);
        } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return "获取成功";

    }



    /**
     * 查询告警信息
     * @author cdf
     * @date 2024/8/21
     */

    @GetMapping("alarmHistory")
    public String alarmHistory(@RequestParam String devId){
        try {
            queryAlarm(devId);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return "获取成功";

    }




    /**
     * 查询设备信息
     *
     * @throws JSONException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     */
    public void queryDeviceInfo(String deviceId) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
        String url = "https://" + sendIp + "/iot/1.0/devices?deviceId="+deviceId+"&appId=" + appId;
       // /iot/1.0/devices?deviceId={deviceId}&appId={appId}
        HttpGet httpGet = new HttpGet(url);  //创建post请求
        setSSLHeader(httpGet);	//设置请求的header
        getSSLResponse(httpGet);//获取响应结果

    }


    public void queryAlarm(String deviceId) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
        String url = "https://" + sendIp + "/iot/1.0/devices?deviceId="+deviceId+"&appId=" + appId;
        // /iot/1.0/devices?deviceId={deviceId}&appId={appId}
        HttpGet httpGet = new HttpGet(url);  //创建post请求
        setSSLHeader(httpGet);	//设置请求的header
        getSSLResponse(httpGet);//获取响应结果

    }








    /**
     * 创建ssl连接，设置客户端信任所有证书
     * @return CloseableHttpClient
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private CloseableHttpClient createSSLClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    /**
     * 设置请求时的header
     * @param httpUriRequest
     */
    private void setSSLHeader(HttpUriRequest httpUriRequest) {
        long time = System.currentTimeMillis();
        String authorization = DigestUtils.sha256Hex(appId + appKey + time);
        httpUriRequest.addHeader("Content-Type", "application/json");
        httpUriRequest.addHeader("Authorization", authorization);
        httpUriRequest.addHeader("timestamp", String.valueOf(time));
    }
    /**
     * 解析响应结果
     * @param httpUriRequest
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     * @throws IOException
     */
    private org.apache.http.HttpEntity getSSLResponse(HttpUriRequest httpUriRequest) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
        CloseableHttpClient httpClient = createSSLClient();
        CloseableHttpResponse response = httpClient.execute(httpUriRequest);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
        }
        return responseEntity;
    }

}
