package com.dk.mdm.infrastructure.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @Author: bo2
 * @Desc:
 * @Date: 2022/3/23 10:03
 */
@Component
public class FileUtils {

    @Value("${apk-folder}")
    private String apkFolder;

    @Value("${apk-file-name}")
    private String apkFileName;

    @Value("${apk-version}")
    private String apkVersion;

    @Value("${apk-file-name-smtt}")
    private String apkFileNameSmtt;

    @Value("${apk-version-smtt}")
    private String apkVersionSmtt;

    @Value("${apk-file-name-crosswalk}")
    private String apkFileNameCrosswalk;

    @Value("${apk-version-crosswalk}")
    private String apkVersionCrosswalk;

    /**
     * @AUTHOR 沈博
     * @DATE_TIME 2022/3/23 10:05
     * @DESCRIPTION 生成文件
     */
    public static void generateFile(HttpServletResponse response, String data, String fileName, String path) throws IOException {

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(path + fileName);
        file.setReadable(true, false);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWritter = new FileWriter(path + fileName, true);
        fileWritter.write(data);
        fileWritter.close();
        download(response, file);
    }

    /**
     * @AUTHOR 沈博
     * @DATE_TIME 2022/3/23 10:05
     * @DESCRIPTION 下载文件
     */
    public static void download(HttpServletResponse response, File file) {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            String fileName = file.getName();
            if (!file.exists()) {
                return;
            }
            ips = new FileInputStream(file);
            response.setContentType("multipart/form-data");
            response.addHeader("Content-Disposition", "attachment; filename=\""
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"");
            out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                ips.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * @desc : 需要去后台下载新的安装包
     * @author : 姜永辉
     * @date : 2023/05/09 17:19
     */
    public static String downloadFile(HttpServletResponse response, String fileName) {
        File path = null;
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(path + "/doc/" + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (FileNotFoundException e1) {
            //e1.getMessage()+"系统找不到指定的文件";
            return "系统找不到指定的文件";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }

    /*
     * @desc   : 实现Spring Boot 的文件下载功能，映射网址为/download
     * @author : 姜永辉
     * @date   : 2023/05/10 8:13
     */
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response ,String code)  {

        String fileName ; //下载的文件名
        if ("X5".equals(code)){
            fileName =  apkFileNameSmtt;
        }else if ("CrossWalk".equals(code)){
            fileName = apkFileNameCrosswalk;
        }else{
            fileName = apkFileName;
        }
        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = apkFolder;
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                try {
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setHeader("Content-Length", "" + file.length());
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download the song successfully!");
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }



    /*
     * @desc   : 实现Spring Boot 的文件下载功能，映射网址为/download
     * @author : 姜永辉
     * @date   : 2023/05/10 8:13
     */
    public Stream downloadFile(String code)  {
        String fileName ; //下载的文件名
        if ("X5".equals(code)){
            fileName =  apkFileNameSmtt;
        }else if ("CrossWalk".equals(code)){
            fileName = apkFileNameCrosswalk;
        }else{
            fileName = apkFileName;
        }
        FileInputStream fis = null;
        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = apkFolder;
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {
                // 实现文件下载
                try {
                    fis = new FileInputStream(file);
                    System.out.println("Download the song successfully!");
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return (Stream) fis;
    }

    /**
     * @desc   : apk版本-不同內核的版本不同
     * @author : 姜永辉
     * @date   : 2023/05/10 8:23
     */
    public Map<String,Object> getApkVersion(String type){
        Map<String,Object> map = new HashMap<>();
        String  fileName  ;
        if (type.equals("X5")){
            //X5內核
            map.put("version",apkVersionSmtt);
            fileName =  apkFileNameSmtt;

        }else if (type.equals("CrossWalk")){
//            crosswalk內核
            map.put("version",apkVersionCrosswalk);
            fileName = apkFileNameCrosswalk;
        }else{
            //原生android-webiview
            map.put("version",apkVersion);
            fileName = apkFileName;
        }
        //设置文件路径
        String realPath = apkFolder;
        File file = new File(realPath, fileName);
        map.put("apksize",file.length());
        return map;
    }
}
