package com.kingdee.shr.customer.gtiit.handler;

import com.aspose.pdf.DocSaveOptions;
import com.aspose.pdf.Document;
import com.aspose.pdf.SaveFormat;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.base.attachment.AttachmentFactory;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.base.attachment.IAttachment;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.empCertification.web.handler.HRcertificationbillListHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HRcertificationbillListHandlerEx extends HRcertificationbillListHandler{

	private static Logger logger =
	        Logger.getLogger("com.kingdee.shr.customer.gtiit.handler.HRcertificationbillListHandlerEx");
	//更新
	public void convertPdfToWordAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
		logger.error("进入附件转换方法");
		String attachId = request.getParameter("attachId");
		Map<String,Object> map = new HashMap<>();
		String fileName = request.getParameter("fileName");
		logger.error("附件下载路径："+attachId);
		logger.error("附件名称："+fileName);
		Document doc= null;
		ByteArrayInputStream fileInputStream= null;
		ByteArrayOutputStream byteOutputStream= null;
		try {
			Context ctx = SHRContext.getInstance().getContext();
			IAttachment attachment = AttachmentFactory.getLocalInstance(ctx);
			AttachmentInfo info = attachment.getAttachmentInfo(new ObjectUuidPK(attachId));

			 fileInputStream = new ByteArrayInputStream(info.getFile());
			// 创建输出流
			 byteOutputStream = new ByteArrayOutputStream();
			//doc是将要被转化的word文档
			 doc = new Document(fileInputStream);
			//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
			// 创建 Word 保存选项
			DocSaveOptions options = new DocSaveOptions();
			// 设置输出格式为 DOCX
			options.setFormat(DocSaveOptions.DocFormat.DocX);
			doc.save(byteOutputStream, options);
			info.setSimpleName("docx");
			info.setType("Microsoft Word Doc");
			if(StringUtils.isNotBlank(fileName)) {
				String name = fileName.replace(".docx","");
				info.setName(name);
			}
			info.setFile(byteOutputStream.toByteArray());
			attachment.save(info);
			map.put("code","ok");
			map.put("msg","ok");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("附件类型转换失败："+e.getMessage());
			map.put("code","err");
			map.put("msg",e.getMessage());
		}finally {
            if(doc != null)doc.close();
            try {
				if(fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
				if(byteOutputStream != null) byteOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
		JSONUtils.SUCCESS(map);
	}

//	public void convertPdfToWordAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
//		logger.error("进入附件转换方法");
//		String downloadUrl = request.getParameter("downloadUrl");
//		downloadUrl = downloadUrl.replace(" ", "+");
//		String fileName = request.getParameter("fileName");
//		logger.error("附件下载路径："+downloadUrl);
//		logger.error("附件名称："+fileName);
//		File attachFile = null;
//		try {
//			// 创建 URL 对象
//            URL url = new URL(downloadUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            // 设置超时时间为100秒
//            conn.setConnectTimeout(100 * 1000);
//            // 得到输入流
//            InputStream inputStream = conn.getInputStream();
//            // 创建文件输出流
//            attachFile = File.createTempFile("temp", ".pdf");
//            // 将输入流中的数据写入临时文件
//            FileOutputStream outputStream = new FileOutputStream(attachFile);
//            // 读取输入流中的数据并写入输出流
//            byte[] buffer = new byte[4096];
//            int bytesRead;
//            while ((bytesRead = inputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, bytesRead);
//            }
//            // 关闭流
//            inputStream.close();
//            outputStream.close();
//
//			FileInputStream fileInputStream = new FileInputStream(attachFile);
//            // 创建输出流
//            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
//            //doc是将要被转化的word文档
//
//            Document doc = new Document(fileInputStream);
//            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
//            doc.save(byteOutputStream, SaveFormat.DocX);
//            // 将 ByteArrayOutputStream 转换为 InputStream
//            InputStream input = new ByteArrayInputStream(byteOutputStream.toByteArray());
//
//            try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
////    			//通知浏览器以附件形式下载
//    			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
//    			//文件输出格式
//    			response.setContentType("multipart/form-data;charset=utf-8");
//    			byte[] car = new byte[1024];
//    			int len;
//    			while ((len = input.read(car)) != -1) {
//    				out.write(car, 0, len);
//    			}
//    		} catch (IOException e) {
//    			e.getMessage();
//    		}
//            doc.close();
//            fileInputStream.close();
//            byteOutputStream.close();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error("附件类型转换失败："+e.getMessage());
//        }
//		if(attachFile != null) {
//			attachFile.deleteOnExit();
//			attachFile.delete();
//		}
//	}
	
	/*public void convertPdfToWordAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
		logger.error("进入附件转换方法");
		String downloadUrl = request.getParameter("downloadUrl");
		downloadUrl = downloadUrl.replace(" ", "+");
		String fileName = request.getParameter("fileName"); 
		logger.error("附件下载路径："+downloadUrl);
		logger.error("附件名称："+fileName);
		try {
			URL url = new URL(downloadUrl);
	        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
	        int responseCode = httpConn.getResponseCode();
	        // 检查是否成功连接到文件
	        if (responseCode == HttpURLConnection.HTTP_OK) {
	            InputStream inputStream = url.openStream();
	            
	            File tempFile = File.createTempFile("temp", ".pdf");
	            // 将输入流中的数据写入临时文件
	            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
	            byte[] buffer = new byte[1024];
	            int bytesRead;
	            while ((bytesRead = inputStream.read(buffer)) != -1) {
	            	fileOutputStream.write(buffer, 0, bytesRead);
	            }
	            fileOutputStream.close();
	            inputStream.close();
	            InputStream fileInputStream = new FileInputStream(tempFile.getPath());
	            tempFile.deleteOnExit();
	            tempFile.delete();
	            // 创建输出流
	            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	            //doc是将要被转化的word文档
	            Document doc = new Document(fileInputStream);
	            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
	            DocSaveOptions saveOptions = new DocSaveOptions();
	            doc.save(outputStream, saveOptions);
	            // 将 ByteArrayOutputStream 转换为 InputStream
	            InputStream input = new ByteArrayInputStream(outputStream.toByteArray());
	            
	            doc.close();
	            inputStream.close();
	            
	            try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
//	    			//通知浏览器以附件形式下载
	    			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
	    			//文件输出格式
	    			response.setContentType("multipart/form-data;charset=utf-8");
	    			byte[] car = new byte[1024];
	    			int len;
	    			while ((len = input.read(car)) != -1) {
	    				out.write(car, 0, len);
	    			}
	    		} catch (IOException e) {
	    			e.getMessage();
	    		}
	            input.close();
	            outputStream.close();
	        }else {
	        	logger.error("附件路径转换异常");
	        }
            
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("附件类型转换失败："+e.getMessage());
        }
		
	}*/
	
}
