package io.renren.modules.sys.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.renren.common.utils.R;
import net.coobird.thumbnailator.Thumbnails;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/sys/filemanager")
@Configuration
public class FileManagerController {

    @Value("${file.datapath}")
    private String dataPath; // 读取配置文件中的指定目录

    @Value("${file.uploadFolder}")
    private String uploadFolder; // 读取配置文件中的指定目录

    @PostMapping("/uploadimg")
    public R uploadImage(@RequestParam(value = "upload_file") MultipartFile file, HttpServletRequest request)
            throws IOException {
        boolean isThumb = false;
        String thumb = request.getParameter("isthumb");
        if (thumb != null && thumb != "" && thumb.equals("1")) {
            isThumb = true;
        }
        // 根据相对路径转化为真实路径
        // String rootpath =
        // request.getSession().getServletContext().getRealPath(File.separator);//
        // 获得web应用的绝对路径
        // File createFile = new File(rootpath + "../data/upload/");
        String activePath = request.getParameter("activepath");
        // 上传的图片只允许是 png、jpg 或 gif 中的格式
        if (file.getOriginalFilename().contains(".png") || file.getOriginalFilename().contains(".jpg")
            || file.getOriginalFilename().contains(".gif")) {
            Map<String, Object> resultSave = saveFile(file, activePath, false);
            
            if ((Integer) resultSave.get("status") != 0) {
                return R.error((String) resultSave.get("msg"));
            }

            String filename = (String) resultSave.get("filename");

            Map<String, Object> result = new HashMap<String, Object>();

            result.put("picname", filename);
            if (isThumb) {
                int dot = filename.lastIndexOf(".");
                if ((dot >-1) && (dot < (filename.length()))) {
                    String suffix = filename.substring(dot + 1);
                    String thumbFilaname = filename.substring(0, dot)+ "_200." + suffix; 
                    Thumbnails.of(dataPath + filename).width(200).toFile(dataPath + filename);
                    result.put("thumb", thumbFilaname);
                }
            }
            
            return R.ok(result);
        } else {
            return R.error("上传文件失败");
        }
    }

    @PostMapping("/uploadpaper")
    public R uploadPaper(@RequestParam(value = "upload_file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (!file.isEmpty()) {
            String fileOldName = file.getOriginalFilename();
            // 上传的文件只允许是 pdf、doc 或 docx 中的格式
            if (fileOldName.contains(".doc") || fileOldName.contains(".docx")) {
                try {
                    // 使用配置文件中的指定上传目录与当前年月新建文件夹
                    LocalDateTime ldt = LocalDateTime.now();
                    String today = ldt.format(DateTimeFormatter.BASIC_ISO_DATE);
                    String useUploadPath = uploadFolder + "/documents"+ "/" + today + "/"; // 文件上传使用的目录
                    String picDir = dataPath + useUploadPath; // 文件绝对路径
                    
                    File createFile = new File(picDir);
                    if (!createFile.exists()) {// 判断文件是否存在如果不存在则自动创建文件夹
                        createFile.mkdir();
                    }
                    String uuid = UUID.randomUUID().toString().replace("-", "");// 随机生成一个唯一性的id 文件不重名
                    String suffix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
                    String newFilename = uuid + "." + suffix;
                    File f = new File(picDir + newFilename);
                    if (f.exists()) {
                        f.delete();// 上传的文件已经存在,就删除保存最新的文件
                    } 
                    file.transferTo(f); // 将上传的文件写入到系统中
                    return R.ok().put("filename", useUploadPath + newFilename);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return R.error("上传文件失败, 只允许上传doc,docx文件");
            }
        }
        return R.error("上传文件不能为空");
    }

    @PostMapping("/uploadfile")
    public R uploadFile(@RequestParam(value = "upload_file") MultipartFile file, HttpServletRequest request) throws IOException {
        
        String useUploadPath = uploadFolder + "/documents"; // 文件上传使用的目录

        String fileOldName = file.getOriginalFilename();
        // 上传的文件只允许是 pdf、doc 或 docx 中的格式
        if (fileOldName.contains(".pdf") || fileOldName.contains(".doc") || fileOldName.contains(".docx")) {
            Map<String, Object> resultSave = saveFile(file, useUploadPath, true);
            if ((Integer) resultSave.get("status") != 0) {
                return R.error((String) resultSave.get("msg"));
            }
            return R.ok(resultSave);
        } else {
            return R.error("上传文件失败, 只允许上传pdf,doc,docx文件");
        }
    }

    /*
     * 读取指定路径下的文件名和目录名
     */
    @RequestMapping("/list")
    public R list(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String activepath = request.getParameter("activepath");
        // System.out.println(activepath);
        String dir = "";
        if (activepath != null && activepath != "") {
            dir = activepath;
        }

        File file = new File(dataPath + dir);
        // System.out.println(dataPath + dir);
        File[] fileList = file.listFiles();

        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> rfile = new HashMap<String, Object>();

        for (int i = 0; i < fileList.length; i++) {
            File ifile = fileList[i];

            String fileName = ifile.getName();

            long time = fileList[i].lastModified();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置格式
            String modifyTime = format.format(time); // 获得带格式的字符串

            String suffix = "";
            String size = "";
            if (ifile.isFile()) {
                suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                long s = ifile.length();
                size = sizeBKM(s);
            }
            rfile.put("fileName", fileName);
            rfile.put("suffix", suffix);
            rfile.put("size", size);
            rfile.put("modifyTime", modifyTime);

            resultList.add(rfile);

        }

        result.put("resultList", resultList);
        result.put("activepath", dir);
        // System.out.println(dir);
        return R.ok(result);
    }

    public String sizeBKM(long filesize) {
        String size = "";
        if (filesize > 1024) {
            DecimalFormat decimalFormat = new DecimalFormat(".00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
            Double lsize = filesize / 1024d;
            if (lsize > 1024) {
                lsize = lsize / 1024;

                size = decimalFormat.format(lsize) + "M";
            } else {
                size = decimalFormat.format(lsize) + "K";
            }
        } else {
            size = filesize + "B";
        }
        return size;
    }

    /**
     * 删除文件
     * 
     * @param pathname
     * @return
     * @throws IOException
     */
    public static boolean deleteFile(String pathname) {
        boolean result = false;
        File file = new File(pathname);
        if (file.exists()) {
            file.delete();
            result = true;
        }
        return result;
    }

    /**
     * 删除目录
     * 
     * @param pathname
     * @return
     * @throws IOException
     */
    public static boolean deleteDir(String pathname) {
        boolean result = false;
        File dir = new File(pathname);
        if (dir.exists()) {
            File[] files = dir.listFiles();
            if (null == files) {
                dir.delete();
                result = true;
            }
        }
        return result;
    }

    @PostMapping("/delete")
    public R deleteFile(String activePath, String fileName) {
        boolean result = false;
        String dir = "";
        if (activePath != null || activePath != "") {
            dir = activePath;
        }

        String pathname = dataPath + dir + "/" + fileName;
        // System.out.println(pathname);
        File file = new File(pathname);
        if (!file.exists()) {
            return R.error(1, "文件or文件夹不存在");
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File f : files) {
                    if (f.exists()) {
                        f.delete();
                    }
                }
            }
            result = file.delete();
        }

        if (file.isFile()) {
            result = file.delete();
        }

        if (!result) {
            return R.error("删除失败");
        }
        return R.ok();
    }

