package hls.plugin.weixin.qiye;

import hls.plugin.weixin.common.HttpUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeixinDownload
{
  static WeixinDownload weixinMedia = null;

  public static String downloadMedia(String accessToken, String mediaId, String savePath, String imageName)
  {
    String filePath = null;

    String filetype = "";
    HttpURLConnection conn = null;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
    requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
    try {
      URL url = new URL(requestUrl);
      conn = (HttpURLConnection)url.openConnection();
      conn.setDoInput(true);
      conn.setRequestMethod("GET");

      if (!savePath.endsWith("/")) {
        savePath = savePath + "/";
      }

      String fileExt = WeixinUtil.getTypeByStream(conn.getHeaderField("Content-Type"));

      filePath = savePath + imageName + "." + fileExt.substring(fileExt.indexOf("/") + 1);
      filetype = fileExt.substring(fileExt.indexOf("/") + 1);
      bis = new BufferedInputStream(conn.getInputStream());
      fos = new FileOutputStream(new File(filePath));
      byte[] buf = new byte[1024];
      int size = 0;
      while ((size = bis.read(buf)) != -1)
        fos.write(buf, 0, size);
    }
    catch (Exception e) {
      filePath = null;
      String error = String.format("ÏÂÔØÃ½ÌåÎÄ¼þÊ§°Ü", new Object[] { e });
      e.printStackTrace();
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bis != null) {
        try {
          bis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (conn != null) {
        conn.disconnect();
      }
    }
    return filetype;
  }
  public static String getNowToken(String id, String secret) {
    String returnString = "";
    String requestUrl = getNowTokenURL(id, secret);
    JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
      requestUrl, "GET"));

    if (jsonObject != null) {
      try {
        returnString = jsonObject.getString("access_token");
      } catch (JSONException e) {
        returnString = null;
      }
    }
    return returnString;
  }

  public static String getNowTokenURL(String id, String secret) {
    String mutiurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + id + "&corpsecret=" + secret;
    return mutiurl;
  }
  public static void main(String[] args) {
    weiDownload("wx4257809fde0f5986", "iTgSpAaEYejcyPBLlyikzx6kvSVuiMBxotfAkAdWAKo6nF8cefdJSTgLXqivXpZ7", "1qyU7RGN3LHdsMrqCw7VrTc85wY-Q5Z3pEk_VJKcU9E3Nx_ukMH7ik2Vp_43EiMa6VyEjpNwtuEQ2ILqoe7F5cA", "G:/pad/");
  }
  private static String createImageName() {
  	return (long)(Math.random()*10000000)+"";
//      return Long.toString(System.currentTimeMillis() / 1000);
  }

  public static Map<String, String> weiDownload(String id, String secret, String mediaId, String savePath) {
    Map map = new HashMap();
    String accessToken = getNowToken(id, secret);
    String imageName = createImageName();
    String filetype = downloadMedia(accessToken, mediaId, savePath, imageName);
    String  fileSize=getFileSize(savePath,imageName,filetype)+"";
    map.put("fileName", imageName);
    map.put("filetype", filetype);
    map.put("fileSize", fileSize);
    return map;
  }
  public static long getFileSize(String savePath, String imageName, String filetype) {
    long fileSize = 0L;
    File file = new File(savePath + "/" + imageName + "." + filetype);
    if ((file.exists()) && (file.isFile())) {
      fileSize = file.length() / 1024L;
    }
    return fileSize;
  }
}