package psdi.app.iface.mdm;

import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class FileUtil {
    public StringBuilder processFile(String fileUrl,String functionId) {
        StringBuilder doc = new StringBuilder();
        try {
            String fileTempPath ="/data/file/temp";//过渡缓存文件路径
            Map<String,Object> retDto = loadFileSyncData(fileUrl, functionId,fileTempPath);
            List<String> rfcFiles = (List<String>) retDto.get("rfcFiles");
            for (int i = 0; i < rfcFiles.size(); i++) {
                String path = rfcFiles.get(i);
                File file = new File(path);
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
                String s = null;
                int line = 0;
                StringBuffer sql = new StringBuffer();
                String first = "";
                boolean isFirst = true;
                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                    doc.append(s);
                }
                br.close();
            }
            String zipUnCompressFileName = (String) retDto.get("zipUnCompressFileName");
            String filePath = (String) retDto.get("filePath");
            //删除解压后的的所有文件
            deletefile(zipUnCompressFileName);
            //删除压缩文件
            File delfile = new File(filePath);
            if (!delfile.isDirectory()) {
                delfile.delete();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return doc;

    }

    public Map loadFileSyncData(String fileUrl,String rfcName,String fileTempPath){
        Map<String,Object> retDto = new HashMap();
        try{
            //log.info("下载文件进行数据同步开始:" + dto.get("rfcName"));
            long startTime = System.currentTimeMillis();
            String filePath = "";
            boolean successDown = false;
            String currentTime = System.currentTimeMillis()+"";
            File posFile = new File(fileTempPath);
            if(!posFile.exists()){
                posFile.mkdirs();
            }
            filePath =fileTempPath+rfcName+"_"+currentTime+".zip";
            successDown = download(fileUrl,filePath);
            long endTime = System.currentTimeMillis();
            float time=(float)(endTime-startTime)/1000;
            //log.info("接口："+dto.get("rfcName")+"下载文件消耗时间--------"+time+"s");
            //log.info("接口："+dto.get("rfcName")+"下载文件消耗时间--------"+time+"s");

            if(!successDown){
                retDto.put("error", "远程同步文件下载失败！");
                //log.error("远程同步文件下载失败1");
                throw new Exception("远程同步文件下载失败！");
            }
            if(filePath!=null && filePath.length()>0 && successDown){
                startTime = System.currentTimeMillis();
                String zipUnCompressFileName = fileTempPath+"/"+rfcName+"_"+currentTime;
                zipUncompress(filePath,zipUnCompressFileName);
                endTime = System.currentTimeMillis();
                time=(float)(endTime-startTime)/1000;
                //log.info("接口："+dto.get("rfcName")+"解压文件消耗时间--------"+time+"s");
                //log.info("接口："+dto.get("rfcName")+"解压文件消耗时间--------"+time+"s");
                //log.info(zipUnCompressFileName+"解压成功");
                List<String> rfcFiles = new ArrayList<String>();
                startTime = System.currentTimeMillis();
                readfile(zipUnCompressFileName,rfcFiles);

                retDto.put("rfcFiles", rfcFiles);

                endTime = System.currentTimeMillis();
                float time1=(float)(endTime-startTime)/1000;
                retDto.put("zipUnCompressFileName", zipUnCompressFileName);
                retDto.put("filePath", filePath);
            }else{
                retDto.remove("success");
                retDto.put("error", "远程同步文件下载失败！");
                throw new Exception("同步文件下载失败！");
            }

        } catch (Exception e) {
            retDto.put("error", e.getMessage());
            e.getMessage();
        }
        return retDto;
    }


    private static boolean download(String downloadUrl,String path) {
        URL url = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            url = new URL(downloadUrl);
            dataInputStream = new DataInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            output.close();
        } catch (IOException e) {
            //log.error("下载文件异常:" + e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            if (dataInputStream != null){
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public static void zipUncompress(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        ZipFile zipFile = new ZipFile(srcFile);//创建压缩文件对象
        //开始解压
        Enumeration<?> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            // 如果是文件夹，就创建个文件夹
            if (entry.isDirectory()) {
                String dirPath = destDirPath + "/" + entry.getName();
                srcFile.mkdirs();
            } else {
                // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                File targetFile = new File(destDirPath + "/" + entry.getName());
                // 保证这个文件的父文件夹必须要存在
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zipFile.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(targetFile);
                int len;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                fos.close();
                is.close();
            }
        }
    }

    /**
     * 读取某个文件夹下的所有文件(支持多级文件夹)
     */
    public static boolean readfile(String filepath,List<String> rfcFiles) throws FileNotFoundException, IOException {
        try {
            String pat = "\\";
            if(filepath.indexOf("/opt/apps")>=0){
                pat = "/";
            }
            File file = new File(filepath);
            if (!file.isDirectory()) {
//				log.info("文件");
//				log.info("path=" + file.getPath());
//				log.info("absolutepath=" + file.getAbsolutePath());
//				log.info("name=" + file.getName());
                rfcFiles.add(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                //log.info("文件夹");
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + pat + filelist[i]);
                    if (!readfile.isDirectory()) {
//						log.info("path=" + readfile.getPath());
//						log.info("absolutepath=" + readfile.getAbsolutePath());
//						log.info("name=" + readfile.getName());
                        rfcFiles.add(readfile.getAbsolutePath());
                    } else if (readfile.isDirectory()) {
                        readfile(filepath + pat + filelist[i],rfcFiles);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            //log.error("readfile()   Exception:" + e.getMessage());
        }
        return true;
    }

    public static boolean deletefile(String delpath) throws FileNotFoundException, IOException {
        try {
            File file = new File(delpath);
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File delfile = new File(delpath + "\\" + filelist[i]);
                    if (!delfile.isDirectory()) {
//						log.info("path=" + delfile.getPath());
//						log.info("absolutepath=" + delfile.getAbsolutePath());
//						log.info("name=" + delfile.getName());
                        delfile.delete();
//						log.info("删除文件成功");
                    } else if (delfile.isDirectory()) {
                        deletefile(delpath + "\\" + filelist[i]);
                    }
                }
                file.delete();
            }

        } catch (FileNotFoundException e) {
            //log.error("deletefile()   Exception:" + e.getMessage());
        }
        return true;
    }
}
