package com.bcxin.ins.coninsweb.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.common.constants.GlobalConstants;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.spring.annotation.LoginRequired;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.third.gzzrx.pingancai.GZZRX_PACRequestService;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.entity.R;
import com.bcxin.ins.dto.ResultDto;
import com.bcxin.ins.entity.policy_core.InsInsuranceSlip;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.DwzPage;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.pingan.iobs.sdk.model.Response;
import com.pingan.iobs.sdk.service.IobsService;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * DWZ编辑器上传图片功能
 * @author linqinglin
 *
 */
@Controller
public class FileUploadController extends BaseController {
	private static String IMG_PATH = "/upload/img/";
	private static String FLASH_PATH ="/upload/flash/";
	private static String MEDIA_PATH ="/upload/media/";


	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;
	@Autowired
	private GZZRX_PACRequestService gZZRX_PACRequestService;

	@RequestMapping(value = "/dwz/fileUpload", method = { RequestMethod.GET, RequestMethod.POST })
	public void upImg(MultipartFile filedata, HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=UTF-8");
		
		/*
		 * request.getServerName() //服务器地址  
           request.getServerPort()           //端口号  
           request.getContextPath()      //项目名称  
           request.getServletPath()      //请求页面或其他地址  
           request.getQueryString() //参数 
		*/
		/*String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		
		String fileName = filedata.getOriginalFilename(); 	//上传文件名
		
		String materialFileType = fileName.split("\\.")[1]; //文件类型
		String saveFilePath=IMG_PATH;
		if(materialFileType.equals("swf"))
			saveFilePath=FLASH_PATH;
		else if(materialFileType.equals("avi"))
			saveFilePath=MEDIA_PATH;
		
		Calendar calendar=Calendar.getInstance();
		String newFileName = calendar.getTimeInMillis() + "." + materialFileType;//随机生成新文件名
		String basePath = request.getSession().getServletContext().getRealPath("");	//获得项目路径
		String materialFilePath = basePath + saveFilePath ;//保存路径
		if(OSSFileUtil.fileUpload(filedata, newFileName, materialFilePath)){
			PrintWriter out = response.getWriter();
			String pathName = strBackUrl + saveFilePath + newFileName;//图片访问路径
			out.println("{\"err\":\"\",\"msg\":\""+pathName+"\"}");//这里返回你图片上传路径，返回json到编辑器中，这样编辑器就能及时显示图片内容了
			out.flush();
			out.close();
		}	*/
		String url = OSSFileUtil.huaweiOBSFileUpload(filedata,"");
		if (StringUtils.isNotEmpty(url)) {
			/*** 如果为生产环境，需要更换域名 ***/
			if(!GlobalResources.IS_TEST_ENVI){//生产
				String cdnUrl = GlobalResources.HW_CDN_URL;
				if(StringUtils.isNotEmpty(cdnUrl)) {
					url = cdnUrl + url.substring(url.indexOf("upload") - 1);
				}
			}
			PrintWriter out = response.getWriter();
			out.println("{\"err\":\"\",\"msg\":\""+url+"\"}");//这里返回你图片上传路径，返回json到编辑器中，这样编辑器就能及时显示图片内容了
			out.flush();
			out.close();
		}
		System.out.println("url:"+url);
	}
	
