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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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 org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;


/**
 * 文档转换工具
 */
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);
            }
            os.close();
            fis.close();
        } 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 doc = new File(srcFile);
   		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 ) {
   		try {			
   			File imagePath = new File(imagePathStr);
   			if (!imagePath.exists()) {
   				imagePath.mkdirs();
   			}		
   		    URL url = new URL(srcFile);
	        //链接url
	        URLConnection uc = url.openConnection();
	        //获取输入流
	        InputStream in = uc.getInputStream();
   			
	        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();
   			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();
   		}

   	}

//   	/**
//   	 * .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();
//   			}
//   
//   		}
//   
//   	}
  }
