package cn.iocoder.yudao.module.server.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Component
public class SMSUtils {

    @Value("${sms.apId}")
    private  String apId;
    @Value("${sms.secretKey}")
    private  String secretKey;
    @Value("${sms.ecName}")
    private  String ecName;	//集团名称
    @Value("${sms.sign}")
    private  String sign;	//网关签名编码

    private  String addSerial = "";	//拓展码 填
    @Value("${sms.url}")
    private  String url ;//请求url
    //private   String mobiles = "18047152895";
    //private  String content ="来自内蒙古自治区政务服务局的消息";
    /**
     * 多用户发送短信信息
     * @return 返回1表示成功，0表示失败
     * @throws IOException
     * @param mobolephone 手机号，多个手机号用英文逗号隔开
     * @param content 正文
     */
    public boolean sendMsg(String mobolephone, String content) throws IOException, NoSuchAlgorithmException {

        SendReq sendReq = new SendReq();
        sendReq.setApId(apId);
        sendReq.setEcName(ecName);
        sendReq.setSecretKey(secretKey);
        String finalContent = content;
        sendReq.setContent(finalContent);
        sendReq.setMobiles(mobolephone);
        sendReq.setAddSerial(addSerial);
        sendReq.setSign(sign);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sendReq.getEcName());
        stringBuffer.append(sendReq.getApId());
        stringBuffer.append(sendReq.getSecretKey());
        stringBuffer.append(sendReq.getMobiles());
        stringBuffer.append(sendReq.getContent());
        stringBuffer.append(sendReq.getSign());
        stringBuffer.append(sendReq.getAddSerial());
        String md5Mac = DigestUtils.md5DigestAsHex(stringBuffer.toString().getBytes());
        sendReq.setMac(md5Mac.toLowerCase());
        String reqText = JSON.toJSONString(sendReq);
        String encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
        String resStr = sendPost(url,encode);
        log.info("用户【{}】发送短信结果：{}",mobolephone,resStr);
        SendRes sendRes = JSON.parseObject(resStr,SendRes.class);
        if(sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *  发送请求的 URL
     * @param param
     *  请求参数
     * @return 所代表远程资源的响应结果
     */
    private String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("contentType","utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(param);
            out.flush();


            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
