package com.yeejoin.amos.fas.core.util;

import fr.opensagres.xdocreport.core.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;

/**
 * HttpServletResponse帮助类
 * 
 * @author arron.wu
 * 
 */
public final class ResponseUtils {
	public static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

	/**
	 * 发送文本。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderText(HttpServletResponse response, String text) {
		render(response, "text/plain;charset=UTF-8", text);
	}

	/**
	 * 发送json。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderJson(HttpServletResponse response, String text) {
		render(response, "text/plain;charset=UTF-8", text);

	}
	


	
	/**
	 * 发送xml。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderXml(HttpServletResponse response, String text) {
		render(response, "text/xml;charset=UTF-8", text);
	}

	/**
	 * 发送内容。使用UTF-8编码。
	 * 
	 * @param response
	 * @param contentType
	 * @param text
	 */
	public static void render(HttpServletResponse response, String contentType, String text) {
		// response.setBufferSize(arg0);
		response.setContentType(contentType);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	public static void renderImage(HttpServletResponse response, InputStream inputStream) throws IOException {
		response.setContentType("image/jpeg");

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		OutputStream outputStream = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer, 0, len);
		}
	}
	
	/*public static void downPhotoByStudentId(InputStream inputStream, final HttpServletResponse response) throws IOException{
		byte[] data = new byte[inputStream.available()];
		Integer size=data.length;
		inputStream.read(data);
		String fileName = "jcsh.apk";
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
		response.addHeader("Content-Length", size.toString());
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
	}*/
	
	
	/**
	 * 
	 * @param inputStream
	 * @param response
	 * @param size 
	 * @throws IOException
	 */
	public static void downFileByInputStream(String fileName,InputStream inputStream, final HttpServletResponse response, String open) throws IOException{
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.reset();
		if("1".equals(open)){
			response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
			if(fileName.endsWith(".pdf")){
				response.setContentType("application/pdf;charset=UTF-8");
			}else if(fileName.endsWith(".doc")||fileName.endsWith(".docx")){
				response.setContentType("application/msword;charset=UTF-8");
			}else{
				response.setContentType("application/octet-stream;charset=UTF-8");
			}
		}else{
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
		}
		response.addHeader("Content-Length", inputStream.available()+"");
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		IOUtils.copy(inputStream, outputStream);
		outputStream.flush();
		outputStream.close();
	}
	
	public static void renderFile(HttpServletResponse response, InputStream inputStream,String fileName) throws IOException {
		response.reset();
		response.setContentType("application/x_msdownload");
		response.setHeader("Content-Type", "application/octet-stream");
		response.addHeader("Content-Disposition", "attachment;filename="
			     + new String(fileName.getBytes(), "ISO8859-1"));
		OutputStream outputStream = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer, 0, len);
		}
	}
	
	/**
	 * 根据属性，获取get方法
	 * @param ob 对象
	 * @param name 属性名
	 * @return
	 * @throws Exception
	 */
	public static Object getGetMethod(Object ob , String name)throws Exception{
		Method[] m = ob.getClass().getMethods();
		for(int i = 0;i < m.length;i++){
			if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
				return m[i].invoke(ob);
			}
		}
		return null;
	}
	
	/**
	 * 根据属性，拿到set方法，并把值set到对象中
	 * @param obj 对象
	 * @param fileName 需要设置值得属性
	 * @param type 
	 * @param value
	 */
	public static void setValue(Object obj,String filedName,Class<?> type,Object value){
		Class<?> clazz = obj.getClass();
		filedName = removeLine(filedName);
		String methodName = "set" + filedName.substring(0,1).toUpperCase()+filedName.substring(1);
		try{
			Method method =  clazz.getDeclaredMethod(methodName, new Class[]{type});
			method.invoke(obj, new Object[]{getClassTypeValue(type, value)});
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
     * 通过class类型获取获取对应类型的值
     * @param typeClass class类型
     * @param value 值
     * @return Object
     */
	private static Object getClassTypeValue(Class<?> typeClass, Object value){
        if(typeClass == int.class  || value instanceof Integer){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == short.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == byte.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == double.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == long.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == String.class){
            if(null == value){
                return "";
            }
            return value;
        }else if(typeClass == boolean.class){
            if(null == value){
                return true;
            }
            return value;
        }else if(typeClass == BigDecimal.class){
            if(null == value){
                return new BigDecimal(0);
            }
            return new BigDecimal(value+"");
        }else {
            return typeClass.cast(value);
        }
    }
    /**
     * 处理字符串  如：  abc_dex ---> abcDex
     * @param str
     * @return
     */
    public static  String removeLine(String str){
		if(null != str && str.contains("_")){
			int i = str.indexOf("_");
			char ch = str.charAt(i+1);
			char newCh = (ch+"").substring(0, 1).toUpperCase().toCharArray()[0];
			String newStr = str.replace(str.charAt(i+1), newCh);
			String newStr2 = newStr.replace("_", "");
			return newStr2;
		}
		return str;
	}
}
