package com.jiayue.ipfcst.console.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.console.dto.FileLogBean;
import com.jiayue.ipfcst.console.util.CommonUtil;
import com.jiayue.ipfcst.fileupload.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
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.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * SysFileController
 *
 * @author bizy
 * @version 1.0
 * @since 2018/12/5 09:37
 */
@RestController
@RequestMapping("sysFile")
@Slf4j
public class SysFileController {
  /**
   * 获取文件夹下的所有文件
   *
   * @param path 文件夹路径
   * @return map
   */
  @GetMapping(value = "/getFileList")
  public ResponseVO getFileList(String path) {
    List<Map<String, Object>> list = new ArrayList<>();
    List<FileLogBean> wjList = new ArrayList<FileLogBean>();//新建一个文件集合
    try {
      if (!path.isEmpty()) {
        String filepath = path;
        List<File> fileList = CommonUtil.getFileSort(filepath);
        for (int i = 0; i < fileList.size(); i++) {
          FileLogBean fileLogBean = new FileLogBean();
          fileLogBean.setFileName(fileList.get(i).getName());
          fileLogBean.setFilePath(filepath);
          fileLogBean.setFileTime(DateFormatUtils.format(fileList.get(i).lastModified(), "yyyy-MM-dd HH:mm:ss"));
          if (fileList.get(i).isDirectory()) {//判断是否为文件夹
            fileLogBean.setFileType("文件夹");
          }
          if (fileList.get(i).isFile()) {//判断是否为文件
            fileLogBean.setFileType("文件");
          }
          wjList.add(fileLogBean);
        }
      } else {
        FileLogBean fileLogBean = new FileLogBean();
        //下载文件根路径
        String initPath = FileUtil.getDownloadFilePath();
        fileLogBean = new FileLogBean();
        fileLogBean.setFileName("下载文件");
        fileLogBean.setFilePath(initPath);
        fileLogBean.setFileTime(DateFormatUtils.format(new File(initPath).lastModified(), "yyyy-MM-dd HH:mm:ss"));
        fileLogBean.setFileType("文件夹");
        wjList.add(fileLogBean);
        //上报文件根路径
        initPath = FileUtil.getFileUploadPath();
        fileLogBean = new FileLogBean();
        fileLogBean.setFileName("上报文件");
        fileLogBean.setFilePath(initPath);
        fileLogBean.setFileTime(DateFormatUtils.format(new File(initPath).lastModified(), "yyyy-MM-dd HH:mm:ss"));
        fileLogBean.setFileType("文件夹");
        wjList.add(fileLogBean);
        //日志文件根路径
        initPath = FileUtil.getLogsPath();
        fileLogBean = new FileLogBean();
        fileLogBean.setFileName("日志文件");
        fileLogBean.setFilePath(initPath);
        fileLogBean.setFileTime(DateFormatUtils.format(new File(initPath).lastModified(), "yyyy-MM-dd HH:mm:ss"));
        fileLogBean.setFileType("文件夹");
        wjList.add(fileLogBean);
        //系统运维资料
        initPath = FileUtil.getSystemFilePath();
        fileLogBean = new FileLogBean();
        fileLogBean.setFileName("系统运维资料");
        fileLogBean.setFilePath(initPath);
        fileLogBean.setFileTime(DateFormatUtils.format(new File(initPath).lastModified(), "yyyy-MM-dd HH:mm:ss"));
        fileLogBean.setFileType("文件夹");
        wjList.add(fileLogBean);
        //报表下载
        initPath = FileUtil.getreportFormPath();
        fileLogBean = new FileLogBean();
        fileLogBean.setFileName("自定义报表");
        fileLogBean.setFilePath(initPath);
        fileLogBean.setFileTime(DateFormatUtils.format(new File(initPath).lastModified(), "yyyy-MM-dd HH:mm:ss"));
        fileLogBean.setFileType("文件夹");
        wjList.add(fileLogBean);
      }
    } catch (RuntimeException e) {
      log.error("系统错误", e);
      return ResponseVO.fail(list);
    }
    return ResponseVO.success(wjList);
  }

