package com.tofly.scada.util;

import com.alibaba.fastjson.JSON;
import com.tofly.scada.entity.ResponseNote;
import com.tofly.scada.entity.SendNote;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

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.util.Objects;

/**
 * @author FlashWJL
 * @date 2021/4/6 10:43
 */
@Component
public class SMSUtils {
    private static String apId = "swag";
    private static String secretKey = "Wjl123456$";
    private static String ecName = "成都沱源自来水有限责任公司";    //集团名称
    private static String sign = "EGhGhiqMO";    //网关签名编码
    private static String addSerial = "";    //拓展码 填空
    public static String url = "http://112.35.1.155:1992/sms/norsubmit";//请求url


    /**
     * 多用户发送短信信息
     *
     * @param mobiles 手机号码逗号分隔
     * @param content 短信内容
     * @return 返回1表示成功，0表示失败
     * @throws IOException
     */
    public String sendMsg(String mobiles, String content) throws Exception {
//        Calendar calendar = Calendar.getInstance();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String nowDatestr = sdf.format(calendar.getTimeInMillis());
//        content += nowDatestr; //短信内容后跟个日期时间（可有可无），需求要求

        SendNote sendReq = new SendNote();
        sendReq.setApId(apId);
        sendReq.setEcName(ecName);
        sendReq.setSecretKey(secretKey);
        sendReq.setContent(content);
        sendReq.setMobiles(mobiles);
        sendReq.setAddSerial(addSerial);
        sendReq.setSign(sign);

        //System.out.println(stringBuffer.toString());
        String stringBuffer = sendReq.getEcName() +
                sendReq.getApId() +
                sendReq.getSecretKey() +
                sendReq.getMobiles() +
                sendReq.getContent() +
                sendReq.getSign() +
                sendReq.getAddSerial();
        sendReq.setMac(Objects.requireNonNull(Md5Util.MD5(stringBuffer)).toLowerCase());
        //System.out.println(sendReq.getMac());

        String reqText = JSON.toJSONString(sendReq);

        String encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
        //System.out.println(encode);

        String resStr = sendPost(url, encode);

        System.out.println("发送短信结果：" + resStr);

        ResponseNote sendRes = JSON.parseObject(resStr, ResponseNote.class);
        //这里是返回结果判断，成功则是返回 1
        if (sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())) {
            return resStr + "。发送成功";
        } else {
            if ("TooManyMobiles".equals(sendRes.getRspcod())) {
                return resStr + "。手机号数量超限（>5000）";
            } else if ("InvalidMessage".equals(sendRes.getRspcod())) {
                return resStr + "。非法消息，请求数据解析失败；检查消息内容是否有特殊字符";
            } else if ("IllegalMac".equals(sendRes.getRspcod())) {
                return resStr + "。mac校验不通过";
            } else if ("IllegalSignId".equals(sendRes.getRspcod())) {
                return resStr + "。无效的签名编码";
            } else if ("InvalidUsrOrPwd".equals(sendRes.getRspcod())) {
                return resStr + "。非法用户名/密码";
            } else if ("NoSignId".equals(sendRes.getRspcod())) {
                return resStr + "。未匹配到对应的签名信息";
            }
            return resStr + "。失败";
        }
    }

  /*
    //main方法测试发送短信，返回1表示成功，0表示失败
   	public static void main(String[] args) throws IOException{
    	String msg = "这是发送短信的内容！";
    	int result = sendMsg("183xxxx65xx,183xxxx12xx",msg);
        System.out.println("==="+result);
    }*/

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数
     * @return 所代表远程资源的响应结果
     */
    private static String sendPost(String url, String param) {
        OutputStreamWriter out = null;

        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        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.append("\n").append(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.toString();
    }

}

