package com.ssm.core.utils;

import com.alibaba.fastjson.JSON;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.query.SmsSendRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.SmsSendResponse;
import com.ssm.manage.response.UserResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class SmsType {

    //深圳创蓝
    /**
     *
     * @Description
     * @param path
     * @param postContent
     * @return String
     * @throws
     */
    public static String sendSmsByPost(String path, String postContent) throws SmsException {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

            httpURLConnection.connect();
                OutputStream os=httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }

        } catch (Exception e) {
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION,e.toString());
        }
        return null;
    }


    /****
     * 发送短信
     * @param url
     * @param account
     * @param pswd
     * @param phone
     * @return
     */
    public static UserResponse sendSmsCode(String url, String account, String pswd, String phone, String msg) throws SmsException {

        if(account == null || account.trim().equals("")) {
            throw new SmsException(ResponseCode.SMS_ACCOUNT_IS_NULL);
        }
        //短信发送的URL 请登录zz.253.com 获取完整的URL接口信息
        if(url == null || url.trim().equals("")) {
            throw new SmsException(ResponseCode.SMS_URL_IS_NULL);
        }

        if(pswd == null || pswd.trim().equals("")) {
            throw new SmsException(ResponseCode.SMS_PASSWORD_IS_NULL);
        }
        if(phone == null || phone.trim().equals("")) {
            throw new SmsException(ResponseCode.PHONE_IS_NULL);
        }
        String report= "true";
        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, pswd, msg, phone.trim(),report);//13060685020//
        String requestJson = JSON.toJSONString(smsSingleRequest);
        //String requestJson = JsonHelper.toJson(smsSingleRequest);
        String response = SmsType.sendSmsByPost(url, requestJson);
        //String response = ChuangLanSmsUtil.sendMsg(url,account,pswd,"13226273079",msg);
        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        UserResponse userResponse = new UserResponse();
//		System.out.println("response  toString is :" + smsSingleResponse);
        if(!smsSingleResponse.getCode().equals("0")) {
            throw new SmsException(ResponseCode.SMS_SEND_EXCEPTION,smsSingleResponse.getErrorMsg());
        }else {
            userResponse.setSendSmsStatus(true);
        }
        return userResponse;
    }

    /****
     * 发送短信
     * @param url
     * @param account
     * @param pswd
     * @param phone
     */
    public static UserResponse sendSmsCodeFG(String url, String account, String pswd, String phone, String msg,String signId) throws SmsException {
        try{
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type","application/json");
            Map<String,Object> map = new HashMap<>();
            map.put("apikey",account);
            map.put("secret",pswd);
            map.put("sign_id",signId);
            map.put("mobile",phone);
            map.put("content",msg);
            String json = JSON.toJSONString(map);
            httpPost.setEntity(new StringEntity(json,"UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            System.out.println("短信发送成功："+res);

            UserResponse userResponse = new UserResponse();
            userResponse.setSendSmsStatus(true);
//		System.out.println("response  toString is :" + smsSingleResponse);
            return userResponse;
        }catch (Exception e){
            throw new SmsException(ResponseCode.MSG,"短信发送异常"+e.getMessage());
        }
    }
}
