package com.steerinfo.util;


import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.utils.io.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 文件下载
 */
@RestController
@RequestMapping("/${api.version}/download")
@Api(value = "A文件下载Api", tags = "A文件下载Api")
public class DownloadController extends BaseRESTfulController {

    @Value("${web.upload-path}")
    String root;

    @Autowired
    private UploadHelper uploadHelper;
    
    @Autowired
    private ActivitiClient activitiClient;

    @ApiOperation(value = "图片获取", notes = "返回二进制字节流")
    @ApiImplicitParam(name = "path", value = "路径", paramType = "query",required = true,example = "FP/1574996244954.jpg")
    @GetMapping("/image")
    public void getImage(@RequestParam("path") String path, HttpServletResponse response) throws Exception {
        File file = new File(root + File.separator+ Const.AppName +File.separator + path);
        if (FileUtils.isFileExists(file)) {
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            os.write(FileUtils.toByteArray(file));
            os.flush();
            os.close();
        }else{
            write("文件未找到",response);
        }
    }
    @ApiOperation(value = "预览PDF", notes = "返回二进制字节流")
    @ApiImplicitParam(name = "path", value = "路径", paramType = "query",required = true,example = "FP/1574996244954.jpg")
    @GetMapping("/pdf")
    public void getPdf(@RequestParam("path") String path,HttpServletResponse response){
        File file = new File(root + File.separator+ Const.AppName +File.separator + path);
        if (FileUtils.isFileExists(file)) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", String.format("inline;fileName=%s",file.getName()));
            try{
                OutputStream os = response.getOutputStream();
                os.write(FileUtils.toByteArray(file));
                os.flush();
                os.close();
            }catch (Exception ex){
            }
        }else{
            write("文件未找到",response);
        }
    }
    
    @ApiOperation(value = "获取文件夹下文件列表",notes = "返回文件列表")
    @ApiImplicitParam(name = "path", value = "路径", paramType = "query",required = true,example = "FP")
    @GetMapping("/files")
    public RESTfulResult getFiles(@RequestParam("path") String path){
        List<UploadHelper.MyFile> list = uploadHelper.getFiles(path);
        return success(list);
    }

    @ApiOperation(value = "下载文件",notes = "下载服务器中文件")
    @ApiImplicitParam(name = "path", value = "路径", paramType = "query",required = true,example = "FP/1574996244954.jpg")
    @GetMapping("/")
    public void download(@RequestParam("path") String path,HttpServletResponse response) {
        File file = new File(root + File.separator+ Const.AppName +File.separator + path);
        if (FileUtils.isFileExists(file)) {
            // 设置信息给客户端不解析
            String type = new MimetypesFileTypeMap().getContentType(path);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type",type);
            // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setHeader("Content-Disposition", String.format("attachment;filename=%s",file.getName()));
            try{
                // 实现文件下载
                OutputStream os = response.getOutputStream();
                os.write(FileUtils.toByteArray(file));
                os.flush();
                os.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }else{
            write("文件未找到",response);
        }
    }

    public static final String separator = File.separator;

    @ApiOperation(value = "下载本地文件",notes = "下载服务器中文件")
    @ApiImplicitParam(name = "path", value = "路径", paramType = "query",required = true,example = "FP/1574996244954.jpg")
    @GetMapping("/localFile")
    public ResponseEntity<InputStreamResource>  downloadLocal() {
        //文件上级目录
        String filePath = "模板";
        //文件名
        String fileName ="合同录入模板.xlsx";
        //下载展示的文件名
        String newName="";

        String route = "static" + separator + "templates" + separator;
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = route + filePath + separator + fileName;
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            //File file = new File(path);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String(newName.getBytes("gbk"), "iso8859-1") + ".xlsx");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {

        } catch (IOException e) {

        }
        return response;
    }


    private void write(String msg,HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain;charset=utf-8");
        try{
            PrintWriter writer = response.getWriter();
            writer.write(msg);
            writer.flush();
            writer.close();
        }catch (Exception ex){

        }

    }

//    @ApiOperation(value = "测试多文件上传",notes = "postman测试通过")
//    @ApiImplicitParam(name = "files",value = "多个文件",paramType = "formData",allowMultiple=true,required = true,dataType = "file")
//    @PostMapping(value = "/testMultiUpload",headers = "content-type=multipart/form-data")
//    public void testUpload(@RequestParam("files") MultipartFile[] files){
//        try{
//            for(MultipartFile file : files){
//                String savePath = uploadHelper.save(file, UploadHelper.Category.FP,"",true);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//    }

    @ApiOperation(value = "测试单文件上传",notes = "postman测试通过")
    @ApiImplicitParam(name = "file",value = "单个文件",paramType = "formData",required = true,dataType = "file")
    @PostMapping(value = "/testSingleUpload",headers = "content-type=multipart/form-data")
    public RESTfulResult testSingleUpload(@RequestParam("file") MultipartFile file){
        try{
            String savePath = uploadHelper.save(file, UploadHelper.Category.FP,"",true);
            return success(savePath);
        }catch (Exception e){
            e.printStackTrace();
            return failed(null, "操作异常，请确认！");
        }

    }

//    @ApiOperation(value = "测试流程引擎服务",notes = "测试流程引擎服务")
//    @GetMapping(value = "/testActivitiService")
//    public RESTfulResult testActivitiService(){
//        Process process = new Process("YF201912200002","yangm");
//        RESTfulResult result = activitiClient.startProcess("tgwl",  "admin",process);
//        if(result != null && result.isSucceed()){
//            return success();
//        }
//        return failed();
//    }
}
