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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.cnd3b.utility.qywechat.base.GetAccessToken;

/**
 * 下载媒体素材文件
 * 
 * @author Administrator
 * 
 */
public class DownLoad {
	long file_size = 0;

	/**
	 * 下载临时素材文件
	 * 
	 * @param MediaId
	 * @param savefile
	 */
	public DownLoad(String MediaId, String savefile) {
		String access_token = GetAccessToken.get();
		URL url = null;
		try {
			url = new URL(
					"https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="
							+ access_token + "&media_id=" + MediaId);
			down(url, savefile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载永久素材文件
	 * 
	 * @param MediaId
	 * @param savefile
	 */
	public DownLoad(String appid, String MediaId, String savefile) {
		String access_token = GetAccessToken.get();
		URL url = null;
		try {
			url = new URL(
					"https://qyapi.weixin.qq.com/cgi-bin/material/get?access_token="
							+ access_token + "&media_id=" + MediaId
							+ "&agentid=" + appid);
			down(url, savefile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void down(URL url, String savefile) throws IOException {
		
		int byteread = 0;
		URLConnection conn = url.openConnection();
		InputStream inStream = conn.getInputStream();
		FileOutputStream fs = new FileOutputStream(savefile);
		byte[] buffer = new byte[1024];
		while ((byteread = inStream.read(buffer)) != -1) {
			fs.write(buffer, 0, byteread);
		}
		file_size = conn.getContentLengthLong();
		inStream.close();
		fs.close();
	}

	/**
	 * 获取下载文件的大小
	 * @return
	 */
	public String getfilesize() {
		double max = 1024.00d;
		if (file_size / max == 0) {
			return (file_size) + "bit";
		} else if (file_size / max < 1024) {
			return (file_size / max) + "kb";
		} else if (file_size / (max * max) < 1024) {
			return (file_size / (max * max)) + "mb";
		} else {
			return (file_size / (max * max * max)) + "gb";
		}
	}
}
