package com.yeejoin.amos.boot.biz.common.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;


/**
 * 文档转换工具
 */
public class WordConverterUtils {




    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(file);
			 OutputStream os = item.getOutputStream();) {
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }





   	/**
   	 * word文档转html文档
   	 *
   	 * @param srcFile    原文档
   	 * @param targetFile 目标文档
   	 * @param fileService   图片上传接口
   	 */
   	public static void wordToHtml(String srcFile, String targetFile, String imagePathStr,String readUrl,FileService fileService,String product,String appKey,String token ) {
   		File html = new File(targetFile);
   		if ( html.exists()) {
   			return;
   		} else {
   			if (srcFile.endsWith(".doc")) {
   				docToHtml(  imagePathStr,readUrl,srcFile, html, fileService, product, appKey, token);
   			}
//   			else if (srcFile.endsWith(".docx")) {
//   				docxToHtml(  imagePathStr,readUrl,srcFile, html, fileService, product, appKey, token);
//   			}
   		}
   	}

   	/**
   	 * .doc文档转换成html
   	 *
   	 * @param srcFile    原文档
   	 * @param targetFile 目标文档
   	 * @param fileService   图片上传接口
   	 */
   	private static void docToHtml( String imagePathStr,String readUrl,String srcFile, File targetFile, FileService fileService,String product,String appKey,String token ) {
		InputStream in = null;
   		try {
   			File imagePath = new File(imagePathStr);
   			if (!imagePath.exists()) {
   				imagePath.mkdirs();
   			}
   		    URL url = new URL(srcFile);
	        //链接url
	        URLConnection uc = url.openConnection();
	        //获取输入流
	        in = uc.getInputStream();
   			if (null != in) {
				HWPFDocument wordDocument = new HWPFDocument(in);

				org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);

				wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
					try {

						FileOutputStream out = new FileOutputStream(imagePathStr + name);
						out.write(content);
						String urlString = fileService.uploadFile(fileToMultipartFile(new File(imagePathStr + name)), product, appKey, token);
						//上传平台
						return readUrl + urlString;
					} catch (Exception e) {
						e.printStackTrace();
						return "";
					}
				});
				wordToHtmlConverter.processDocument(wordDocument);
				org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
				DOMSource domSource = new DOMSource(htmlDocument);
				StreamResult streamResult = new StreamResult(targetFile);
				TransformerFactory tf = TransformerFactory.newInstance();
				tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
				tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
				Transformer serializer = tf.newTransformer();
				serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
				serializer.setOutputProperty(OutputKeys.INDENT, "yes");
				serializer.setOutputProperty(OutputKeys.METHOD, "html");
				serializer.transform(domSource, streamResult);
			}
   		} catch (Exception e) {
   			e.printStackTrace();
   		} finally {
   			if (null != in) {
   				try {
   					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

   	}

//   	/**
//   	 * .docx文档转换成html
//   	 *
//   	 * @param srcFile    原文档
//   	 * @param targetFile 目标文档
//   	 * @param fileService   图片上传接口
//   	 */
//   	private static void docxToHtml( String imagePathStr,String readUrl,String srcFile, File targetFile, FileService fileService,String product,String appKey,String token) {
//
//   		File imagePath = new File(imagePathStr);
//   		if (!imagePath.exists()) {
//   			imagePath.mkdirs();
//   		}
//   	 OutputStream outputStreamWriter=null;
//   		try {
//
//   			URL url = new URL(srcFile);
//	        //链接url
//	        URLConnection uc = url.openConnection();
//	        //获取输入流
//	        InputStream in = uc.getInputStream();
//   			XWPFDocument document = new XWPFDocument(in);
//   		   //存储图片
//   			PdfOptions  options=PdfOptions.create();
//
//             outputStreamWriter=new FileOutputStream(targetFile);
//   		     PdfConverter.getInstance().convert(document,outputStreamWriter,options);
//
//
//   		} catch (Exception e) {
//   			e.printStackTrace();
//   		} finally {
//   			try {
//   				if (outputStreamWriter != null) {
//   					outputStreamWriter.close();
//   				}
//   			} catch (Exception e2) {
//   				e2.printStackTrace();
//   			}
//
//   		}
//
//   	}
  }
