package com.yc.ship.module.trade.service.sms;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yc.ship.module.infra.api.config.ConfigApi;
import com.yc.ship.module.trade.api.sms.dto.SmsReqDTO;
import com.yc.ship.module.trade.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.Random;


/**
 * 移动短信实现类
 *
 * @className: SmsServiceImpl
 * @author: lishiqiang
 * @date: 2025/8/6 23:12
 */
@Slf4j
@Service
@Validated
public class SmsServiceImpl implements SmsService {

    @Resource
    private ConfigApi configApi;


    /**
     * 发送短信
     *
     * @param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sendMsg(SmsReqDTO smsReqDTO) {
        try {
            //sxly
            String appId = configApi.getConfigValueByKey("sms.appId");
            //Sx@202305
            String secretKey = configApi.getConfigValueByKey("sms.secretKey");
            //https://112.35.10.201:58888/sms/tmpsubmit
            String url = configApi.getConfigValueByKey("sms.url");
            //jFKNw6Cis
            String signName = configApi.getConfigValueByKey("sms.signName");
//            例：List<Object> paramList = new ArrayList<Object>();
//            paramList.add("两坝一峡");
//            paramList.add("12345");
//            paramList.add("3");
//            smsReqDTO.setSmsContent(JSON.toJSONString(paramList.toArray()));
            log.error("[短信发送参数]：" + smsReqDTO.getSmsContent()+";手机号："+smsReqDTO.getMobile());
            String params = SmsUtil.generateParams(String.join(",", smsReqDTO.getMobile()), smsReqDTO.getSmsContent(), smsReqDTO.getSmsTemplateId(), appId, signName, secretKey);
            log.error("[短信发送参数]：" +url+";"+ params);
//            String result = restTemplate.postForObject(url, params, String.class);
            String result = sendPost(url,params,null);
            log.error("[短信返回参数]：" +result);
            JSONObject resultObject = JSONUtil.parseObj(result);
            if (resultObject != null && "true".equals(resultObject.getStr("success"))) {
                log.error("[短信发送成功]：" + smsReqDTO.getMobile());
                return "发送成功";
            } else {
                return "短信发送失败: " + resultObject.getStr("rspcod");
            }
        } catch (Exception e) {
            log.error("[短信发送失败]：" + e.getMessage());
            return "短信发送失败: " + e.getMessage();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String sendMsg2(SmsReqDTO smsReqDTO) {
        try {
            String appId = configApi.getConfigValueByKey("sms.appId");
            String secretKey = configApi.getConfigValueByKey("sms.secretKey");
            String url = configApi.getConfigValueByKey("sms.url");
            String signName = configApi.getConfigValueByKey("sms.signName");
            log.error("[短信发送参数]：" + smsReqDTO.getSmsContent()+";手机号："+smsReqDTO.getMobile());
            HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gbk");
            post.addParameter("SpCode", signName);
            post.addParameter("LoginName", appId);
            post.addParameter("Password", secretKey);
            post.addParameter("MessageContent", smsReqDTO.getSmsContent());
            post.addParameter("UserNumber", String.join(",", smsReqDTO.getMobile()));
            Random random = new Random();
            int ranNum = random.nextInt(9);
            String serialNumber = SmsUtil.createOrderNo(ranNum + "");
            if(serialNumber.length()>20) {
                serialNumber = serialNumber.substring(0, 19);
            }
            post.addParameter("SerialNumber", serialNumber);
            post.addParameter("ScheduleTime", "");
            post.addParameter("templateId",  smsReqDTO.getSmsTemplateId());
            post.addParameter("f", "1");
            httpclient.executeMethod(post);
            String result = new String(post.getResponseBody(),"gbk");
            log.error("[短信返回参数]：" +result);
            if (result.contains("result=0")) {
                log.error("[短信发送成功]：" + smsReqDTO.getMobile());
                return "发送成功";
            } else {
                return "短信发送失败: " + result;
            }
        } catch (Exception e) {
            log.error("[短信发送失败]：" + e.getMessage());
            return "短信发送失败: " + e.getMessage();
        }
    }


    private static class MyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static String sendPost(String url, String param, Map<String, String> headParam) {
        Long s0 = System.currentTimeMillis();
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
            conn.setHostnameVerifier(new MyHostnameVerifier());
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset","UTF-8");
            if (headParam != null) {
                for (Map.Entry<String, String> entry : headParam.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(1000000);
            conn.setReadTimeout(1000000);

//            System.setProperty("sun.net.client.defaultConnectTimeout", "1000000");
//            System.setProperty("sun.net.client.defaultReadTimeout", "1000000");
            // 获取URLConnection对象对应的输出流
            if(StringUtils.isNotBlank(param)){
                out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
                out.write(param);
                // flush输出流的缓冲
                out.flush();
            }

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            //LogUtil.appLog.info("sendPost>>"+url+">>"+param+">>>"+headParam+">>>>>执行时间："+(System.currentTimeMillis()-s0));
        }
        return result;
    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public Integer queryStatus(String smsId) {
        return 1;
    }

}
