package com.bcxin.web.controller;

import com.bcxin.utils.ConfigUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 *  页面跳转
 * @author yudian-it
 * @date 2017/12/27
 */
@Controller
public class IndexController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String go2Index(){
        return "index";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String root() {
        return "redirect:/index";
    }

    @RequestMapping(value = "/getResource",method = RequestMethod.GET)
    public void getResource(HttpServletRequest request ,HttpServletResponse response) {
        String path = request.getParameter("path");
        String uploadPath = ConfigUtil.getValue("material_path");
        System.out.println("==========> getResource,path:"+path);
        downloadFile(path, response, uploadPath);
    }

    @RequestMapping(value = "/pdf/getResource/{fileName}",method = RequestMethod.GET)
    public void getResource(@PathVariable String fileName ,HttpServletResponse response) {
        String uploadPath = ConfigUtil.getValue("material_path");
        if(!fileName.endsWith(".pdf")){
            fileName = fileName + ".pdf";
        }
        downloadFile(fileName, response, uploadPath);
    }

    @RequestMapping(value = "/getPdfFile/{fileOid}")
    public void getPdfFile(@PathVariable String fileOid, HttpServletResponse response) {
        String uploadPath = ConfigUtil.getValue("material_path");
        if (fileOid.contains("pdf")) {
            downloadFile("/" + fileOid , response, uploadPath);
        } else {
            downloadFile("/" + fileOid + ".pdf", response, uploadPath);
        }

    }

    private void downloadFile(String path, HttpServletResponse response, String uploadPath) {
        try {
            if (path.contains("..")) {
                return;
            }
            File file = new File(uploadPath + path);
            String fileName = file.getName();
            ServletOutputStream out = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            InputStream is = new FileInputStream(file);
            int read = 0;
            byte[] buffer = new byte[8192];
            while ((read = is.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            is.close();
            out.flush();
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
