package com.liquidnet.service.galaxy.biz;

import com.liquidnet.commons.lang.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @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();
        }
    }

    public static HashMap<String,Integer> getImageWidthAndHeight(String imgLocalFilePath){


        HashMap rsHashMap = CollectionUtil.mapStringInteger();
//        String imgLocalFilePath = "/Users/anjiabin/Downloads/zxl_image_test_001.jpg";
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new FileInputStream(imgLocalFilePath));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("xuper getImageWidthAndHeight error:"+e.getMessage(),e);
        }
        int height = bufferedImage.getHeight();
        int width = bufferedImage.getWidth();
        rsHashMap.put("width",width);
        rsHashMap.put("height",height);
        log.info("getImageWidthAndHeight width=={} height=={}",width,height);
        return rsHashMap;
    }

    public static boolean isImageType(String imageUrl){
//        ”jpg”, “jpeg”, “png”, “bmp”, “webp”, “heic”
        String[] imageArray = {"jpg","jpeg","png","bmp","webp","hejc"};
        String imageType = null;

        if(imageUrl.lastIndexOf("?")!=-1){
            String tempUrl = imageUrl.substring(0,imageUrl.lastIndexOf("?"));
            imageType = tempUrl.substring(tempUrl.lastIndexOf(".")+1,tempUrl.length());
        }else{
            imageType = imageUrl.substring(imageUrl.lastIndexOf(".")+1,imageUrl.length());
        }
        System.out.println("imageType====="+imageType);
        if(Arrays.asList(imageArray).contains(imageType.toLowerCase())){
            return true;
        }
        return false;
    }

}
