package com.yem.tws.aip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class FileUploadService {
	
	private static final FileUploadService service = new FileUploadService();
	
	private static final String BOUNDARY = "----WebKitFormBoundaryBHp47SjGMxpHX0X6--";
	
	private FileUploadService() {}
	
	//静态工厂方法
	public static FileUploadService getService() {
		return service;
	}
	
	public String postFile(String url, Map<String, Object> param, File file, String accessToken) throws Exception {
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("api", "true");
		httppost.addHeader("accessToken", accessToken);
		//设置boundary,文件解析�?,不可省略
		httppost.addHeader("Content-Type",  "multipart/form-data; boundary="+BOUNDARY);
		MultipartEntity entry = this.getMutipartEntry(param, file);
		httppost.setEntity(entry);
		return HttpService.getService().doExecuteByHttpClient(httppost, new ResponseHandler<String>() {
			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				HttpEntity entity = response.getEntity();
				String  rtn =  EntityUtils.toString(entity, "UTF-8");
				JSONObject json  = JSONObject.parseObject(rtn);
				String url  = json.getString("url");
				return url;
			}
		});
	}
    
    private MultipartEntity getMutipartEntry(Map<String, Object> param, File file) 
			throws UnsupportedEncodingException, FileNotFoundException {
    	if (file == null) {
    		throw new IllegalArgumentException("文件不能为空");
        }
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, BOUNDARY, Charset.forName("UTF-8"));
        multipartEntity.addPart("file", new InputStreamBody(new FileInputStream(file), file.getName()));
        if (param != null) {
        	Iterator<String> iterator = param.keySet().iterator();
        	while (iterator.hasNext()) {
        		String key = iterator.next();
        		FormBodyPart field = new FormBodyPart(key, new StringBody((String) param.get(key)));
        		multipartEntity.addPart(field);
        	}
        }
        return multipartEntity;
    }
}
