package com.rongwei.sfcommon.sys.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rongwe.scentity.vo.AspRiskMapVo;
import com.rongwe.scentity.vo.AspRiskUnitVo;
import com.rongwe.scentity.vo.FourColorSynchronizationVo;
import com.rongwei.sfcommon.utils.Result;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import static com.rongwei.safecommon.utils.SaveConstans.AsyncStatus.SUCCESSSYNC;

public interface SynchronizationService {

    /**
     * 四色图信息同步
     *
     */
    void fourColorSynchronizationList(List<String> ids) throws IOException;

    /**
     * 单元、事件和措施信息同步
     *
     */
    void unitSynchronizationList(List<String> ids);

    /**
     * 安全维护信息同步
     *
     */
    void safeMaintenanceSynchronizationList(List<String> ids);

    default Result dataPush(String ip, String address, List<Map<String, Object>> syncDataMapList) {
        StringBuilder failureReason = new StringBuilder();
        try {
            // 验证输入参数
            if (ip == null || ip.isEmpty()) {
                failureReason.append("IP地址为空;");
            }
            if (address == null || address.isEmpty()) {
                failureReason.append("接口路径为空;");
            }
            if (syncDataMapList == null || syncDataMapList.isEmpty()) {
                failureReason.append("同步数据为空;");
            }
            if (failureReason.length() > 0) {
                return Result.error(failureReason.toString());
            }

            // 构造完整的URL（ip包含端口）
            String urlStr = "http://" + ip + address;
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置连接超时和读取超时（防止长时间挂起）
            conn.setConnectTimeout(5000); // 5秒连接超时
            conn.setReadTimeout(10000);    // 10秒读取超时

            // 设置请求属性
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 将数据转换为JSON字符串
            ObjectMapper mapper = new ObjectMapper();
            String jsonInputString = mapper.writeValueAsString(syncDataMapList);

            // 发送请求体
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 检查响应码
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println("推送成功，响应内容：" + response.toString());
                    if (response.toString().contains("200")) {
                        return Result.ok(jsonInputString);
                    }
                    return Result.error(response.toString());
                }
            } else {
                // 读取错误响应信息
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        errorResponse.append(responseLine.trim());
                    }
                    failureReason.append("HTTP错误码: ").append(responseCode);
                    if (errorResponse.length() > 0) {
                        failureReason.append("; 错误详情: ").append(errorResponse.toString());
                    }
                } catch (Exception e) {
                    failureReason.append("; 读取错误响应失败: ").append(e.getMessage());
                }
            }
        } catch (MalformedURLException e) {
            failureReason.append("URL格式错误: ").append(e.getMessage());
        } catch (ConnectException e) {
            failureReason.append("连接失败: ").append(e.getMessage());
            if (e.getMessage().contains("refused")) {
                failureReason.append("(连接被拒绝，检查IP和端口)");
            } else if (e.getMessage().contains("timed out")) {
                failureReason.append("(连接超时，检查网络或增加超时时间)");
            }
        } catch (SocketTimeoutException e) {
            failureReason.append("读取超时: ").append(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            failureReason.append("编码不支持: ").append(e.getMessage());
        } catch (IOException e) {
            failureReason.append("IO异常: ").append(e.getMessage());
        } catch (Exception e) {
            failureReason.append("未知异常: ").append(e.getMessage());
        }

        String reasonStr = failureReason.toString();
        System.err.println("推送失败，原因: " + reasonStr);
        return Result.error(reasonStr);
    }

    /**
     * 安全检查记录信息同步
     *
     */
    void safeRecordSynchronizationList(List<String> ids);
}
