package com.cnd3b.utility.qywechat.tools;

import com.alibaba.fastjson.JSONObject;
import com.cnd3b.utility.qywechat.base.GetAccessToken;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
/**
 * 成员增删改查
 * @author jxbyadmin
 *
 */
public class Users {
	public String createUser(String userid,String name,String department,String mobile,String email,String weixinid) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token="
						+ GetAccessToken.get());
		try {
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(createJson(userid,name,department,mobile,email,weixinid).getBytes(StandardCharsets.UTF_8));// 传入参数
			os.flush();
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			return new String(jsonBytes, StandardCharsets.UTF_8);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "createUser 失败";
	}
	public String updateUser(String userid,String name,String department,String mobile,String email,String weixinid) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token="
						+ GetAccessToken.get());	
		try {
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(createJson(userid,name,department,mobile,email,weixinid).getBytes(StandardCharsets.UTF_8));// 传入参数
			os.flush();
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			return new String(jsonBytes, StandardCharsets.UTF_8);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "updateUser 失败";
	}
	
	public String deleteUser(String userid) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token="
						+ GetAccessToken.get() + "&userid=" + userid);
		URLConnection connection = url.openConnection();
		// 获取媒体文件上传的输入流（从微信服务器读数据）
		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		StringBuffer content = new StringBuffer();
		String line = null;
		while ((line = in.readLine()) != null) {
			content.append(line);
		}
		in.close();
		// 测试打印结果
	return  content.toString();
	}
	
	public String getUser(String userid) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="
						+ GetAccessToken.get() + "&userid=" + userid);
		URLConnection connection = url.openConnection();
		// 获取媒体文件上传的输入流（从微信服务器读数据）
		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		StringBuffer content = new StringBuffer();
		String line = null;
		while ((line = in.readLine()) != null) {
			content.append(line);
		}
		in.close();
		// 测试打印结果
	return  content.toString();
	}
	
	/**
	 * 获取部门成员
	 * @param department_id 获取的部门id
	 * @param fetch_child 1/0：是否递归获取子部门下面的成员
	 * @param status 0获取全部成员，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加，未填写则默认为4
	 * @return
	 * @throws IOException
	 */
	public String getUsers(String department_id,String fetch_child,String status) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token="
						+ GetAccessToken.get() + "&department_id=" + department_id
						+ "&fetch_child=" + fetch_child+ "&status=" + status);
		URLConnection connection = url.openConnection();
		// 获取媒体文件上传的输入流（从微信服务器读数据）
		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		StringBuffer content = new StringBuffer();
		String line = null;
		while ((line = in.readLine()) != null) {
			content.append(line);
		}
		in.close();
		// 测试打印结果
	return  content.toString();
	}
	
	/**
	 * 获取部门成员(详细信息)
	 * @param department_id 获取的部门id
	 * @param fetch_child 1/0：是否递归获取子部门下面的成员
	 * @param status 0获取全部成员，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加，未填写则默认为4
	 * @return
	 * @throws IOException
	 */
	public String getUsersWithMx(String department_id,String fetch_child,String status) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="
						+ GetAccessToken.get() + "&department_id=" + department_id
						+ "&fetch_child=" + fetch_child+ "&status=" + status);
		URLConnection connection = url.openConnection();
		// 获取媒体文件上传的输入流（从微信服务器读数据）
		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		StringBuffer content = new StringBuffer();
		String line = null;
		while ((line = in.readLine()) != null) {
			content.append(line);
		}
		in.close();
		// 测试打印结果
	return  content.toString();
	}
	
	public String createJson(String userid,String name,String department,String mobile,String email,String weixinid){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userid", userid);
		jsonObject.put("name", name);
		jsonObject.put("department", "1");
		jsonObject.put("mobile", mobile);
		jsonObject.put("email", email);
		jsonObject.put("weixinid", weixinid);
		
		return jsonObject.toString();
	}
	
	
}
