package com.sunyard.ssp.utils;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author:tsz
 * @date:2020/3/6
 * @description:
 */
@Component
@Slf4j
public class FileUtil {

    @Value("${file.path}")
    private String filePath;

    /**
     * 文件路径上传完整路径
     *
     * @param file
     * @return
     */
    public String localUpload(MultipartFile file) {

        String key = CommonUtil.renamePic(file.getOriginalFilename());
        String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String path = filePath + "/" + day;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File f = new File(path + "/" + key);
        if (f.exists()) {
            throw new RuntimeException("文件名已存在");
        }
        try {
            file.transferTo(f);
            return path + "/" + key;
        } catch (IOException e) {
            log.error(e.toString());
            throw new RuntimeException("上传文件出错");
        }
    }

    /**
     * 文件路径上传只返回文件名
     *
     * @param file
     * @return
     */
    public String upload(MultipartFile file) throws IOException {
        try {
            //String key = Md5Util.md5HashCode(file.getInputStream()) +"_"+ file.getOriginalFilename();
            String key = file.getOriginalFilename();
            String s = Md5Util.little16MD5a(DigestUtils.md5Hex(file.getInputStream()));
            String path = filePath + "/" + s;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(path + "/" + key);
            //如果文件已经存在直接返回文件名证明快速上传了
            if (f.exists()) {
                return s + "/" +key;
            }
            file.transferTo(f);
            key = s + "/"+ key;
            return key;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            throw new RuntimeException("上传文件出错");
        }
    }

    /**
     * 读取文件
     *
     * @param url
     * @param response
     */
    public void view(String url, HttpServletResponse response) {

        File file = new File(url);
        FileInputStream i = null;
        OutputStream o = null;

        try {
            i = new FileInputStream(file);
            o = response.getOutputStream();

            byte[] buf = new byte[1024];
            int bytesRead;

            while ((bytesRead = i.read(buf)) > 0) {
                o.write(buf, 0, bytesRead);
                o.flush();
            }

            i.close();
            o.close();
        } catch (IOException e) {
            log.error(e.toString());
            throw new RuntimeException("读取文件出错");
        }
    }

    /**
     * 重命名
     *
     * @param url
     * @param toKey
     * @return
     */
    public String renameFile(String url, String toKey) {

        String result = copyFile(url, toKey);
        deleteFile(url);
        return result;
    }

    /**
     * 复制文件
     *
     * @param url
     * @param toKey
     */
    public String copyFile(String url, String toKey) {

        File file = new File(url);
        FileInputStream i = null;
        FileOutputStream o = null;

        try {
            i = new FileInputStream(file);
            o = new FileOutputStream(new File(file.getParentFile() + "/" + toKey));

            byte[] buf = new byte[1024];
            int bytesRead;

            while ((bytesRead = i.read(buf)) > 0) {
                o.write(buf, 0, bytesRead);
            }

            i.close();
            o.close();
            return file.getParentFile() + "/" + toKey;
        } catch (IOException e) {
            log.error(e.toString());
            throw new RuntimeException("复制文件出错");
        }
    }

    /**
     * 删除文件
     *
     * @param url
     */
    public void deleteFile(String url) {

        File file = new File(url);
        file.delete();
    }

    /**
     * 删除文件
     *
     * @param url
     */
    public void deleteFileName(String url) {

        File file = new File(filePath + "/" + url);
        file.delete();
    }
}
