package com.artfess.file.service.impl;


import com.artfess.base.attachment.AttachmentService;
import com.artfess.base.attachment.AttachmentServiceFactory;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.file.attachmentService.FtpAttachmentServiceImpl;
import com.artfess.file.model.DefaultFile;
import com.artfess.file.service.FilePreview;
import com.artfess.file.util.AppFileUtil;
import com.artfess.file.util.FileUtils;
import com.artfess.file.util.LibreOfficeToPdf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

/**
 * Created by kl on 2018/1/17.
 * Content :处理office文件
 */
@SuppressWarnings(value = "unchecked")
@Service
@Slf4j
public class OfficeFilePreviewImpl implements FilePreview {

	@Autowired
	FileUtils fileUtils;

	@Value("${file.file.dir}")
	String fileDir;
	/*@Value("${imageMagick}")
	String imageMagick;*/
	@Resource
	AttachmentServiceFactory attachmentServiceFactory;
//	@Autowired
//	private OfficeToPdf officeToPdf;
	@Resource
	private LibreOfficeToPdf libreOfficeToPdf;


	@Override
	public String filePreviewHandle(DefaultFile fileMode,@SuppressWarnings("rawtypes") Map map) {
		String fileName=fileMode.getId()+"."+fileMode.getExtensionName();
		String suffix=fileMode.getExtensionName();
		// boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx");
		String filePath = fileDir+fileMode.getId()+"."+fileMode.getExtensionName();
		String checkfilePath=filePath.substring(0,filePath.lastIndexOf(".")+1)+("pdf");
		//判断该文件是否已经转过PDF
		boolean falg=checkFile(checkfilePath,map);
		if(!falg){
			if (!new File(filePath).exists()) {
				try {
					File dirFile = new File(fileDir);
					if (!dirFile.exists()) {
						dirFile.mkdirs();
					}
					String separator = File.separator;
					if(!filePath.contains(File.separator)){
						separator = File.separator.equals("/")?"\\\\":"/";
					}
					String saveType = null;
					if (!StringUtil.isEmpty(fileMode.getStoreType())) {
						fileMode.setProp6(fileMode.getStoreType());
						saveType = fileMode.getStoreType();
					}
					AppFileUtil.createPath(filePath.substring(0,filePath.lastIndexOf(separator)), fileName);
					if(StringUtil.isEmpty(saveType)) {
						saveType = AppFileUtil.getSaveType(fileMode.getProp6());
						if (StringUtil.isEmpty(saveType)) {
							saveType = AppFileUtil.getFileSaveTypeByConfig(BeanUtils.isNotEmpty(fileMode) ? fileMode.getBizCode() : "");
						}
					}
					AttachmentService attachmentService=attachmentServiceFactory.getCurrentServices(saveType);
					//特殊场景，附件上传方式是ftp，word套打生成的文件是磁盘存储，下载套打文件时特殊处理
					if(attachmentService instanceof FtpAttachmentServiceImpl && DefaultFile.SAVE_TYPE_FOLDER.equals(fileMode.getStoreType())){
						AttachmentServiceFactory attachmentHandlerFactory = AppUtil.getBean(AttachmentServiceFactory.class);
						attachmentService = attachmentHandlerFactory.getCurrentServices(DefaultFile.SAVE_TYPE_FOLDER);
					}
					attachmentService.download(fileMode, new FileOutputStream(filePath),BeanUtils.isNotEmpty(fileMode)?fileMode.getProp6():"");
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
			String outFilePath = filePath.substring(0,filePath.lastIndexOf(".")+1)+("pdf");
			if (StringUtils.hasText(outFilePath)) {
				long systemTime = System.currentTimeMillis();
				log.info("------------------------openOffice 文件:{} 转换开始------------------------",fileMode.getFileName());
				libreOfficeToPdf.libreOfficeToPDF(filePath, outFilePath, false);
				long overTime = System.currentTimeMillis() - systemTime;
                log.info("------------------------openOffice 文件转换结束，耗时:{}------------------------", overTime);
				File f = new File(filePath);
				if (f.exists()) {
					map.put("fileSize",f.length());
					f.delete();
				}
			}
		}
		map.put("pdfUrl","/file/onlinePreviewController/v1/getFileByPathAndId_"+fileMode.getId()+"_"+("pdf"));
		return "pdf";
	}

	private boolean checkFile(String path,Map map){
		File file=new File(path);
		if (file.exists()) {
			map.put("fileSize",file.length());
		}
		return file.exists();
	}

}