    @RequestMapping("/filesupload")
    public R filesUpload(@RequestParam("myfiles") MultipartFile[] files, HttpServletRequest request) {
        List<String> list = new ArrayList<String>();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // 保存文件
                list = saveFile(file, list);
            }
        }
        return R.ok().put("list", list);// 跳转的页面
    }

    private List<String> saveFile(MultipartFile file, List<String> list) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 使用配置文件中的指定上传目录与当前年月新建文件夹
                LocalDateTime ldt = LocalDateTime.now();
                String today = ldt.format(DateTimeFormatter.BASIC_ISO_DATE);
                String useUploadPath = uploadFolder + "/" + today + "/";
                String picDir = dataPath + useUploadPath; // 文件绝对路径
                
                File createFile = new File(picDir);
                if (!createFile.exists()) {// 判断文件是否存在如果不存在则自动创建文件夹
                    createFile.mkdir();
                }
                String fileOldName = file.getOriginalFilename();
                // 上传的图片只允许是 png、jpg 或 gif 中的格式
                if (file.getOriginalFilename().contains(".png") || file.getOriginalFilename().contains(".jpg")
                || file.getOriginalFilename().contains(".gif")) {
                    String uuid = UUID.randomUUID().toString().replace("-", "");// 随机生成一个唯一性的id 文件不重名
                    String suffix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
                    String newFilename = uuid + "." + suffix;
                    File f = new File(picDir + newFilename);
                    if (f.exists()) {// 上传的文件已经存在,则提示用户重新上传 apk 或者重命名
                        // list.add("上传的文件已经存在,则提示用户重新上传 apk 或者重命名");
                        return list;
                    } else {
                        file.transferTo(f); // 将上传的文件写入到系统中
                        list.add(useUploadPath + newFilename);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    

    private Map<String, Object> saveFile(MultipartFile file) {
        return saveFile(file, "", false);   // 使用当前年月日目录,uuid新文件名
    }

    private Map<String, Object> saveFile(MultipartFile file, String desDir, 
        Boolean useOldname) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!file.isEmpty()) {
            try {
                String useUploadPath = "";
                if (desDir != null && !desDir.equals("")) {
                    useUploadPath = desDir + "/";
                } else {
                    // 使用配置文件中的指定上传目录与当前年月新建目录
                    LocalDateTime ldt = LocalDateTime.now();
                    String today = ldt.format(DateTimeFormatter.BASIC_ISO_DATE);
                    useUploadPath = uploadFolder + "/" + today + "/";
                }
                String absolutePath = dataPath + useUploadPath; // 目录绝对路径

                // 判断目录是否存在, 如果不存在则自动创建目录
                File createFile = new File(absolutePath);
                if (!createFile.exists()) {
                    createFile.mkdir();
                }

                String newFilename = "";
                String fileOldName = file.getOriginalFilename();
                String suffix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
                if (useOldname) {
                    newFilename = fileOldName;
                } else {
                    String uuid = UUID.randomUUID().toString().replace("-", "");// 随机生成一个唯一性的id 文件不重名
                    newFilename = uuid + "." + suffix;
                }

                File f = new File(absolutePath + newFilename);
                if (f.exists()) {
                    result.put("status", 1);  // 上传的文件已经存在,则提示用户重新上传图片或者重命名
                    result.put("msg", "上传的文件已经存在,则提示用户重新上传图片或者重命名");  // 上传的文件已经存在,则提示用户重新上传图片或者重命名
                } else {
                    file.transferTo(f); // 将上传的文件写入到系统中
                    result.put("status", 0);
                    result.put("filename", useUploadPath + newFilename);
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("status", 2);
                result.put("msg", e.getMessage());
            }
        }

        return result;
    }
}