	/**
	 * <b>上传文件转base64 ，返回 图片格式，64位的字符串 </b> 
	 * 
	 * @param imageFile
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author linqinglin 
	 * @date 2016年12月21日 下午2:15:46
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/base64/fileToString")
	public JSONObject fileToString(@RequestParam(value = "file") MultipartFile imageFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String fileName = imageFile.getOriginalFilename(); 	//上传文件名
		
		String fileType = fileName.split("\\.")[1]; //文件类型
		byte[] bytes = imageFile.getBytes();

		String fileString = BASE64Util.encryptBASE64Byte(bytes);
		json.put("fileType", fileType);
		json.put("fileString", fileString);
		return json;//这里返回你图片上传路径，返回json到编辑器中，这样编辑器就能及时显示图片内容了
	}
	
	@RequestMapping(value = "/downloadAttachment")
	public void downloadAttachment(@RequestParam("oid") long oid, @RequestParam("name") String name, @RequestParam("code") String code, HttpServletResponse response) {
		InsInsuranceSlip policy = insInsuranceSlipService.selectById(oid);
		String attachPath = "";
		if("1".equals(code)){
			attachPath = policy.getInsure_path();
		}else{
			attachPath = policy.getLg_path();
		}
		long fileLength = new File(attachPath).length();
	    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(attachPath));
			BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
	    	response.reset();
	    	response.setHeader("Content-Disposition", "attachment; filename="+new String(name.getBytes("gbk"),"iso-8859-1") + ".pdf");
	    	response.setContentType("application/octet-stream; charset=utf-8");
	        response.setHeader("Content-Length", String.valueOf(fileLength));

			byte[] buff = new byte[2048];
	        int bytesRead;  
	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
	            bos.write(buff, 0, bytesRead);  
	        }  
	    } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/t/test")
	public ModelAndView test() {
		ModelAndView view = new ModelAndView("/flows/PolicySale/test");
		return view;
	}
	
	@RequestMapping("/dwz/uploadfy")
	public @ResponseBody R uploadfy(HttpServletRequest request) {
		String names = request.getParameter("name");
		String base64 = request.getParameter("base64");
		String savePath = "/policy/";
		logger.info(base64);
		if (StringUtils.isNotEmpty(base64)) {
			try {
				String fileData = base64.split(",")[1];
				byte[] bytes = BASE64Util.decryptBASE64Byte(fileData);
				String files = DateUtil.generatorRadomNumber() + "." + names;
				String result = savePath + files;
				String path = GlobalResources.COM_IMG_RE+savePath;
				FileHelp.byteFile(bytes, path, files);
				result = "/getResource?path="+result;
				return new R(true,result);
			} catch (Exception e) {
				e.printStackTrace();
				return new R(false,"异常信息："+e.getMessage());
			}
		}
		return new R(false,"文件存储失败");
	}
	
	/**
	 * <b>上传图片或文件处理 </b> 
	 * 
	 * @param file
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author linqinglin 
	 * @date 2016年12月21日 下午2:16:00
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/file/ajaxFormDataLoad")
    @ResponseBody
	public ResultDto ajaxFormDataLoad(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(file != null){
//			String fileName = request.getParameter("fileName");
			String directoryName = request.getParameter("directoryName");
			String url = OSSFileUtil.huaweiOBSFileUpload(file,directoryName);
			if (StringUtils.isNotEmpty(url)) {
				/*** 如果为生产环境，需要更换域名 ***/
				if(!GlobalResources.IS_TEST_ENVI){//生产
					String cdnUrl = GlobalResources.HW_CDN_URL;
					if(StringUtils.isNotEmpty(cdnUrl)) {
						url = cdnUrl + url.substring(url.indexOf("upload") - 1);
					}
				}
			} else {
				return new ResultDto("上传失败:" + file.getOriginalFilename(), ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			System.out.println("url:"+url);
//			Map<String, String> map = OSSFileUtil.ossFileUpload_sysc(file, directoryName, false, fileName);
			return new ResultDto(url, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("传输过程出现异常，请重新上传！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	/**
	 * <b>上传图片或文件处理(平安附件专用，同步上传平安使key生效) OSS </b>
	 *
	 * @param file
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author linqinglin
	 * @date 2016年12月21日 下午2:16:00
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/file/ajaxFormDataLoadPA")
	@ResponseBody
	public ResultDto ajaxFormDataLoadPA(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(file != null){
			String fileName = request.getParameter("fileName");
			String directoryName = request.getParameter("directoryName");
			// TODO 页面自行组装的key用于平安标识
			String fileId = request.getParameter("fileId");
			String url = OSSFileUtil.huaweiOBSFileUpload(file,directoryName);
			if (StringUtils.isNotEmpty(url)) {
				/*** 如果为生产环境，需要更换域名 ***/
				if(!GlobalResources.IS_TEST_ENVI){//生产
					String cdnUrl = GlobalResources.HW_CDN_URL;
					if(StringUtils.isNotEmpty(cdnUrl)) {
						url = cdnUrl + url.substring(url.indexOf("upload") - 1);
					}
				}
			} else {
				return new ResultDto("上传失败:" + file.getOriginalFilename(), ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
//			Map<String, String> map = OSSFileUtil.ossFileUpload_sysc(file, directoryName, false, fileName);
			System.out.println("url:"+url);
			if(gZZRX_PACRequestService.isUploadPA(file.getInputStream(),fileId,fileName)){
				System.out.println("fileName:"+fileName);
				System.out.println("directoryName:"+directoryName);
				System.out.println("fileId:"+fileId);
				return new ResultDto(url, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			return new ResultDto("同步理赔附件token获取失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("传输过程出现异常，请重新上传！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	@RequestMapping("/file/ajaxFormDataLoadOther")
	@ResponseBody
	public ResultDto ajaxFormDataLoadOther(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(file != null){
			String fileName = request.getParameter("fileName");
			String directoryName = request.getParameter("directoryName");
			String url = OSSFileUtil.huaweiOBSFileUpload(file,directoryName);
			if (StringUtils.isNotEmpty(url)) {
				/*** 如果为生产环境，需要更换域名 ***/
				if(!GlobalResources.IS_TEST_ENVI){//生产
					String cdnUrl = GlobalResources.HW_CDN_URL;
					if(StringUtils.isNotEmpty(cdnUrl)) {
						url = cdnUrl + url.substring(url.indexOf("upload") - 1);
					}
				}
			} else {
				return new ResultDto("上传失败:" + file.getOriginalFilename(), ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			System.out.println("url:"+url);
//			Map<String, String> map = OSSFileUtil.ossFileUpload_sysc(file, directoryName, false, fileName);
			return new ResultDto(url, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("传输过程出现异常，请重新上传！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	/**
	 * <b> 可回溯文件列表 </b>
	 * @author ZXF
	 * @create 2024/03/04 0004 16:35
	 * @version
	 * @注意事项 </b>
	 */

	@RequestMapping("/file/reader/playerList/{sign}")
	public ModelAndView playerList(HttpServletRequest request, @PathVariable String sign) {
		String keyword = request.getParameter("keyword");
		if(!GlobalConstants.getConfig("readerKey").equals(sign)||StringUtils.isEmpty(keyword)){
			throw new RuntimeException("非法请求");
		}
		ModelAndView view = new ModelAndView("/coninsweb/synopsis/playerTable");
		view.addObject("playerList",insInsuranceSlipService.findOperationRecordByExNo(keyword));
		return view;
	}

	/**
	 * <b> 可回溯文件回放业务入库 </b>
	 * @author ZXF
	 * @create 2024/03/04 0004 16:35
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/file/reader/{sign}")
	public ModelAndView reader(HttpServletRequest request, @PathVariable String sign) {
		if(!GlobalConstants.getConfig("readerKey").equals(sign)){
			throw new RuntimeException("非法请求");
		}
		ModelAndView view = new ModelAndView("/coninsweb/synopsis/rrwebPlayer");
		view.addObject("sign",sign);
		return view;
	}

	/**
	 * <b> 可回溯文件对取成文本 </b>
	 * @author ZXF
	 * @create 2024/03/04 0004 16:36
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/file/reader/txt/{sign}")
	@ResponseBody
	public String readerTxt(HttpServletRequest request, @PathVariable String sign) {
		String path = request.getParameter("path");
		if(!GlobalConstants.getConfig("readerKey").equals(sign)||StringUtils.isEmpty(path)){
			throw new RuntimeException("非法请求");
		}
		return HttpUtil.get(path);
	}

	@RequestMapping("/file/ajaxFormCanvasLoad")
	@ResponseBody
	public void ajaxFormCanvasLoad(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(file != null){
			String sigId = request.getParameter("sigId");
			String orderId = request.getParameter("orderId");
			String oType = request.getParameter("oType");
//			String fileName = request.getParameter("fileName");
			String sign = request.getParameter("sign");
			String directoryName = request.getParameter("directoryName");
			String fileType = Files.getFileExtension(file.getOriginalFilename());
			//先转base64
			String base64 = FileUtils.convertToBase64(file);
			//只做记录所以异步
			new Thread(()->{
				saveVideoTxt(sigId, orderId, oType, sign, directoryName, fileType, base64);
			}).start();
		}
	}

	/**
	 * <b> 记录入库业务设置synchronized，保证入库时间顺序 </b>
	 * @author ZXF
	 * @create 2024/05/24 0024 17:42
	 * @version
	 * @注意事项 </b>
	 */
	private synchronized void saveVideoTxt(String sigId,String orderId,String oType,String sign,String directoryName,String fileType,String base64){
		String url = OSSFileUtil.huaweiOBSFileUpload_base64(base64,fileType,directoryName,sign);
		if (StringUtils.isNotEmpty(url)) {
			/*** 如果为生产环境，需要更换域名 ***/
			if(!GlobalResources.IS_TEST_ENVI){//生产
				String cdnUrl = GlobalResources.HW_CDN_URL;
				if(StringUtils.isNotEmpty(cdnUrl)) {
					url = cdnUrl + url.substring(url.indexOf("upload") - 1);
				}
			}
			insInsuranceSlipService.saveInsOperationRecord(orderId,sigId,oType,url);
			//如果页面传2个都有值就是要更新订单id（这是设计这套逻辑时前后端约定的规则）
			if(StringUtils.isNotEmpty(sigId)&&StringUtils.isNotEmpty(orderId)){
				insInsuranceSlipService.updateOrderIdBySigId(orderId,sigId);
			}
		}
		System.out.println("url:"+url);
	}
	@RequestMapping("/file/ajaxFormHtmlLoad")
	@ResponseBody
	public void ajaxFormHtmlLoad(/*@RequestParam(value = "file", required = false) MultipartFile file, */HttpServletRequest request, HttpServletResponse response) throws IOException {
//		if(file != null){
			String file = request.getParameter("file");
			String sigId = request.getParameter("sigId");
			String orderId = request.getParameter("orderId");
			String oType = request.getParameter("oType");
			String fileName = request.getParameter("fileName");
			String directoryName = request.getParameter("directoryName");
			String width = request.getParameter("width");
			String height = request.getParameter("height");
			String length = request.getParameter("length");
		MultipartFileImpl multipartFile = null;
		try {
			String b64 = BASE64Util.decryptBASE64(file);
			String html = URLDecoder.decode(b64, "utf-8");
			System.out.println("****html:"+html);
			multipartFile = new MultipartFileImpl(fileName,html.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String url = OSSFileUtil.huaweiOBSFileUpload(multipartFile,directoryName);
		if (StringUtils.isNotEmpty(url)) {
			/*** 如果为生产环境，需要更换域名 ***/
			if(!GlobalResources.IS_TEST_ENVI){//生产
				String cdnUrl = GlobalResources.HW_CDN_URL;
				if(StringUtils.isNotEmpty(cdnUrl)) {
					url = cdnUrl + url.substring(url.indexOf("upload") - 1);
				}
			}
			System.out.println("orderId:"+orderId+",sigId:"+sigId+",oType:"+oType+",width:"+width+",height:"+height+",length:"+length+",url:"+url);
		}
		System.out.println("url:"+url);
	}

	/**
	 * <b> 上传图片或文件处理(平安附件专用，同步上传平安使key生效) app个人报案场景用</b>
	 * @author ZXF
	 * @create 2020/06/16 0016 10:32
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/file/uploadFileForPA")
	@ResponseBody
	public ResultDto uploadFileForPA(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
		if(file != null){
			// TODO key用于平安标识
			String fileId = UUID.randomUUID().toString();
			String folder = "/report/";
			String url = FileHelp.reportUpload(file,GlobalResources.COM_IMG_RE,folder,GlobalResources.DONOW_PATH);
			System.out.println("url:"+url);
			if(StringUtils.isEmpty(url)){
				return new ResultDto("文件上传失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			if(gZZRX_PACRequestService.isUploadPA(file.getInputStream(),fileId,url.split(folder)[1])){
				System.out.println("fileId:"+fileId);
				Map<String,String> map = Maps.newHashMap();
				map.put("fileId",fileId);
				map.put("url",url);
				return new ResultDto(JSON.toJSONString(map), ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			return new ResultDto("同步理赔附件token获取失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("传输过程出现异常，请重新上传！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	@RequestMapping("/file/uploadFileForOther")
	@ResponseBody
	public ResultDto uploadFileForOther(@RequestParam(value = "file", required = false) MultipartFile file) {
		if(file != null){
			String fileId = UUID.randomUUID().toString();
			String folder = "/report/";
			String url = FileHelp.reportUpload(file,GlobalResources.COM_IMG_RE,folder,GlobalResources.DONOW_PATH);
			System.out.println("url:"+url);
			if(StringUtils.isEmpty(url)){
				return new ResultDto("文件上传失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			Map<String,String> map = Maps.newHashMap();
			map.put("fileId",fileId);
			map.put("url",url);
			return new ResultDto(JSON.toJSONString(map), ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("传输过程出现异常，请重新上传！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	/**
	 * <b> 文件流推送平安业务方法 </b>
	 * @author ZXF
	 * @create 2019/11/18 0018 16:15
	 * @version
	 * @注意事项 </b>
	 */
	private boolean uploadPA(InputStream inputStream
			, Map<String, String> iobsParamMap
			, String fileId
			, String originalName) throws IOException {
		// 上传文件流的大小
		long length = inputStream.available();
		// 上传的关键方法
		Response response = new IobsService().uploadStream(iobsParamMap.get("bucket"), fileId, inputStream, originalName, iobsParamMap.get("token"), length);
		System.out.println("返回结果:" + JSON.toJSONString(response));
		if (response.isOK()) {
			return true;
		} else {
			System.out.println("error code：" + response.error());
			return false;
		}
	}
	
	/**
	 * fileinput上传图片删除
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/file/ajaxFormDataDelete")
	public void ajaxFormDataDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//oss存储图片url路径：http://bcxin-conins-extranet-test.oss-cn-shanghai.aliyuncs.com/policy/201609081921491352.pdf
		String url = request.getParameter("url");
		/*if(StringUtils.isNotEmpty(url)&&!ConstProp.DIGIT_ZERO.equals(url)){
			//oss的key:policy/201609081921491352.pdf
			String key = url.split(".com/")[1];
			new Thread(()->{ //异步删除
				OSSFileUtil.ossFileDelete(key);
			}).start();
		}*/
	}


	/************************当前采用上传****************************/

	@RequestMapping(value = "/getResource")
	public void getResource(String path, HttpServletResponse response) {
		String upload_path = GlobalResources.COM_IMG_RE;
		downloadFile(path, response, upload_path);
	}



	private void downloadFile(String path, HttpServletResponse response, String upload_path) {
		File file = new File(upload_path + path);
		try(ServletOutputStream out = response.getOutputStream();
			InputStream is = new FileInputStream(file);) {

			response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
			int read = 0;
			byte[] buffer = new byte[8192];
			while ((read = is.read(buffer)) != -1) {
				System.out.println(read);
				out.write(buffer, 0, read);
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
//		String fileContent = readFile("E:\\data\\upload\\tbpd\\电子批单下载地址.txt");
//		String[] arr = fileContent.split(",");
//		for (String s : arr){
//			FileHelp.downloadFileAndSave(s, "E:\\data\\upload\\tbpd\\", UUID.randomUUID().toString(), ".pdf");
//		}
	}

	public static String readFile(String filename) {
		StringBuilder content = new StringBuilder();
		try (FileReader fileReader = new FileReader(filename);
			 BufferedReader bufferedReader = new BufferedReader(fileReader)) {
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				content.append(line).append(System.lineSeparator());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content.toString();
	}
}
