package com.bcxin.web.controller;

import com.bcxin.config.WPSConfig;
import com.bcxin.service.DownloadService;
import com.bcxin.service.IWpsFilePreview;
import com.bcxin.utils.BASE64Util;
import com.bcxin.vo.wps.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author jianjun.wang
 * @version V1.0
 * @className WpsOnlinePreviewController
 * @packageName com.bcxin.web.controller
 * @description wps文件预览与编辑服务控制器
 * @data 2019-09-02 13:54
 **/
@Slf4j
@RestController
@RequestMapping("/wps")
public class WpsOnlinePreviewController {

    @Resource(name = "wpsFilePreviewImpl")
    private IWpsFilePreview wpsFilePreview;

    @Resource
    private DownloadService downloadService;

    /**
     * 文件预览接口控制器
     *
     * @param filePath 文件路径url base64
     * @param fileId   文件唯一id，用于与wps交互。sysName+fileId不能重复
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/preview")
    public ResultVo preview(@RequestParam("filePath") String filePath, @RequestParam("readonly") String readonly, @RequestParam(value = "envi", required = false) String envi) throws Exception {
        return wpsFilePreview.previewHandle(BASE64Util.decryptBASE64(filePath), readonly,envi);
    }

//    /**
//     * 文件编辑接口控制器--暂时不用
//     *
//     * @param filePath 文件路径url
//     * @param fileId   文件唯一id，用于与wps交互
//     * @return
//     * @throws Exception
//     */
//    @Deprecated
//    @GetMapping(value = "/edit")
//    public ResultVo edit(@RequestParam("filePath") String filePath, @RequestParam("fileId") String fileId, String version) throws Exception {
//        return wpsFilePreview.editService(filePath, fileId, version);
//    }

    /**
     * 文件下载控制器
     *
     * @param key  文件名
     * @param req
     * @param resp
     * @throws IOException
     * @throws IOException
     */
    @RequestMapping(value = "/download/{key}", method = RequestMethod.GET)
    public void download(
            @PathVariable(value = "key") String key,
//            @RequestParam(value = "name", required = false) String name,
            HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName = key;
        if (fileName == null || fileName.trim().length() == 0) {
            resp.reset();
            resp.setContentType("text/plain;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("error:can't get the file name! 不能获取文件名");
            writer.flush();
            return;
        }
        fileName = WPSConfig.WPS_FILE_TEMP_FOLDER + fileName;

        downloadService.downloadService(fileName, req, resp);

    }
}



