package com.yizhi.application.certificate.util;



import com.yizhi.application.certificate.constant.LogError;
import com.yizhi.application.certificate.constant.UtilConstants;
import com.yizhi.application.course.util.OssUpload;
import com.yizhi.core.application.exception.FileReadException;
import com.yizhi.util.application.zip.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class CertificateZipAnalysis {

    @Value("${ACTIVE}")
    public String active;

    private static final Logger LOG = LoggerFactory.getLogger(CertificateZipAnalysis.class);





    public String parseTemplate(File fileInfo) {

    	//fileInfo   F:\home\file\certificate\完整竖版证书包1552529700331.zip
        try {
            // 证书模板 文件目录(解压后都放在这里面)
            File templateBaseDir = new File(UtilConstants.CERTIFICATE_SAVE_PATH);

            // 若 模板 文件夹不存在
            if (!templateBaseDir.exists()) {
                if (!templateBaseDir.mkdir()) {
                    LOG.error("证书文件夹新建失败！");
                    return LogError.CERTIFICATE_ANALYSIS_ERROR;
                }
            }
            // 没有后缀的文件名
            //  完整竖版证书包1552529700331
            String fileNameWithoutSuffix = fileInfo.getName().substring(0, fileInfo.getName().lastIndexOf("."));
            // 当前 模板 课件解压后的根目录
            //F:\home\file\certificate\完整竖版证书包1552529700331
            File templateDir = new File(templateBaseDir.getAbsolutePath() + File.separator + fileNameWithoutSuffix);
            ZipUtil.unZip(fileInfo.getAbsolutePath(), templateDir.getAbsolutePath());
            File tem=new File(templateDir.getAbsolutePath());
            //去找index文件
            //File indexFile = new File(templateDir.getAbsolutePath() + "/index.html");
            
            String indexFilePath=pointFile(tem);
            //index文件的全路径
            File indexPath=new File(indexFilePath);
           String fileIndexParentPath=indexPath.getParent();
           templateDir=new File(fileIndexParentPath);
            int height = 0;
            int width = 0;
            File imgFile = new File(templateDir.getAbsolutePath() + File.separator  + "background.jpg");
            if (imgFile.exists()) {
                try {
                    BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imgFile));
                    height = bufferedImage.getHeight();
                    width = bufferedImage.getWidth();
                } catch (IOException e) {
                    LOG.info("获取图片信息异常{}",e);
                }
            }
            HtmltopdfAndImage.convert(templateDir.getAbsolutePath() + "/index.html",
                    templateDir.getAbsolutePath() + "/" + fileNameWithoutSuffix + ".pdf",
                    1,height,width);


            PdfToPng.pdfToPng(templateDir.getAbsolutePath() + "/" + fileNameWithoutSuffix + ".pdf",templateDir.getAbsolutePath(),500,1,fileNameWithoutSuffix);

            String result = OssUpload.upload(templateDir.getAbsolutePath() + "/" + fileNameWithoutSuffix + ".png", fileNameWithoutSuffix + ".png",active);

            return result;
        } catch (Exception e) {
            LOG.error("文件解析失败", e);
            return LogError.CERTIFICATE_ANALYSIS_ERROR;
        }
    }

    /**
     * @param urlStr
     * @param savePath
     * @param fileName
     * @return fileInfo 的 properties 中含有一个 absolutePath
     */
    public static File read(String urlStr, String savePath, String fileName) {

        File fileInfo = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();

            byte[] getData = bos.toByteArray();
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            fileInfo = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(fileInfo);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            LOG.error("文件拉取失败", e);
            throw new FileReadException();
        }
        return fileInfo;
    }



    public String parse(String urlStr, String savePath, String fileName) {
        try {
        	//文件下载下来 保存的全路径
            File fileInfo = read(urlStr, savePath, fileName);
            String result = parseTemplate(fileInfo);
            return result;
        } catch (Exception e) {
            return LogError.CERTIFICATE_ANALYSIS_ERROR;
        }

    }
    
    
    private  String pointFile(File file) {
    	String name=null;
		if(file.exists()){
		if (file.isFile()) {
			name=file.getAbsolutePath();
			if(name.indexOf("index.html")>0&&name.indexOf("_index.html")==-1) {
				return name;
			}
		} else {
		File[] list = file.listFiles();
		if (list.length == 0) {
		    System.out.println(file.getAbsolutePath() + " is null");
		} else {
			for (int i = 0; i < list.length; i++) {
				name=pointFile(list[i]);
				if(name!=null) {
					return name;
				}
			}
		}
		}
		}else{
		System.out.println("The directory is not exist!");
		}
		return null;
		}





}
