package com.cnd3b.utility.qywechat.tools.media_manage;

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class UpLoad {
	String result = "";
	/**
	 * 上传临时素材文件
	 * 
	 * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
	 * @param files 文件地址
	 */
	public UpLoad(String type, String files) throws IOException { 
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="
						+ GetAccessToken.get() + "&type=" + type);
		File file = new File(files);
		Up(url, file);
	}
	/**
	 * 上传永久素材文件
	 * 
	 * @param appid 应用ID
	 * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
	 * @param files 文件地址
	 */
	public UpLoad(String appid,String type,String files) throws IOException {
		URL url = new URL(
				"https://qyapi.weixin.qq.com/cgi-bin/material/add_material?agentid="+appid+"&type="+type+"&access_token="+GetAccessToken.get());
		File file = new File(files);
		Up(url, file);
	}

	public void Up(URL url, File file) throws IOException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		// 设置请求头信息
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Charset", "UTF-8");
		String BOUNDARY = "----------" + System.currentTimeMillis();
		connection.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + BOUNDARY);
		// -------------------------------
		// 第一部分：

		String sb = "--" + // 必须多两道线
				BOUNDARY +
				"\r\n" +
				"Content-Disposition: form-data;name=\"file\";filename=\""
				+ file.getName() + "\"\r\n" +
				"Content-Type:application/octet-stream\r\n\r\n";
		byte[] head = sb.getBytes(StandardCharsets.UTF_8);
		// 获得输出流
		OutputStream outputStream = connection.getOutputStream();
		// 输出表头
		outputStream.write(head);
		// -------------------------------

		// 获取媒体文件的输入流（读取文件）
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		byte[] buf = new byte[1024];
		int size = 0;
		while ((size = bis.read(buf)) != -1) {
			// 将媒体文件写到输出流（往微信服务器写数据）
			outputStream.write(buf, 0, size);
		}

		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8);// 定义最后数据分隔线
		outputStream.write(foot);

		// 请求体结束
		outputStream.close();
		bis.close();

		// 获取媒体文件上传的输入流（从微信服务器读数据）
		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();
		// 测试打印结果
		result = content.toString();
	}

	public String getresult() {
		return result;
	}
	public String getMedia_id() {
		JSONObject jsonObject = JSONObject.parseObject(result);
		return(String) jsonObject.get("media_id");
	}
}
