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.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;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;


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


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

    public static MultipartFile fileToMultipartFileZip(File file) throws IOException {
        FileItem fileItem = createFileItemZip(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;
    }

	private static boolean isZipFile(File file) {
		try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
			byte[] signature = new byte[4];
			int length = is.read(signature);
			return length == 4 && (signature[0] == 0x50 && signature[1] == 0x4B && signature[2] == 0x03 && signature[3] == 0x04);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static FileItem createFileItemZip(File file) throws IOException {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		String mimeType = getMimeType(file);

		// 创建 FileItem
		FileItem item = factory.createItem("textField", mimeType, true, file.getName());

		try (FileInputStream fis = new FileInputStream(file);
			 OutputStream os = item.getOutputStream()) {

			if (isZipFile(file)) {
				handleZipFile(fis, os);
			} else {
				copyStream(fis, os);
			}
		}

		return item;
	}

	private static void handleZipFile(InputStream fis, OutputStream os) throws IOException {
		try (ZipInputStream zis = new ZipInputStream(fis)) {
			ZipEntry entry;
			while ((entry = zis.getNextEntry()) != null) {
				if (!entry.isDirectory()) {
					copyStream(zis, os);
				}
				zis.closeEntry();
			}
		}
	}

	private static void copyStream(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead;
		while ((bytesRead = input.read(buffer, 0, BUFFER_SIZE)) != -1) {
			output.write(buffer, 0, bytesRead);
		}
	}

	private static String getMimeType(File file) {
		String fileName = file.getName().toLowerCase();
		if (fileName.endsWith(".zip")) {
			return "application/zip";
		} else {
			// 这里可以根据文件扩展名返回其他 MIME 类型，或者使用更复杂的 MIME 类型检测机制
			return "application/octet-stream";
		}
	}


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