  /**
   * 文件下载
   *
   * @param request  HttpServletRequest
   * @param response HttpServletResponse
   * @param path     路径
   * @param name     文件名
   * @param type     文件类型
   */
  @PostMapping(value = "/downLoadFile")
  public void downLoadFile(HttpServletRequest request,
                           HttpServletResponse response,
                           String path,
                           String name,
                           String type) {
    response.setContentType("text/html;charset=utf-8");
    try {
      request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
      log.error("系统错误：" + e1.getMessage(), e1);
    }

    String downLoadPath = path + File.separator + name;
    if (name.isEmpty()) {//传入name为空，说明是一级目录，路径中已经包涵最后一级目录
      name = path.substring(path.lastIndexOf(File.separator) + 1, path.length());
      downLoadPath = path;
    }
    InputStream ins = null;
    BufferedInputStream bins = null;
    try {
      File df = new File(downLoadPath);
      ins = new FileInputStream(df);
      bins = new BufferedInputStream(ins);
      OutputStream outs = response.getOutputStream();
      BufferedOutputStream bouts = new BufferedOutputStream(outs);
      response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "UTF-8"));
      response.setContentType("application/x-msdownload; charset=utf-8");
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
        bouts.write(buffer, 0, bytesRead);
      }
      bouts.flush();
      bouts.close();
    } catch (Exception e) {
      log.error("系统错误：" + e.getMessage(), e);
    }
    finally {
      if (bins != null){
        try {
          bins.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (ins != null){
        try {
          ins.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 文件删除
   *
   * @param path 路径
   * @param name 文件名
   * @return map
   */
  @PostMapping(value = "/deleteFile")
  public ResponseVO deleteFile(String path, String name) {
    List<Map<String, Object>> list = new ArrayList<>();
    String[] names = name.split(",");
    try {
      if (names.length > 0) {
        for (String n : names) {
          String downLoadPath = path + File.separator + n;
          File df = new File(downLoadPath);
          if (df.renameTo(new File(FileUtil.getDeleteFilePath() + File.separator + n))) //源文件移动至目标文件目录
          {
            log.info("File is moved successful!");//输出移动成功
          } else {
            log.error("File is failed to move !");//输出移动失败
          }
        }
      }
    } catch (RuntimeException e) {
      log.error("系统错误：" + e.getMessage(), e);
    } finally {
      return getFileList(path);
    }
  }

  /**
   * 删除空目录
   *
   * @param dir 将要删除的目录路径
   */
  private static void doDeleteEmptyDir(String dir) {
    boolean success = (new File(dir)).delete();
    if (success) {
      System.out.println("Successfully deleted empty directory: " + dir);
    } else {
      System.out.println("Failed to delete empty directory: " + dir);
    }
  }

  /**
   * 递归删除目录下的所有文件及子目录下所有文件
   *
   * @param dir 将要删除的文件目录
   * @return boolean
   */
  private ResponseVO deleteDir(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      //递归删除目录中的子目录下
      for (int i = 0; i < children.length; i++) {
        ResponseVO vo = deleteDir(new File(dir, children[i]));
        if (vo.getCode() != 1) {
          return ResponseVO.fail(0);
        }
      }
    }
    // 目录此时为空，可以删除
    dir.delete();
    return ResponseVO.success(1);
  }

  /**
   * 导入数据
   *
   * @param file 导入的文件
   * @return 返回状态结果
   */
  @PostMapping("/upload")
  public ResponseVO upload(@RequestParam("path") String path,@RequestParam("file") MultipartFile file) {
    try {
      String filepath = path + File.separator + file.getOriginalFilename();
      file.transferTo(new File(filepath));
      log.info("上传文件成功");
      return ResponseVO.success(1);
    } catch (Exception ex) {
      log.error("上传失败" + ex);
      return ResponseVO.error(ex);
    }
  }

  /**
   * 获取文件内容
   *
   * @param path 路径
   * @return map
   */
  @GetMapping(value = "/getFileContent")
  public ResponseVO getFileContent(String path, String name) {
    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> map = new Hashtable<>();
    File file = null;
    BufferedReader br = null;
    StringBuffer sb = new StringBuffer();
    file = new File(path + File.separator + name);
    try {
      br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
      char[] chs = new char[1024];
      int len = 0;
      while ((len = br.read(chs)) != -1) {
        sb.append(new String(chs, 0, len));
      }
      map.put("fileContent", sb.toString());
    } catch (Exception e) {
      log.error("系统错误", e);
      return ResponseVO.fail(map);
    }
    finally {
      if (br!=null){
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    list.add(map);
    return ResponseVO.success(map);
  }

  /**
   * 下载整个文件夹 whc
   *
   * @param request  HttpServletRequest
   * @param response HttpServletResponse
   * @param path     路径
   * @param name     文件名
   * @param type     文件类型
   */
  @PostMapping(value = "/downLoadFolder")
  public void downLoadFolder(HttpServletRequest request,
                           HttpServletResponse response,
                           String path,
                           String name,
                           String type) {
    response.setContentType("text/html;charset=utf-8");
    try {
      request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
      log.error("系统错误：" + e1.getMessage(), e1);
    }


    try {
      String downLoadPath = path + File.separator+name;
      String zipName = downLoadPath +".zip";
      //先吧文件提前压缩好
      List<File> fileList = new ArrayList<>();
      File[] files = new File(downLoadPath).listFiles();
      for(File file : files){
        fileList.add(file);
      }
      FileOutputStream fos2 = new FileOutputStream(new File(zipName));
      CommonUtil.toZip(fileList, fos2);
      //压缩完文件后直接下载压缩包
      downLoadFile(request,response,path,name+".zip",type);
      File deleteFile = new File(zipName);
      deleteFile.delete();
    } catch (Exception e) {
      log.error("系统错误：" + e.getMessage(), e);
    }
  }


  }
