package cn.base.servlet;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import cn.base.bean.BeanHelper;
import cn.base.conf.ModuleConfFactory;
import cn.base.util.StringUtil;

public class SourceProxy extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static Logger log = Logger.getLogger(SourceProxy.class);
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.reset();
		response.setHeader("Expires", "Sat, 10 May 2059 12:00:00 GMT");
		response.setHeader("Cache-Control", "max-age=315360000");
		FileInputStream hFile = null;
		OutputStream toClient = null;
		InputStream inputStream = null;
		BufferedInputStream bis = null;
		try {
			String fileType = request.getParameter("fileType");
			String filePath = request.getParameter("filePath");
			String contentType = request.getParameter("contentType");
			if(StringUtil.isEmpty(contentType)) contentType ="image/jpeg";
		
			if(fileType.equals("resourcePath")) { //获取服务器上的文件,传人全路径
				response.setContentType(contentType); // 设置返回的文件类型
				String resourcePath = ModuleConfFactory.getInstance().getScatter().getResourcePath();
				int j = filePath.lastIndexOf("/");
				String temNmae = "";
				if (j > 0) {
					temNmae = filePath.substring(j + 1);
				} else {
					temNmae = filePath;
				}
				response.setHeader("Content-disposition", "attachment;fileName=" + StringUtil.toUtf8String(temNmae));
				//String path = BeanHelper.getConfService().getScatter().getPicStorePath()+filePath;
				File file = new File(resourcePath+filePath);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			} else if (fileType.equals("imageHot")){//获取服务器上的文件,传人全路径
				response.setContentType(contentType); // 设置返回的文件类型
				
		//		String beiAnPhotoUrl = ModuleProps.getInstance().getTinyCfg().getTracePath();
		//		String imageHot = ModuleProps.getInstance().getTinyCfg().getImageHot();
				String imageHot = "D:/vp/uploadPath/";
				int j = filePath.lastIndexOf("/");
				String temNmae = "";
				if (j > 0) {
					temNmae = filePath.substring(j + 1);
				} else {
					temNmae = filePath;
				}
				response.setHeader("Content-disposition", "attachment;fileName=" + StringUtil.toUtf8String(temNmae));
				File file = new File(imageHot+filePath);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			}else if (fileType.equals("beiAnPhotoUrl")){//获取服务器上的文件,传人全路径
				response.setContentType(contentType); // 设置返回的文件类型
				String beiAnPhotoUrl = ModuleConfFactory.getInstance().getScatter().getTracePath();
				int j = filePath.lastIndexOf("/");
				String temNmae = "";
				if (j > 0) {
					temNmae = filePath.substring(j + 1);
				} else {
					temNmae = filePath;
				}
				response.setHeader("Content-disposition", "attachment;fileName=" + StringUtil.toUtf8String(temNmae));
				File file = new File(beiAnPhotoUrl+filePath);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			}
			
			else if(fileType.equals("loclFileProxy")) { //获取服务器上的文件,传人全路径
				response.setContentType(contentType); // 设置返回的文件类型
				int j = filePath.lastIndexOf("/");
				String temNmae = "";
				if (j > 0) {
					temNmae = filePath.substring(j + 1);
				} else {
					temNmae = filePath;
				}
				response.setHeader("Content-disposition", "attachment;fileName=" + StringUtil.toUtf8String(temNmae));
				//String path = BeanHelper.getConfService().getScatter().getPicStorePath()+filePath;
				File file = new File(filePath);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			} else if(fileType.equals("shootPhotoProxy")) { //获取服务器上的文件,供三大库使用
				response.setContentType(contentType); // 设置返回的文件类型
				int j = filePath.lastIndexOf("/");
				String temNmae = "";
				if (j > 0) {
					temNmae = filePath.substring(j + 1);
				} else {
					temNmae = filePath;
				}
				response.setHeader("Content-disposition", "attachment;fileName=" + StringUtil.toUtf8String(temNmae));
				String path = BeanHelper.getModuleConfFactory().getScatter().getBasePath()+filePath;
				File file = new File(path);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			} else if(fileType.equals("vehiclePicProxy")) { //获取服务器上的文件,供车辆布控使用
				response.setContentType(contentType); // 设置返回的文件类型
				String path = "";//BeanHelper.getConfService().getScatter().getVehicleStorePath()+filePath;
				File file = new File(path);
				long fileLen = file.length();
				response.setContentLength((int) fileLen);
				hFile = new FileInputStream(file);
				toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				IOUtils.copy(hFile, toClient);
				return;
			} else if(fileType.equals("vehiclePic")) { //根据过车ID获取图片信息,现场定制
				response.setContentType(contentType); // 设置返回的文件类型
				try {
					String vehicleId = request.getParameter("vehicleId");
					if(StringUtil.isEmpty(vehicleId)) {
						return;
					}
					int i = 0;
					String index = request.getParameter("index");
					if(StringUtil.isNotEmpty(index)) {
						i = Integer.parseInt(index);
					}
					Map map = new HashMap();
					map.put("vehicleId", vehicleId);
					//VehicleTravelRecord vtr = BeanHelper.getVehicleTravelRecordDAO().queryTravelRecord(map);
					String tempUrl = "";// vtr.getCenterStoreKey();
					String[] vhUrls = tempUrl.split(";");
					if(vhUrls.length<=i) {
						return;
					}
					URL url = new URL(vhUrls[i]);
					// 获取网络输入流
					inputStream = url.openStream();
					bis = new BufferedInputStream(inputStream);
					toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
					IOUtils.copy(bis, toClient);
				} catch (Exception e) {
					log.error("无法打开图片：",e);
					response.setContentType("text/html;charset=GBK");
					response.setCharacterEncoding("GBK");
					PrintWriter out = response.getWriter(); // 得到向客户端输出文本的对象
					out.write("无法打开图片!");
					out.flush();
				} 
				return;
			} else if (fileType.equals("picUrlProxy")) { //图片代理
				String destUrl = request.getQueryString();
				destUrl = destUrl.substring(destUrl.indexOf("picUrl=")+7);
				String type = System.getProperty("file.encoding"); 
				log.info("decode type:"+type);
				if(type.toUpperCase().equals("GBK")) {
					destUrl = new String (destUrl.getBytes("ISO8859-1"),"GBK"); 
				} else {
					destUrl = StringUtil.toUtf8String(destUrl);
				}
				log.info("decode destUrl:"+destUrl);
				//BufferedInputStream bis = null;
				try {
					String tempUrl = destUrl;
					tempUrl = tempUrl.replaceAll("\\\\", "/");
					URL url = new URL(tempUrl);
					// 获取网络输入流
					inputStream = url.openStream();
					bis = new BufferedInputStream(inputStream);
					toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
					IOUtils.copy(bis, toClient);
				} catch (Exception e) {
					log.error("无法打开图片：",e);
					response.setContentType("text/html;charset=GBK");
					response.setCharacterEncoding("GBK");
					PrintWriter out = response.getWriter(); // 得到向客户端输出文本的对象
					out.write("无法打开图片!");
					out.flush();
				}
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeAllIO(bis, toClient, hFile, inputStream);
		}
	}

	//关闭所有IO流
	private void closeAllIO(BufferedInputStream bis,OutputStream toClient,FileInputStream hFile,InputStream inputStream) {
		try {
			if(bis!=null)
				bis.close();
			if(toClient!=null)
				toClient.close();
			if(hFile!=null) 
				hFile.close();
			if(inputStream!=null)
				inputStream.close();
		} catch (IOException e) {
			//iLog.error("IO关闭失败："+e);
		}
	}
}
