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;

@RequiredArgsConstructor
public class SwtMessage {


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

//    private static final String messageContent = ConfigParam.MessageContent;

    private static final String messageUrl = "http://50.16.172.231:80/open/apigw/v1/messages/create";


    public static void sendMessage(String appToken,String staffId,String messageContent){
        // 目标URL
        String url = messageUrl + "?app_token=" + appToken;

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"userIdList\": [ \"")
                .append(staffId)
                .append("\" ],")
                .append("\"msgType\": \"text\",")
                .append("\"msgData\": {")
                .append("\"text\": {")
                .append("\"content\": \"")
                .append(messageContent)
                .append("\"}")
                .append("}}");
        String json = jsonBuilder.toString();

        logger.info("Sending request with JSON: {}", json);

        // 创建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)) {
                // 读取响应内容
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.info("Response: {}", responseString);
            }
        } catch (Exception e) {
            logger.error("Error sending message", e);
        }
    }

    public static BaseFlowLog sendMessage(String appToken,String staffId,String messageContent,String operName,String receiveName,String taskId){
        // 目标URL
        String url = messageUrl + "?app_token=" + appToken;

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"userIdList\": [ \"")
                .append(staffId)
                .append("\" ],")
                .append("\"msgType\": \"text\",")
                .append("\"msgData\": {")
                .append("\"text\": {")
                .append("\"content\": \"")
                .append(messageContent)
                .append("\"}")
                .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(1);
        baseFlowLog.setSendContent(messageContent);
        baseFlowLog.setSendId(taskId);
        JSONObject jsonObject = new JSONObject(responseString);
        String errMsg = jsonObject.getStr("errMsg");
        if ("ok".equals(errMsg)){
            baseFlowLog.setSendStatus(1);
            baseFlowLog.setSendResult(1);
            baseFlowLog.setErrReason("");
        }else {
            baseFlowLog.setSendStatus(2);
            baseFlowLog.setSendResult(2);
            baseFlowLog.setErrReason(errMsg);
        }
        return baseFlowLog;
    }




    public static void sendMessageNoLog(String appToken,String staffId,String messageContent){
        // 目标URL
        String url = messageUrl + "?app_token=" + appToken;

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"userIdList\": [ \"")
                .append(staffId)
                .append("\" ],")
                .append("\"msgType\": \"text\",")
                .append("\"msgData\": {")
                .append("\"text\": {")
                .append("\"content\": \"")
                .append(messageContent)
                .append("\"}")
                .append("}}");
        String json = jsonBuilder.toString();

        logger.info("Sending request with JSON: {}", json);

        // 创建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)) {
                // 读取响应内容
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.info("Response: {}", responseString);
            }
        } catch (Exception e) {
            logger.error("Error sending message", e);
        }
    }


    public static void goMsg(String messageContent,String phone){
        String swtAppToken = SwtToken.getSwtAppToken();
        String staffIdByPhone = SwtToken.getStaffIdByPhone(phone, swtAppToken);
        sendMessageNoLog(swtAppToken,staffIdByPhone,messageContent);
    }

}
