package com.yihu.jw.sms.service;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 物联网短信网关
 *
 * @author hmf
 */
@Service
public class IotSMSService {

    @Value("${wlyy.url}")
    private String wlyyUrl;

    @Autowired
    private HttpClientUtil httpClientUtil;

    public String IotSendSMS(String mobileStr, String content) throws Exception {
        //请求i健康发送短信接口
        String url = wlyyUrl+"wlyygc/doctor/message/sendMobileMessage";
        List<NameValuePair> par = new ArrayList<NameValuePair>();
        par.add(new BasicNameValuePair("mobiles", mobileStr));
        par.add(new BasicNameValuePair("content", content));
        String result = httpClientUtil.post(url,par,"UTF-8");
        System.out.println("短信接口返回结果result：" + result);
        JSONObject re = JSONObject.parseObject(result);
        if (re.getInteger("status") != 10000) {
            // 发送失败
            throw new Exception("短信发送失败！");
        } else {
            return "success";
        }
    }

    public static JSONObject toJson(String result) {
        JSONObject json = new JSONObject();
        try {
            String[] temps = result.split("&");
            for (String temp : temps) {
                if (temp.split("=").length != 2) {
                    continue;
                }
                String key = temp.split("=")[0];
                String value = temp.split("=")[1];
                json.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}
