package com.jfinal.club.util;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.club.common.kit.ImageKit;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import sun.net.www.protocol.https.Handler;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.Collator;
import java.util.*;

/**
 * 发送请求帮助类
 *
 * @author YaoShiHang
 */
public class CommonUtil {

    public static Map< String, Object > cache = new HashMap<>( );

    private static Logger log = Logger.getLogger(CommonUtil.class);
    //用来产生随机验证码的
    private static Random rand = new Random( );
    private static String[] str = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

    public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
            jsonObject = JSONObject.parseObject(buffer.toString( ));
            //jsonObject = JSONObject.fromObject(buffer.toString( ));
        } catch (ConnectException ce) {
            log.error("连接超时：" + ce.getMessage( ));
        } catch (Exception e) {
            log.error("https请求异常：" + e.getMessage( ));
        }
        return jsonObject;
    }

    private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
            throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
            IOException, ProtocolException, UnsupportedEncodingException {
        URL url = new URL(null, requestUrl, new Handler( ));
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection( );
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        if (null != output) {
            OutputStream outputStream = connection.getOutputStream( );
            outputStream.write(output.getBytes("UTF-8"));
            outputStream.close( );
        }
        // 从输入流读取返回内容
        InputStream inputStream = connection.getInputStream( );
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        StringBuffer buffer = new StringBuffer( );
        while ((str = bufferedReader.readLine( )) != null) {
            buffer.append(str);
        }
        bufferedReader.close( );
        inputStreamReader.close( );
        inputStream.close( );
        inputStream = null;
        connection.disconnect( );
        return buffer;
    }

    /**
     * 获取几位随机数
     *
     * @param num 位数
     * @return
     */
    public static String getRandom(int num) {
        //存放产生的随机数
        String sms;
        //生成六位数的随机数
        StringBuffer buf = new StringBuffer( );
        for (int i = 0; i < num; i++) {
            buf.append(str[rand.nextInt(10)]);
        }
        sms = buf.toString( );
        return sms;
    }

    /**
     * 获取uuid 转小写
     *
     * @return
     */
    public static String getUUIDToLower( ) {
        return UUID.randomUUID( ).toString( ).trim( ).replace("-", "").toLowerCase( );
    }

    /**
     * 获取uuid 转大写
     *
     * @return
     */
    public static String getUUIDToUpper( ) {
        return UUID.randomUUID( ).toString( ).trim( ).replace("-", "").toUpperCase( );
    }


    /**
     * list集合按字典顺序排序
     *
     * @param list
     * @return
     */
    public static List chineseSort(List< String > list) {
        if (list == null || list.isEmpty( )) {
            return list;
        }
        Collections.sort(list, (o1, o2) -> {
            Comparator< Object > com = Collator.getInstance(Locale.CHINA);
            return com.compare(o1, o2);
        });
        return list;
    }

    public static String[] splitIgnoreCase(String str) {
        return str.split("[,，]+");
    }


    /**
     * 对象序列化成字节码数据
     *
     * @param obj
     * @return
     */
    public static byte[] setSerialize(Object obj) {
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream( );
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(byteOutStream);
            oos.writeObject(obj);
            oos.close( );
            return byteOutStream.toByteArray( );
        } catch (Exception e) {
            e.printStackTrace( );
        } finally {
            try {
                oos.close( );
            } catch (IOException e) {
                e.printStackTrace( );
            }
        }
        return null;
    }

    /**
     * 反序列化  字节码文件转对象
     *
     * @param bytes
     * @return
     */
    public static Object getSerialize(byte[] bytes) {
        ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(byteInStream);
            return ois.readObject( );
        } catch (Exception e) {
            e.printStackTrace( );
        } finally {
            try {
                ois.close( );
            } catch (IOException e) {
                e.printStackTrace( );
            }
        }
        return null;
    }


    /**
     * 添加到缓存中
     *
     * @param key
     * @param value
     */
    public static void setCache(String key, Object value) {
        cache.put(key, value);
    }

    /**
     * 从缓存中取出
     *
     * @param key
     * @return
     */
    public static Object getCache(String key) {
        return cache.get(key);
    }




    /**
     * 获取文件大小 格式化单位
     *
     * @param filepath
     * @return KB, MB, GB
     */
    public static String formatFileUnit(UploadFile filepath) {
        long length = filepath.getFile( ).length( );
        return sizeChange(length);
    }

    public static String sizeChange(long length) {
        if (length < 1024 * 1024) {
            long z = length / 1024;
            return "" + (z) + "KB";
        }

        if (length > 1024 * 1024 && length < 1024 * 1024 * 1024) {
            long z = length / (1024 * 1024);
            return "" + (z) + "MB";
        }

        if (length > 1024 * 1024 * 1024) {
            long z = length / (1024 * 1024 * 1024);
            long m = length % (1024 * 1024 * 1024) / (1000 * 1000 * 10);
            return "" + (z) + "." + m + "GB";
        }
        return "0KB";
    }

    public static String fileSize(long folderSize) {
        if (folderSize <= 0) {
            return "0KB";
        }
        long length = folderSize;
        return sizeChange(length);
    }

    /**
     * 获取文件路径
     *
     * @param uploadFile
     * @param folder
     * @return
     */
    public static String getFilePath(UploadFile uploadFile, String folder) {
        if (uploadFile != null) {
            return "/upload" + folder + uploadFile.getFileName( );
        }
        return "";
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static boolean deleteFile(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            String path = PathKit.getWebRootPath( ) + filePath;
            return new File(path).delete( );
        }
        return false;
    }

    /**
     * 文件上传
     *
     * @param img
     * @param folder
     * @return
     */
    public static String imgUpload(String img, String folder) {
        if (StringUtils.isBlank(img) || StringUtils.isBlank(folder)) {
            return "";
        }
        File file = new File(img);
        String f = PathKit.getWebRootPath( ) + "/upload/" + folder;
        File file1 = new File(f);
        if (!new File(f).exists( )) {
            file1.mkdirs( );
        }

        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file);
            out = new FileOutputStream(new File(f, file.getName( )));

            byte[] bytes = new byte[1024];
            int l;
            while ((l = in.read(bytes)) != -1) {
                out.flush( );
                out.write(bytes, 0, l);
            }
        } catch (IOException e) {
            e.printStackTrace( );
        } finally {
            try {
                in.close( );
                out.flush( );
                out.close( );
            } catch (IOException e) {
                e.printStackTrace( );
            }
        }
        return "/upload/" + folder + "/" + file.getName( );
    }


    /**
     * 迭代删除文件夹
     *
     * @param dirPath 文件夹路径
     */
    public static void deleteDir(String dirPath) {
        File file = new File(dirPath);
        if (file.isFile( )) {
            file.delete( );
        } else {
            File[] files = file.listFiles( );
            if (files == null) {
                file.delete( );
            } else {
                for (int i = 0; i < files.length; i++) {
                    deleteDir(files[i].getAbsolutePath( ));
                }
                file.delete( );
            }
        }
    }

    public static boolean isMobileDevice(HttpServletRequest request) {
        String requestHeader = request.getHeader("user-agent");
        String[] deviceArray = new String[] {"android","mac os","windows phone"};
        if(requestHeader==null) {
            return false;
        }
        requestHeader = requestHeader.toLowerCase();
        for (String device:deviceArray) {
            if(requestHeader.indexOf(device)!=-1) {
                return true;
            }
        }
        return false;
    }

    public static boolean isWechatJSPI(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent").toLowerCase();
        if (ua.indexOf("micromessenger") > -1) {
            return true;//微信
        }
        return false;//非微信手机浏览器

    }
}
