package com.steerinfo.ems.multipart.controller;

import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.tools.ant.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/${api.version}/multipart")
public class MultipartController extends BaseRESTfulController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MultipartController.class);

    @ApiOperation(value="文件上传", notes="通过文件名和路径上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "path", value = "路径", required = false, dataType = "String")
    })
    @PostMapping("/upload/")
    public RESTfulResult upload(HttpServletRequest request, @ModelAttribute MultipartFile[] file,String path) {
        String fileName = "";
        try {
            // 上传目录地址
            //String uploadDir = ResourceUtils.getURL("classpath:").getPath() + "BOOT-INF/classes/upload/"+path;
            String uploadDir = "/home/upload/" + path;
            // 如果目录不存在，自动创建
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            for (int i = 0;i < file.length;i++){
                // 上传文件名
                fileName = file[i].getOriginalFilename();
                // 服务器端保存的文件对象
                File serverFile = new File(uploadDir, fileName);
                file[i].transferTo(serverFile);
                LOGGER.info("上传成功!上传文件是"+fileName);
            }
            return success(null, "上传成功!此次共上传" + file.length + "个文件,上传路径是" + uploadDir);
        } catch (Exception e) {
            LOGGER.error("上传失败!失败原因："+e.toString());
            return failed(null,"上传失败!失败原因："+e.toString());
        }
    }

    @ApiOperation(value="文件下载", notes="通过文件名和路径下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "path", value = "路径", required = false, dataType = "String")
    })
    @GetMapping("/download/")
    public void downloadFile(@RequestParam String fileName, String path, HttpServletResponse response)throws UnsupportedEncodingException,FileNotFoundException {
        if (fileName != null) {
            //设置文件路径
            //String realPath = ResourceUtils.getURL("classpath:").getPath() + "BOOT-INF/classes/upload/" + path;
            String realPath = "/home/upload/" + path;
            File file = new File(realPath, fileName);
            if (file.exists()) {
                //fileName = new String(fileName.getBytes("utf-8"),"iso8859-1");
                // response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    LOGGER.info("下载成功！下载文件是"+fileName+"，下载路径是"+path);
                } catch (Exception e) {
                    LOGGER.error("下载失败!失败原因："+e.toString());
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            LOGGER.error("下载失败!失败原因："+e.toString());
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            LOGGER.error("下载失败!失败原因："+e.toString());
                        }
                    }
                }
            }
        }
    }

    @ApiOperation(value="获取文件目录", notes="通过路径获取该路径下的全部文件")
    @ApiImplicitParam(paramType = "path", name = "path", value = "路径", required = true, dataType = "String")
    @GetMapping("/list/{path}")
    public RESTfulResult getuploadlist(@PathVariable String path){
        String filepath = "/home/upload/" + path;
        File file = new File(filepath);
        if(!file.exists()){
            return failed(null, "找不到该文件目录！");
        }
        else{
            List<String> list = Arrays.asList(file.list());
            return success(list);
        }
    }
/**
    public RESTfulResult getfile(@RequestParam String path){
        File file = new File(path);
        if(file != null){
            File[] f = file.listFiles();
            if(f != null){
                for(int i=0;i < f.length;i++){
                    getFile(f[i]);
                }
            }else{
                System.out.println(file);
            }
        }
    }
 */
}
