package com.bcxin.service.impl;

import com.bcxin.model.FileAttribute;
import com.bcxin.model.ReturnResponse;
import com.bcxin.service.IFilePreview;
import com.bcxin.utils.ConfigUtil;
import com.bcxin.utils.DownloadUtils;
import com.bcxin.utils.FileUtils;
import com.bcxin.utils.OfficeToPdf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * Created by kl on 2018/1/17.
 * Content :处理office文件
 */
@Service
public class OfficeIFilePreviewImpl implements IFilePreview {

    @Autowired
    private FileUtils fileUtils;

    @Autowired
    private DownloadUtils downloadUtils;

    @Autowired
    private OfficeToPdf officeToPdf;

    @Override
    public String filePreviewHandle(String url, Model model) {
        FileAttribute fileAttribute=fileUtils.getFileAttribute(url);
        String suffix=fileAttribute.getSuffix();
        String fileName=fileAttribute.getName();
        String decodedUrl=fileAttribute.getDecodedUrl();
        boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx");
        String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf");
        System.out.println("============> Office-pdfUrl:"+url+",pdfName:"+pdfName+",fileName:"+fileName);
        // 判断之前是否已转换过，如果转换过，直接返回，否则执行转换
        if (!fileUtils.listConvertedFiles().containsKey(pdfName)) {
            String filePath = ConfigUtil.getValue("material_path") + fileName;
            if (!new File(filePath).exists()) {
                ReturnResponse<String> response = downloadUtils.downLoad(decodedUrl, suffix, null);
                if (0 != response.getCode()) {
                    model.addAttribute("msg", response.getMsg());
                    return "fileNotSupported";
                }
                filePath = response.getContent();
            }
            String outFilePath = ConfigUtil.getValue("material_path") + pdfName;
            if (StringUtils.hasText(outFilePath)) {
                officeToPdf.openOfficeToPDF(filePath, outFilePath);
                File f = new File(filePath);
                if (f.exists()) {
                    f.delete();
                }
                if (isHtml) {
                    // 对转换后的文件进行操作(改变编码方式)
                    fileUtils.doActionConvertedFile(outFilePath);
                }
                // 加入缓存
                fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath));
            }
        }
        model.addAttribute("pdfUrl", "/getPdfFile/" + pdfName);
        return isHtml ? "html" : "pdf";
    }
}
