package com.bcxin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import com.bcxin.service.IFilePreview;
import com.bcxin.utils.BcxinFileUtil;
import com.bcxin.utils.ConfigUtil;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

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

    @Override
    public String filePreviewHandle(String url, Model model) {
        System.out.println("============> pdfUrl:"+url);
        /* 本地链接，需重新组装 */
        if (url.contains(":8012")) {
            String newUrl = url.substring(0,url.indexOf("8012")+5) + "pdf/getResource/" + url.substring(url.indexOf("8012")+5,url.length());
            model.addAttribute("pdfUrl", newUrl);
        }
        /* 处理浙江url */
        else if (url.contains("41.188.66.95")) {
            String newUrl = "http://41.188.66.95/pdf/getResource/"+url.substring(url.indexOf("41.188.66.95")+13,url.length());
            System.out.println("==========> filePreviewHandle,newUrl:"+newUrl);
            model.addAttribute("pdfUrl", newUrl);
        } else {
            /* 需要先下载下来重新组装链接，否则会截断url */
            String randomName = UUID.randomUUID().toString();
            String fileName = randomName + ".pdf";
            String materialPath = ConfigUtil.getValue("material_path");
            FileUtil.mkdir(materialPath);
            File localFile = new File(materialPath + fileName);
            if(!url.contains("/getResource?path=")){
                url = url.replace(ConfigUtil.getValue("web_url"),ConfigUtil.getValue("web_url")+"/getResource?path=");
                if(url.contains("/getResource?path=")){
                    try {
                        url = url.split("path=")[0] + "path=" + URLEncoder.encode(url.split("path=")[1],"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            /*下载源文件*/
            BcxinFileUtil.download(url,localFile);
            model.addAttribute("pdfUrl", "/getPdfFile/" + randomName);
        }
        return "pdf";
    }

    public static void main(String[] args) {
        String url = "http://41.188.66.95/1563951999350.rar_%E6%9D%8E.pdf";
        Console.log();

    }
}
