package com.fdage.util;

import com.alibaba.fastjson.JSONObject;
import com.fdage.respon.ResponExhibition;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.codec.digest.DigestUtils;
//import org.apache.tools.zip.ZipEntry;
//import org.apache.tools.zip.ZipFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 文件管理工具类
 * Created by Hb_zzZ on 2018/11/26.
 */
@Slf4j
public class FileUtil {

    /**
     * 上传文件
     * @param file 文件
     * @param path 文件存放路径
     * @param fileName 源文件名
     * @return
     */
    public static boolean upload(MultipartFile file, String path, String fileName){

        // 生成新的文件名
        //String realPath = path + "/" + FileNameUtils.getFileName(fileName);

        //使用原文件名
        String realPath = path + "/" + fileName;

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    public static void writeFile(String filePath,String str) throws IOException {
        File fout = new File(filePath);
        FileOutputStream fos = new FileOutputStream(fout);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        bw.write(str);
        bw.close();
    }

    //按行读文件
    public static String readFile(String path)throws Exception
    {
        File f = new File(path);
        if(!f.exists()){
            return null;
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());
        BufferedInputStream in = null;
        try{
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while(-1 != (len = in.read(buffer,0,buf_size))){
                bos.write(buffer,0,len);
            }
            return bos.toString();
        }catch (IOException e) {
            e.printStackTrace();
            throw e;
        }finally{
            try{
                in.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

    //按行读文件
    public static int readLineCount(String path)throws Exception
    {
        File f = new File(path);
        if(!f.exists()){
            return 0;
        }

        int count = 0;
        //BufferedReader是可以按行读取文件
        FileInputStream inputStream = new FileInputStream(path);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;
        while((str = bufferedReader.readLine()) != null)
        {
            if(str==null||str.trim().equals(""))
            {
                continue;
            }
            else
            {
                ++count;
            }
        }

        //close
        inputStream.close();
        bufferedReader.close();

        return count;
    }

    //按行读文件
    public static List<String> readFileByLine(String path)throws Exception
    {
        File f = new File(path);
        if(!f.exists()){
            return null;
        }

        List<String> result = new ArrayList<String>();
        //BufferedReader是可以按行读取文件
        FileInputStream inputStream = new FileInputStream(path);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;
        while((str = bufferedReader.readLine()) != null)
        {
            if(str==null||str.trim().equals(""))
            {
                continue;
            }
            else
            {
                result.add(str);
            }
        }

        //close
        inputStream.close();
        bufferedReader.close();

        return result;
    }

    public static void decodeBase64(String path,String str) throws Exception{
        byte[] bt = null;
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

            if(str.startsWith("data:image/png;base64,"))
            {
                bt = decoder.decodeBuffer( str.replace("data:image/png;base64,", "") );
            }
            else if(str.startsWith("data:image/jpeg;base64,"))
            {
                bt = decoder.decodeBuffer( str.replace("data:image/jpeg;base64,", "") );
            }
            else if(str.startsWith("data:image/bmp;base64,"))
            {
                bt = decoder.decodeBuffer( str.replace("data:image/bmp;base64,", "") );
            }
            else
            {
                log.error("FileUtil-decodeBase64:"+path);
                return;
            }

            //bt = decoder.decodeBuffer(str);
            writeBinary(bt,path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeBinary(byte[] buf,String filePath)throws Exception
    {
        File fout = new File(filePath);
        if(!fout.getParentFile().exists())
        {
            fout.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(fout);
        ByteArrayInputStream stream = new ByteArrayInputStream(buf);
        BufferedOutputStream bos = new BufferedOutputStream(fos);//设置输出路径
        BufferedInputStream bis = new BufferedInputStream(stream);
        int b = -1;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        bis.close();
        bos.close();
    }

    public static boolean deleteFile(String sPath) {

        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    //下载多个文件
//    public static void downLoadFromUrls(String urlStr,String fileName,String savePath,String projectNum){
//
//        try
//        {
//            File file = new File(savePath+File.separator+fileName);
//            if(file.exists())
//            {
//                List<String> list = readFileByLine(savePath+File.separator+fileName);
//                for(int i=0;i<list.size();++i)
//                {
//                    String str = list.get(i);
//                    String name = str.substring(str.lastIndexOf("/")+1);
//                    downLoadFromUrl( str, name, savePath+File.separator+name, projectNum);
//                }
//            }
//            else
//            {
//                downLoadFromUrl( urlStr, fileName, savePath, projectNum);
//            }
//        }
//        catch(Exception e)
//        {
//            log.info("下载场景文件失败！"+projectNum+":"+urlStr);
//            e.printStackTrace();
//            StringWriter trace=new StringWriter();
//            e.printStackTrace(new PrintWriter(trace));
//            log.error(trace.toString());
//            deleteFile(savePath+File.separator+fileName);
//            downLoadFromUrls( urlStr, fileName, savePath, projectNum);
//        }
//    }

//    public static void downLoadFromUrl(String urlStr,String fileName,String savePath,String projectNum){
//        try
//        {
//            URL url = new URL(urlStr);
//            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//            //设置超时间为3秒
//            conn.setConnectTimeout(3*1000);
//            //防止屏蔽程序抓取而返回403错误
//            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//
//            //得到输入流
//            InputStream inputStream = conn.getInputStream();
//            //获取自己数组
//            byte[] getData = readInputStream(inputStream);
//
//            //文件保存位置
//            File saveDir = new File(savePath);
//            if(!saveDir.exists()){
//                saveDir.mkdir();
//            }
//            File file = new File(saveDir+File.separator+fileName);
//            FileOutputStream fos = new FileOutputStream(file);
//            fos.write(getData);
//
//            //获取文件md5
//            DigestUtils.md5Hex(new FileInputStream(saveDir+File.separator+fileName));
//            if(fos!=null){
//                fos.close();
//            }
//            if(inputStream!=null){
//                inputStream.close();
//            }
//            log.info("下载场景文件成功！"+projectNum+":"+urlStr);
//        }
//        catch(FileNotFoundException e)
//        {
//            log.info("要下载场景的文件不存在"+projectNum+":"+urlStr);
//        }
//        catch(Exception e)
//        {
//            log.info("下载场景文件失败！"+projectNum+":"+urlStr);
//            e.printStackTrace();
//            StringWriter trace=new StringWriter();
//            e.printStackTrace(new PrintWriter(trace));
//            log.error(trace.toString());
//            deleteFile(savePath+File.separator+fileName);
//            downLoadFromUrl( urlStr, fileName, savePath, projectNum);
//        }
//    }

    public static void downLoadFromUrl(String urlStr,String fileName,String savePath){
        try
        {
            //文件保存位置
            File saveDir = new File(savePath);
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            File file = new File(savePath+File.separator+fileName);
            if(file.exists())
            {
                return;
            }

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if(fos!=null){
                fos.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            log.info("下载文件成功！"+":"+urlStr);
        }
        catch(FileNotFoundException e)
        {
            log.info("要下载的文件不存在:"+urlStr);
        }
        catch(Exception e)
        {
            log.info("下载文件失败！"+":"+urlStr);
            e.printStackTrace();
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
            deleteFile(savePath+File.separator+fileName);
            downLoadFromUrl( urlStr, fileName, savePath);
        }
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

//    public static void decompress(String srcPath, String dest) throws Exception {
//
//        File file = new File(srcPath);
//
//        if (!file.exists()) {
//
//            throw new RuntimeException(srcPath + "所指文件不存在");
//
//        }
//
//        ZipFile zf = new ZipFile(file);
//
//        Enumeration entries = zf.getEntries();
//
//        ZipEntry entry = null;
//
//        while (entries.hasMoreElements()) {
//
//            entry = (ZipEntry) entries.nextElement();
//
//            log.info("解压" + entry.getName());
//
//            if (entry.isDirectory()) {
//
//                String dirPath = dest + File.separator + entry.getName();
//
//                File dir = new File(dirPath);
//
//                dir.mkdirs();
//
//            } else {
//
//                // 表示文件
//
//                File f = new File(dest + File.separator + entry.getName());
//
//                if (!f.exists()) {
//
//                    //String dirs = FileUtils.getParentPath(f);
//                    String dirs =  f.getParent();
//
//                    File parentDir = new File(dirs);
//
//                    parentDir.mkdirs();
//
//
//
//                }
//
//                f.createNewFile();
//
//                // 将压缩文件内容写入到这个文件中
//
//                InputStream is = zf.getInputStream(entry);
//
//                FileOutputStream fos = new FileOutputStream(f);
//
//
//
//                int count;
//
//                byte[] buf = new byte[8192];
//
//                while ((count = is.read(buf)) != -1) {
//
//                    fos.write(buf, 0, count);
//
//                }
//
//                is.close();
//
//                fos.close();
//
//            }
//
//        }
//
//    }

    public static boolean copyFile(String srcFileName, String destFileName,  boolean overlay) {
        File srcFile = new File(srcFileName);

        // 判断源文件是否存在
        if (!srcFile.exists()) {
            return false;
        } else if (!srcFile.isFile()) {
            return false;
        }

        // 判断目标文件是否存在
        File destFile = new File(destFileName);
        if (destFile.exists()) {
            // 如果目标文件存在并允许覆盖
            if (overlay) {
                // 删除已经存在的目标文件，无论目标文件是目录还是单个文件
                new File(destFileName).delete();
            }
        } else {
            // 如果目标文件所在目录不存在，则创建目录
            if (!destFile.getParentFile().exists()) {
                // 目标文件所在目录不存在
                if (!destFile.getParentFile().mkdirs()) {
                    // 复制文件失败：创建目标文件所在目录失败
                    return false;
                }
            }
        }

        // 复制文件
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String[]readfileNamesForDirectory(String path) throws Exception{
        File file = new File(path);
        if(file.isDirectory()) {
            String[] fileNames = file.list();
            return fileNames;
        }
        return null;
    }

    public static List<String> readfileNamesForDirectory(String path,String except) throws Exception{
        File file = new File(path);
        if(file.isDirectory())
        {
            String[] fileNames = file.list();
            List<String> list = new ArrayList<String>();
            if(fileNames!=null)
            {
                for(int i=0;i<fileNames.length;++i)
                {
                    if(fileNames[i].toLowerCase().endsWith(except) )
                    {
                        list.add(fileNames[i]);
                    }
                }
            }

            return list;
        }
        return null;
    }

    //删除文件夹
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下的所有文件
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        if(tempList!=null)
        {
            for (int i = 0; i < tempList.length; i++) {
                if (path.endsWith(File.separator)) {
                    temp = new File(path + tempList[i]);
                } else {
                    temp = new File(path + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                    delFolder(path + "/" + tempList[i]);//再删除空文件夹
                    flag = true;
                }
            }
        }

        //再删除当前空文件夹
        file.delete();
        return flag;
    }

    // 流转化成字符串
    public static String inputStream2String(InputStream is) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1)
        {
            baos.write(i);
        }
        return baos.toString();
    }

    // 流转化成文件
    public static void inputStream2File(InputStream is, String savePath)throws Exception
    {
        log.info("来自app的录屏音频文件保存路径为:" + savePath);
        File file = new File(savePath);
        if(file.exists())
        {
            deleteFile(savePath);
        }
        InputStream inputSteam = is;
        BufferedInputStream fis = new BufferedInputStream(inputSteam);
        FileOutputStream fos = new FileOutputStream(file);
        int f;
        while ((f = fis.read()) != -1)
        {
            fos.write(f);
        }
        fos.flush();
        fos.close();
        fis.close();
        inputSteam.close();
    }

    public static void saveImageToDisk(String accessToken, String mediaId, String picName, String picPath,InputStream inputStream)
            throws Exception {
        byte[] data = new byte[10240];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(picPath+picName+".amr");
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        try{
//            FileUtil.writeFile("G:\\java project\\test.json","{\"scenePsd\":\"\",\"public\":0,\"sceneType\":\"0\",\"sceneName\":\"1314家装互联网峰会\",\"shootCount\":\"40\",\"thumbImg\":0,\"floorLogo\":0,\"version\":1,\"hasBGM\":\"欢快\"}");
//            File saveDir = new File("G:\\java project\\test.json");
//            System.out.println("路径：" + saveDir);
//            String parametr = "7sd:;szx";
//            Integer resolution = new Integer(1);
//            parametr += ":;" + (resolution == null ? 0 : resolution.intValue());
            ResponExhibition responExhibition = new ResponExhibition();
            responExhibition.setName("123asd");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", 0);
            jsonObject.put("data", responExhibition);
            System.out.println(jsonObject.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
