package com.netwisd.biz.demo;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netwisd.common.core.exception.IncloudException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class IncloudLogin {

    private HttpClient httpClient = HttpClientBuilder.create().build();

    //客户端ID
    private static String clientId = "1664527552103235586";

    // 客户端凭证
    private static String clientSecret = "1VN-srs#!jB0Jdn(ZelTcwbjugZJK!A1";

    //客户端凭证 加密公钥
    private static String clientSecretPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDT4myj96f5lklBa2JO4AY03euFWqFxQqHcnlLiyC5OUcBlrsdWg85IdVLIjXEFXdQ+VqDujzgHbTHhk+cGXQZdBrGmAFL2mRB4CFFEpHiYjV/j73p0/yFbztpt2DB2yIjYt1PlPWOGmTx/uvfrR0k7/dAKur9j6rUFGOGaAvKr4wIDAQAB";


    private static String clientPwdPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC62x1In4A55KpLsSSlDO1BGQ2gWVuhzYErSjXu9d6UVhENZ8lklsdlEJbdJUrjf89Z9CuUgTCTOm6mb5Mx1K9SyIiol5R7WgPFVKnU0R0mDDh/jkbVo8QfQpqdK2uJmYL2P5//rscRMbs6lJnrEt75ErscXn2igcegDdhKy6Uo4QIDAQAB";


    //开发环境网关
    //private static String gatewayUrl = "http://10.73.178.98:8000";

    //测试环境网关
    //private static String gatewayUrl = "http://10.73.178.90:8000";

    //正式环境网关
    //private static String gatewayUrl = "http://portal.hbyt.petrochina/api/v5.0";
    private static String gatewayUrl = "http://127.0.0.1:8002";

    /**
     * 加密处理客户端凭证
     *
     * @param secret
     * @param publicKey
     */
    public String getClientSecret(String authCode, String secret, String publicKey) {
        RSA rsa = SecureUtil.rsa(null, publicKey);
        byte[] encrypt = rsa.encrypt(authCode + secret, KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    public String getClientPwd(String pwd, String pwdPublicKey) {
        RSA rsa = SecureUtil.rsa(null, pwdPublicKey);
        byte[] encrypt = rsa.encrypt(pwd, KeyType.PublicKey);
        return Base64.encode(encrypt);
    }


    public String getAuthCode(String clientId) {
        HttpResponse execute = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(gatewayUrl + "/authCode");
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            Map<String, String> prams = new HashMap<>();
            prams.put("clientId", clientId);
            String jsonString = JSONUtil.toJsonStr(prams);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(entity);
            execute = httpClient.execute(httpPost);
            if (execute.getStatusLine().getStatusCode() == 200) {
                log.info("获取成功！");
                HttpEntity httpEntity = execute.getEntity();
                JSONObject jsonObj = JSON.parseObject(EntityUtils.toString(httpEntity));
                result = jsonObj.get("data").toString();
            } else {
                log.info("请求异常，错误代码：{}", execute.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new IncloudException("获取授权码失败!:{}", e.getMessage());
        }
        return result;
    }

    public String getClientToken() {
        String authCode = getAuthCode(clientId);
        log.info("authCode : {}", authCode);
        String clientSecretData = getClientSecret(authCode, clientSecret, clientSecretPublicKey);
        log.info("clientSecretData : {}", clientSecretData);
        String authorization = "Basic " + Base64.encode(clientId + ":" + clientSecretData);
        String pwd = getClientPwd("Sjzx@123", clientPwdPublicKey);
        log.info("pwd : {}", pwd);
        HttpResponse execute = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(gatewayUrl + "/client/oauth");
            httpPost.setHeader("Authorization", authorization);
            String userName = "admin";
            String jsonString = JSONUtil.toJsonStr("username=" + userName + "&password=" + pwd);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            entity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(entity);
            execute = httpClient.execute(httpPost);
            HttpEntity httpEntity = execute.getEntity();
            JSONObject jsonObj = JSON.parseObject(EntityUtils.toString(httpEntity));
            JSONObject jsonObjData = JSON.parseObject(jsonObj.get("data").toString());
            result = jsonObjData.get("access_token").toString();
            log.info("获取Token 成功 result : {}", result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IncloudException("登录失败!:{}", e.getMessage());
        }
        return result;
    }


    @Test
    public void doTest() {
//        sendSmsForUnify();
        sendWarningLog();
        //updateWarningLogstat();
        //decodeStr();

//        LocalDate nowData = LocalDate.now();
//        LocalDate one = nowData.with(TemporalAdjusters.firstDayOfMonth());
//        log.info("现在时间：{}", nowData);
//        log.info("月初：{}", one);
//        log.info("plusDays10：{}", one.plusDays(10));
    }


    private void sendSmsForUnify() {
        String token = getClientToken();
        log.info("result : {}", token);
        HashMap<String, Object> map = new HashMap<>();
        //准备转成jsonObject
        map.put("msgTitle", "测试数据");
        map.put("msgContent", "测试数据");
        map.put("smsMsgType", "wechat");
        map.put("msgSource", "other");
        map.put("sendUserId", 1);
        // map.put("receiverUserId", 0);
        map.put("receiverUserCode", "50070464");
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = gatewayUrl + "/sms/smsApiController/sendSmsForUnify"; //请求对方的路径地址
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(JSONUtil.toJsonStr(map), "utf-8"); //JSONObject.toJSONString(map)将map集合转成JSONObject
            s.setContentType("application/json");
            post.setEntity(s);
            post.setHeader("Authorization", "Bearer " + token);
            HttpResponse res = client.execute(post);
            String response = EntityUtils.toString(res.getEntity()); //将请求回来的json转成String
            System.out.println(response);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 推送消息日志
     */
    private void sendWarningLog() {
        String token = getClientToken();
        log.info("result : {}", token);
        HashMap<String, Object> map = new HashMap<>();
        //准备转成jsonObject
        map.put("eventId", "10");
        map.put("eventCode", "1");
        map.put("eventLevel", "3");
        map.put("orgCode", "00000");
        map.put("orgName", "00000");
        map.put("username", "admin");
        map.put("usernameCh", "admin");
        map.put("area", "北京");
        map.put("device", "2");
        map.put("startTime", "2023-05-05 00:00:01");
        map.put("endTime", "2023-05-05 00:00:01");
        map.put("pushTime", "2023-05-05 00:00:01");
        map.put("pullTime", "2023-05-05 00:00:01");
        map.put("content", "井下钻修X04563_2告警日志信息");
        map.put("customerDetails", "{\\\"areaId\\\":\\\"jingxiazuanxiuX04563\\\",\\\"areaName\\\":\\\"井下钻修X04563\\\",\\\"description\\\":\\\"未佩戴安全帽\\\",\\\"deviceCode\\\":\\\"11010000001320010034\\\",\\\"deviceName\\\":\\\"井下钻修X04563_2\\\",\\\"deviceType\\\":\\\"0\\\",\\\"exceptionImageUrl\\\":\\\"http://10.73.178.179:19000/helmetc/helmet_0d74076a0b2111eeabfc0242ac110003_1686795161_186_1686795161689241.jpg\\\",\\\"parallelFlag\\\":\\\"0\\\",\\\"processFlag\\\":\\\"0\\\",\\\"screeningFlag\\\":\\\"0\\\",\\\"source\\\":\\\"this\\\",\\\"thumbnailUrl\\\":\\\"http://10.73.178.179:19000/helmett/helmet_0d74076a0b2111eeabfc0242ac110003_1686795161_186_1686795161689241.jpg\\\",\\\"updatedTime\\\":\\\"2023-06-15 10:12:41\\\"}");
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        HttpPost post = new HttpPost(gatewayUrl + "/warning/warningEventLog");
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(JSONUtil.toJsonStr(map), "utf-8"); //JSONObject.toJSONString(map)将map集合转成JSONObject
            s.setContentType("application/json");
            post.setEntity(s);
            post.setHeader("Authorization", "Bearer " + token);
            HttpResponse res = client.execute(post);
            String response = EntityUtils.toString(res.getEntity()); //将请求回来的json转成String
            System.out.println(response);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改状态
     */
    private void updateWarningLogstat() {
        String token = getClientToken();
        log.info("result : {}", token);
        HashMap<String, Object> map = new HashMap<>();
        map.put("eventId", "3");
        map.put("state", "1");
        map.put("handlerTime", "2023-05-05 00:00:01");
        map.put("handlerUserNameCh", "1");
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        HttpPost post = new HttpPost(gatewayUrl + "/warning/warningEventLog/updateState");
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(JSONUtil.toJsonStr(map), "utf-8"); //JSONObject.toJSONString(map)将map集合转成JSONObject
            s.setContentType("application/json");
            post.setEntity(s);
            post.setHeader("Authorization", "Bearer " + token);
            HttpResponse res = client.execute(post);
            String response = EntityUtils.toString(res.getEntity()); //将请求回来的json转成String
            System.out.println(response);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void decodeStr() {
        String data = "Mg==";
        Integer intData = Integer.valueOf(Base64.decodeStr(data));
        log.info("intData:{}", intData);
    }
}