package com.ruoyi.business.util;

import cn.hutool.json.JSONObject;
import com.ruoyi.database.domain.BaseFlowLog;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@RequiredArgsConstructor
public class SySMS {

    protected static final Logger logger = LoggerFactory.getLogger(SySMS.class);

    public static BaseFlowLog sendMessage(String phone, String time, String messageContent,String operName,String receiveName,String taskId){
        // 目标URL
        String url = "http://50.146.63.43:9605/sendSms/send";

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{")
                .append("\"extcode\": \"12\",")
                .append("\"destaddr\": \"" + phone + "\",")
                .append("\"messagecontent\": \"" + messageContent + "\",")
                .append("\"reqdeliveryreport\": \"1\",")
                .append("\"msgfmt\": \"0\",")
                .append("\"sendmethod\": \"0\",")
                .append("\"requesttime\": \"" + time + "\",")
                .append("\"applicationid\": \"P000000000000083\"")
                .append("}");
        String json = jsonBuilder.toString();

        logger.info("Sending request with JSON: {}", json);
        String responseString = "";
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");

            // 创建StringEntity对象，将JSON字符串设置为请求体
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 读取响应内容
                responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
//                logger.info("Response: {}", responseString);
            }
        } catch (Exception e) {
            responseString = e.toString();
//            logger.error("Error sending message", e);
        }
        //发送日志
        BaseFlowLog baseFlowLog = new BaseFlowLog();
        baseFlowLog.setOperName(operName);
        baseFlowLog.setOperTime(System.currentTimeMillis()/1000L);
        baseFlowLog.setReceiveName(receiveName);
        baseFlowLog.setSendType(2);
        baseFlowLog.setSendContent(messageContent);
        baseFlowLog.setSendId(taskId);
        JSONObject jsonObject = new JSONObject(responseString);
        String errMsg = jsonObject.getStr("msg");
        if ("操作成功".equals(errMsg)){
            baseFlowLog.setSendStatus(1);
            baseFlowLog.setSendResult(0);
            baseFlowLog.setErrReason("");
            baseFlowLog.setSmsId(jsonObject.getStr("data"));
        }else {
            baseFlowLog.setSendStatus(2);
            baseFlowLog.setSendResult(0);
            baseFlowLog.setErrReason("接口未调通");
        }
        return baseFlowLog;
    }


    public static Map<String,String> sendMesStatus(String smsid) {
        // 目标URL
        String url = "http://50.146.63.43:9605/sendSms/getSmsStatus";

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{")
                .append("\"sismsid\": \"" + smsid + "\"")
                .append("}");
        String json = jsonBuilder.toString();

//        logger.info("Sending request with JSON: {}", json);
        String responseString = "";
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");

            // 创建StringEntity对象，将JSON字符串设置为请求体
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 读取响应内容
                responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
//                logger.info("Response: {}", responseString);
            }
        } catch (Exception e) {
//            logger.error("Error sending message", e);
        }
        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject(responseString);
        JSONObject object = jsonObject.getJSONObject("data");
        if (object == null){
            return map;
        }
        String sentresult = object.getStr("sentresult");
        String smsstatus = object.getStr("smsstatus");
        map.put("sentresult",sentresult);
        map.put("smsstatus",smsstatus);
        return map;
    }
}
