package hls.plugin.weixin.qiye;

import hls.plugin.weixin.common.HttpUtil;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
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 WeiImageUpload
{
  public JSONObject send(String fileType, String filePath, String id, String secret)
    throws Exception
  {
    String result = null;
    File file = new File(filePath);
    if ((!file.exists()) || (!file.isFile())) {
      throw new IOException("文件不存在");
    }
    String token = getNowToken(id, secret);

    URL urlObj = new URL("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + 
      "&type=" + fileType);
    HttpURLConnection con = (HttpURLConnection)urlObj.openConnection();
    con.setRequestMethod("POST");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);

    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Charset", "UTF-8");

    String BOUNDARY = "----------" + System.currentTimeMillis();
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] head = sb.toString().getBytes("utf-8");

    OutputStream out = new DataOutputStream(con.getOutputStream());

    out.write(head);

    DataInputStream in = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = in.read(bufferOut)) != -1) {
      out.write(bufferOut, 0, bytes);
    }
    in.close();

    byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
    out.write(foot);
    out.flush();
    out.close();
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = null;
    try
    {
      reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null)
      {
        buffer.append(line);
      }
      if (result == null)
        result = buffer.toString();
    }
    catch (IOException e) {
      System.out.println("发送POST请求出现异常！" + e);
      e.printStackTrace();
      throw new IOException("数据读取异常");
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
    JSONObject jsonObj = JSONObject.fromObject(result);
    System.out.println("jsonObj>>>>" + jsonObj);
    return jsonObj;
  }

  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) {
    try {
      JSONObject jsonObj = new WeiImageUpload().send("image", "C:/Users/Administrator/Desktop/pak/3.jpg", "wx4257809fde0f5986", "iTgSpAaEYejcyPBLlyikzx6kvSVuiMBxotfAkAdWAKo6nF8cefdJSTgLXqivXpZ7");

      System.out.println(jsonObj.getString("media_id"));
      System.out.println(jsonObj.getString("created_at"));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public static Map<String, String> weiUpload(String fileType, String filePath, String id, String secret)
  {
    Map map = new HashMap();
    try {
      JSONObject jsonObj = new WeiImageUpload().send(fileType, filePath, id, secret);
      map.put("media_id", jsonObj.getString("media_id"));
      map.put("created_at", jsonObj.getString("created_at"));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return map;
  }
}