package com.xkrs.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author XinYi Song
 */
public class PhotoUtil {

    public static Logger log = LoggerFactory.getLogger(PhotoUtil.class);

    /**
     * 上传单张图片
     * @param imgFile
     * @return
     * @throws IOException
     */
    public static String memoryPhoto(MultipartFile imgFile) throws IOException {
        //String uploadPath = "http://139.199.98.175:2088/wfTaskImage/";
//        String uploadPath = "http://192.168.2.139";
        String uploadPath = "/";
        //获取原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        if (originalFilename != null && !"".equals(originalFilename)) {
            //找到 . 的位置
            int index = originalFilename.lastIndexOf(".");
            //根据 . 的位置进行分割，拿到文件后缀名
            String suffix = originalFilename.substring(index);
            //uuid生成新的文件名
            String newName = UUID.randomUUID().toString() + suffix;

            //将图片保存到本地/usr/etc/images/Folder
            File file = new File("E:/img/");
            if (!file.exists()) {
                file.mkdirs();
            }
            String path = "E:/img/" + newName;
            String uploadsImage = uploadPath + newName;
            //实现上传
            imgFile.transferTo(new File(path));


            return uploadsImage;
        }
        return null;
    }

    /**
     * 以文件形式，批量上传图片
     * @param files
     * @return
     * @throws IOException
     */
    /*public static List<FireTaskPhoto> uploadImage(MultipartFile[] files, String fireCode) throws IOException {
        //String uploadPath = "http://139.199.98.175:2099/forestTaskImage/";
        String uploadPath = "http://118.24.27.47:2088/";
        String newName = "";
        String oldName = "";
        List<FireTaskPhoto> fireTaskPhotos = new ArrayList<>();
        for(MultipartFile file : files){
            //获取file图片名称
            oldName = file.getOriginalFilename();
            //找到 . 的位置
            int index = oldName.lastIndexOf(".");
            //根据 . 的位置进行分割，拿到文件后缀名
            String suffix = oldName.substring(index);
            //uuid生成新的文件名
            newName = UUID.randomUUID().toString() + suffix;
            //将图片保存到本地/usr/etc/images/Folder
            File file1 = new File("/home/sxy/server/fire_point/firePointImage/");
            //File file1 = new File("E:/file/work/image/");
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String path = "/home/sxy/server/fire_point/firePointImage/" + newName;
            //String path = "E:/file/work/image/" + newName;
            String uploadPaths = "/firePointImage/" + newName;
            //实现上传
            file.transferTo(new File(path));
            FireTaskPhoto fireTaskPhoto = new FireTaskPhoto();
            fireTaskPhoto.setPhotoFireCode(fireCode);
            fireTaskPhoto.setTaskPhoto(uploadPaths);

            fireTaskPhotos.add(fireTaskPhoto);
        }
        return fireTaskPhotos;
    }*/



    /**
     * 删除本地或服务器储存的图片
     * @param path
     * @return
     */
    public static String delFile(String path){
        String resultInfo = null;
        int lastIndexOf = path.lastIndexOf("/");
        String imgPath = path.substring(lastIndexOf + 1,path.length());
        System.out.println(imgPath);
        imgPath = "/usr/local/etc/images/" + imgPath;
//        img_path = "/usr/etc/images/Folder/" + img_path;
        File file = new File(imgPath);
        if(file.exists()){
            if(file.delete()){
                resultInfo = "删除成功！";
            }else {
                resultInfo = "删除失败！";
            }
        }else {
            resultInfo = "文件不存在";
        }
        return resultInfo;
    }

    /**
     * 通过图片路径解析 ，上传保存
     * @param listImgSrc
     * @return
     */
    public static List downloadImage(List<String> listImgSrc) {
        try {
            List list = new ArrayList();
            //开始时间
            Date beginDate = new Date();
            for (String url : listImgSrc) {
                //开始时间
                Date beginDate2 = new Date();
                String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());
                URL uri = new URL(url);
                InputStream in = uri.openStream();
                //String pathUpload = "E:/img/" + imageName;
                String pathUpload = "/home/web/wf-fire-service/wfimage/" + imageName;
                FileOutputStream fo = new FileOutputStream(new File(pathUpload));
                byte[] buf = new byte[1024];
                int length = 0;
                log.info("-------开始下载:" + url);
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    fo.write(buf, 0, length);
                }
                in.close();
                fo.close();
                list.add(imageName);
                log.info(imageName + "------下载完成");
                //结束时间
                Date overDate2 = new Date();
                double time = overDate2.getTime() - beginDate2.getTime();
                log.info("-----耗时：" + time / 1000 + "s");
            }
            Date overDate = new Date();
            double time = overDate.getTime() - beginDate.getTime();
            log.info("======总耗时：" + time / 1000 + "s");
            return list;
        } catch (Exception e) {
            log.info("++++++下载失败");
        }
        return null;
    }

    /**
     * 删除本地文件夹图片
     * @param url
     */
    public static void deleteImage(String url){
        File file=new File(url);
        //判断file是否是文件目录 若是返回TRUE
        if (file.isDirectory()){
            //name存储file文件夹中的文件名
            String[] name =file.list();
            for (int i=0; i<name.length; i++){
                //此时就可得到文件夹中的文件
                File f=new File(url, name[i]);
                //删除文件
                f.delete();
            }
        }
    }
}
