package com.ifish.netease;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ifish.enums.NeteaseEnum;
import com.ifish.util.IfishUtil;

@SuppressWarnings("deprecation")
public class NeteaseIM {
	
	String appKey = "87b0e3315dfc2df08060bcb54246da68";
	String appSecret = "e62f6c247b46";
	
	private static Logger log = LoggerFactory.getLogger(NeteaseIM.class);
	
	/**
	 * 创建云信ID
	 * @param accid  云信ID，最大长度32字符，必须保证一个APP内唯一
	 * @param name   云信ID昵称，最大长度64字符，用来PUSH推送 时显示的昵称
	 * @param icon   云信ID头像URL，第三方可选填，最大长度1024
	 * @param props  json属性，第三方可选填，最大长度1024字符
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> createAccid(String accid,String name,String icon,String props){
		try {
			
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/user/create.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("accid", accid));
			nvps.add(new BasicNameValuePair("name", name));
			nvps.add(new BasicNameValuePair("icon", icon));
			nvps.add(new BasicNameValuePair("props", props));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				JSONObject infoJson = json.getJSONObject("info");
				String token = infoJson.getString("token");
				map.put("token", token);
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("CreateAccid error message:{},{}",accid,e.toString());
		}
		return null;
	}
	
	/**
	 * 更新并获取新token
	 * @param accid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> refreshToken(String accid){
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/user/refreshToken.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("accid", accid));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				JSONObject infoJson = json.getJSONObject("info");
				String token = infoJson.getString("token");
				map.put("token", token);
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("refreshToken error message:{},{}",accid,e.toString());
		}
		return null;
	}
	
	/**
	 * 更新用户信息
	 * @param accid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> updateUinfo(String accid,String name,String icon,String ex){
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/user/updateUinfo.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("accid", accid));
			nvps.add(new BasicNameValuePair("name", name));
			nvps.add(new BasicNameValuePair("icon", icon));
			nvps.add(new BasicNameValuePair("ex", ex));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("updateUinfo error message:{},{}",accid,e.toString());
		}
		return null;
	}
	
	/**
	 * 获取用户信息
	 * @param accid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> getUinfos(String accids){
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/user/getUinfos.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("accids", accids));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("getUinfos error message:{},{}",accids,e.toString());
		}
		return null;
	}
	
	/**
	 * 发送普通消息
	 * @param from
	 * @param to
	 * @param msg
	 * @return
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> sendMsg(String from,String to,String msg,String ext){
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/msg/sendMsg.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("from", from));
			nvps.add(new BasicNameValuePair("to", to));
			nvps.add(new BasicNameValuePair("ope", "0"));
			nvps.add(new BasicNameValuePair("type", "0"));
			nvps.add(new BasicNameValuePair("body", "{\"msg\":\""+msg+"\"}"));
			nvps.add(new BasicNameValuePair("ext", ext));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("refreshToken error message:{}",e.toString());
		}
		return null;
	}
	/**
	 * 批量发送点对点普通消息
	 * @param fromAccid
	 * @param toAccids
	 * @param msg
	 * @return
	 */
	@SuppressWarnings({"resource"})
	public Map<String, String> sendBatchMsg(String fromAccid,String toAccids,String msg){
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String url = "https://api.netease.im/nimserver/msg/sendBatchMsg.action";
			HttpPost httpPost = new HttpPost(url);
			String nonce =  IfishUtil.getCharAndNumr(10);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			//计算CheckSum
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
			//设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("fromAccid", fromAccid));
			nvps.add(new BasicNameValuePair("toAccids", toAccids));
			nvps.add(new BasicNameValuePair("type", "0"));
			nvps.add(new BasicNameValuePair("body", "{\"msg\":\""+msg+"\"}"));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			//执行请求
			HttpResponse response = httpClient.execute(httpPost);
			//执行结果
			String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject json = JSON.parseObject(responseStr);
			String code = json.getString("code");
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			//200
			if(code.equals(NeteaseEnum.status200.getKey())){
				
			}
			else if(code.equals(NeteaseEnum.status414.getKey())){
				//String desc = json.getString("desc");
			}
			return map;
		} catch (Exception e) {
			log.error("refreshToken error message:{}",e.toString());
		}
		return null;
	}
	
}
