package com.liquidnet.service.galaxy.biz;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: GalaxyCommonBiz
 * @Package com.liquidnet.service.galaxy.router.strategy.biz
 * @Copyright: LightNet @ Copyright (c) 2022
 * @date 2022/3/23 11:20
 */
@Slf4j
@Component
public class GalaxyCommonBiz {
    @Value("${liquidnet.service.galaxy.temp-file-path}")
    private String tempFilePath;

    /**
     * 通过URL上传
     * @param url
     * @param name
     * @return
     */
    public File inputStreamToFile(String url, String name) {
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            InputStream ins = httpUrl.getInputStream();

            try{
                if (!(new File(tempFilePath)).exists()) {
                    (new File(tempFilePath)).mkdirs();
                }
            }catch(Exception e){
                log.error("创建素材上传目录异常：{}",e.getMessage());
                log.error(e.getMessage(),e);
            }
//            File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
            File file = new File(tempFilePath + File.separator + name);
            if (file.exists()) {
                return file;
            }
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            int len = 8192;
            byte[] buffer = new byte[len];
            while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return file;
        } catch (Exception e) {
            log.error("inputStreamToFileUrlError", e);
            return null;
        }
    }
    /*读取文件的字节数组*/

    public static byte[] toByteArray(File file) throws IOException {
        File f = file;
        if (!f.exists()) {
            throw new FileNotFoundException("file not exists");
        }

        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.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }
}
