package com.iamberry.wechat.service.sendmsg;

import com.iamberry.app.config.ImberryConfig;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.face.sendmsg.CodeService;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月1日
 * @explain	验证码业务实现类
 */
@SuppressWarnings("unused")
@Service
public class CodeServiceImpl implements CodeService {

	@Autowired
	private RatFWLogger logger;
	private static String ENCODING = "UTF-8";
	private static Random rnd = new Random();

	//向特定手机发送验证码
	@Override
	public String informShipping(String phone, String text) {
		return sendOtherCMS(phone,text);
	}

	/**
	 * 向指定手机发送短信 返回发送结果
	 * @param phone	电话
	 * @param text	短信内容
	 * @return
	 */
	private String sendOtherCMS(String phone, String text) {
		String results = sendSms(text,phone);
		logger.info("向手机：" + phone + ",发送短信：" + text + ",返回结果-->>" + results);
        JSONObject json =  JSONObject.fromObject(results);
        String resultcod  = json.get("code").toString();
        if("0".equals(resultcod)){
        	return "SUCCESS";
        }else{
        	return "验证码发送失败，请稍后重试";
        }
	}

	/**
	 * 配置云片相关信息并发送请求
	 * @param text		发送的内容
	 * @param mobile	手机号
	 * @return
	 */
	public static String sendSms(String text, String mobile)  {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", ImberryConfig.INTER_SMS_KEY);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(ImberryConfig.INTER_SMS_URL, params);
    }

	/** 基于HttpClient 4.3的通用POST方法
	 * @param url       提交的URL
	 * @param paramsMap 提交<参数，值>Map
	 * @return 提交响应
	 */
	public static String post(String url, Map<String, String> paramsMap) {
		CloseableHttpClient client = HttpClients.createDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost method = new HttpPost(url);
			if (paramsMap != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
					paramList.add(pair);
				}
				method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
			}
			response = client.execute(method);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return responseText;
	}
}
