/*
 * Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
 * FileName: SmsUtils.java
 * Author:   duhui
 * Date:     2015年2月11日 上午9:09:35
 * Description:     
 * History: 
 * <author>      <time>      <version>    <desc>
 * 修改人姓名                          修改时间                        版本号                                 描述
 */
package com.house365.commons.system;

import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 短信发送方法
 *
 * @author jiagnzhou
 * @version [v1.0.0, 2015年2月11日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class SmsUtils {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsUtils.class);

    /**
     * 调用短信接口 发送短信内容
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @throws Exception
     * @author jiangzhou
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String sendSms(String city, String mobileno, String msg) {

        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        String smsUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.default.smsUrl");
        // 测试方便
        if (null == smsUrl) {
            smsUrl = "http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/5/depart/1/city/";
        }

        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            // 拼接内容
            smsUrl = smsUrl + city + "/" + "mobileno/" + mobileno + "?" + "msg=" + msg;
            URL url = new URL(smsUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }

        return jsonStr;
    }

    /**
     * 调用短信接口 发送短信内容
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @throws Exception
     * @author jiangzhou
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String sendSms(String city, String mobileno, String msg, String yzm) {
        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        String smsUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.default.consultansmsUrl");
        // 测试方便
        if (null == smsUrl) {
            smsUrl = "http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/87/depart/1/city/";
        }
        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            // 拼接内容
            smsUrl = smsUrl + city + "/" + "mobileno/" + mobileno + "?" + "msg=" + msg + "&yzm=" + yzm;
            URL url = new URL(smsUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }

        return jsonStr;
    }

    /**
     * 调用短信接口 发送短信内容
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @throws Exception
     * @author nizhengjia
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String sendSms(String smsUrl, String city, String mobileno, String msg, String yzm) {
        // 调用接口返回值
        String jsonStr = "";
        try {
            if (null != smsUrl) {
                // 设置短信内容编码
                msg = URLEncoder.encode(msg, "GBK");
                // 拼接内容
                smsUrl = smsUrl + city + "/" + "mobileno/" + mobileno + "?" + "msg=" + msg + "&yzm=" + yzm;
                URL url = new URL(smsUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
                String line;
                while ((line = in.readLine()) != null) {
                    jsonStr += line;
                }
                in.close();
            }
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }
        return jsonStr;
    }


    /**
     * 调用短信接口 发送短信内容
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @throws Exception
     * @author jiangzhou
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String shakeSendSms(String city, String mobile, String msg, String sendUrl) {
        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            // 拼接内容
            sendUrl = sendUrl + city + "/" + "mobileno/" + mobile + "?" + "msg=" + msg;
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }
        return jsonStr;
    }

    /**
     * 精准导购客户约看
     *
     * @param city
     * @param mobile
     * @param msg
     * @param sendUrl
     * @return
     */
    public static String hgsCustomerRecordSendSms(
        String city, String mobile, String msg, String params, String sendUrl
    ) {
        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            params = URLEncoder.encode(params, "GBK");
            // 拼接内容
            sendUrl = sendUrl + city + "/mobileno/" + mobile + "?msg=" + msg + "&sms_params=" + params + "&sms_template=JSM40093-0026";
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }

            LOGGER.info("smsutil send hgsCustomerRecord: url [{}] , result[{}]", sendUrl, jsonStr);
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }
        return jsonStr;
    }

    /**
     * 验证码短信接口
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @param yzm      验证码
     * @throws Exception
     * @author huaqingchun
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String yzmSendSms(String city, String mobile, String msg, String sendUrl, String yzm) {
        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            // 拼接内容
            sendUrl = sendUrl + city + "/" + "mobileno/" + mobile + "?" + "msg=" + msg + "&yzm=" + yzm;
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }
        return jsonStr;
    }


    /**
     * 验证码短信接口
     *
     * @param city     城市 如：nj、wx
     * @param mobileno 手机号码
     * @param msg      发送内容
     * @param yzm      验证码
     * @throws Exception
     * @author charmyin
     * @version [v1.0.0, 2015年2月11日]
     * @since [产品/模块版本](可选)
     */
    public static String sendSeckillRemindSms(String city, String mobile, String msg, String sendUrl) {
        // 调用接口返回值
        String jsonStr = "";
        // 取得短信接口URL
        try {
            // 设置短信内容编码
            msg = URLEncoder.encode(msg, "GBK");
            // 拼接内容
            sendUrl = sendUrl + city + "/" + "mobileno/" + mobile + "?" + "msg=" + msg;
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("短信接口异常：发送短信失败！");
        }
        return jsonStr;
    }


    /**
     * 业务处理报警短信
     */
    public static void doBusinessErrorSms(String sendMessage) {
        if (StringUtils.isNotEmpty(sendMessage)) {
            try {
                String smsPeopleStr = MemoryPropertyPlaceholderConfigurer.getContextProperty(
                    "system.default.smsPeople");
                String[] smsPeoples = smsPeopleStr.split(",");
                for (String smsPeople : smsPeoples) {
                    sendSms("nj", smsPeople,
                            sendMessage.substring(sendMessage.length() > 130 ? sendMessage.length() - 130 : 0,
                                                  sendMessage.length()));
                }
            } catch (Exception e) {
                LOGGER.error("短信接口异常：接口预警短信发送失败！");
            }
        }
    }

    /**
     * Test
     */
    public static void main(String[] args) throws Exception {
        String result = SmsUtils.sendSeckillRemindSms("nj", "13270838331", "请在5分钟内输入验证码，过期需重新申请",
                                                      "http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/70/depart/1/city/");
        System.out.println("短信返回：" + result);
        //String result = SmsUtils.shakeSendSms("nj", "18626460868", "您的验证码是：1234，请在5分钟内输入验证码，过期需重新申请",69, "system.shake.smsUrl");
        //System.out.println("短信返回：" + result);
    }

}
