package com.bonus.hn.bearing.capacity.backstage.manager.utils;

import org.apache.commons.lang3.StringUtils;
import org.osgeo.proj4j.*;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author bonus
 */
public class StringHelper {

    private static String hexString = "0123456789ABCDEF";

    public static String replaceAll(String str, String oldStr, String newStr) {
        return str.replaceAll(oldStr, newStr);
    }

    public static boolean contains(String s1, String s2) {
        if (isEmpty(s1)) {
            return false;
        }
        return s1.contains(s2);

    }

    /**
     * 集合转数组
     *
     * @param list
     * @param separator
     * @return
     */
    public static String listToString(List<String> list, char separator) {
        return StringUtils.join(list.toArray(), separator);
    }

    public static String convertBlobToBase64String(Blob blob) {
        String result = "";
        if (null != blob) {
            try {
                InputStream msgContent = blob.getBinaryStream();
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[100];
                int n = 0;
                while (-1 != (n = msgContent.read(buffer))) {
                    output.write(buffer, 0, n);
                }
                result = new BASE64Encoder().encode(output.toByteArray());
                output.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } else {
            return null;
        }
    }

    public static void writeText(String args) {
        File fp = new File("F:\\1.txt");
        PrintWriter pfp;
        try {
            pfp = new PrintWriter(fp);
            pfp.print(args);
            pfp.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * blob中文乱码转码
     *
     * @param
     * @return
     */
    public static String blobToStrings(Blob b) {
        try {
            if (b == null) {
                return null;
            }
            String content = new String(b.getBytes((long) 1, (int) b.length()), "UTF-8");
            return content;
        } catch (SQLException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * blob中文乱码转码
     *
     * @param content
     * @return
     */
    public static String blobToString(String content) {
        try {
            return new String(content.getBytes("ISO_8859_1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
    }

    /**
     * unicode转字符串
     *
     * @param unicode
     * @return
     */
    public static String unicodeToString(String unicode) {
        StringBuffer sb = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int index = Integer.parseInt(hex[i], 16);
            sb.append((char) index);
        }
        return sb.toString();
    }

    /**
     *      * 含有unicode 的字符串转一般字符串      * @param unicodeStr 混有 Unicode 的字符串
     *      * @return      
     */
    public static String unicodeStr2String(String unicodeStr) {
        int length = unicodeStr.length();
        int count = 0;
        // 正则匹配条件，可匹配“\\u”1到4位，一般是4位可直接使用 String regex = "\\\\u[a-f0-9A-F]{4}";
        String regex = "\\\\u[a-f0-9A-F]{1,4}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(unicodeStr);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            // 原本的Unicode字符
            String oldChar = matcher.group();
            // 转换为普通字符
            String newChar = unicode2String(oldChar);
            // int index = unicodeStr.indexOf(oldChar);
            // 在遇见重复出现的unicode代码的时候会造成从源字符串获取非unicode编码字符的时候截取索引越界等
            int index = matcher.start();
            // 添加前面不是unicode的字符
            sb.append(unicodeStr.substring(count, index));
            // 添加转换后的字符
            sb.append(newChar);
            // 统计下标移动的位置
            count = index + oldChar.length();
        }
        // 添加末尾不是Unicode的字符
        sb.append(unicodeStr.substring(count, length));
        return sb.toString();
    }

    /**
     * unicode 转字符串
     *
     * @param unicode 全为 Unicode 的字符串
     * @return
     */
    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }

    /**
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
        // 将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
        return new String(baos.toByteArray());
    }

    public static String fillPrefixZero(int v, int len) {
        String vStr = v + "";
        while (vStr.length() < len) {
            vStr = "0" + vStr;
        }
        return vStr;
    }

    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim()) || "null".equals(str.trim())) {
            return true;
        }
        return false;
    }


    /**
     *
     * @param easting 东向坐标
     * @param northing 北向坐标
     * @return
     */
    public  static String coordinateTransform(double easting,double northing,String meridian){
        // 定义CGCS2000投影坐标系（3度带）
        String sourceCrsCode = "+proj=tmerc +lon_0="+meridian+" +k_0=1 +x_0=500000 +ellps=GRS80 +units=m +no_defs";
        CoordinateTransformFactory ctf = new CoordinateTransformFactory();
        CRSFactory crsFactory = new CRSFactory();
        CoordinateReferenceSystem sourceCrs = crsFactory.createFromParameters(null, sourceCrsCode);
        // WGS84 经纬度坐标系
        CoordinateReferenceSystem targetCrs = crsFactory.createFromName("EPSG:4326");
        CoordinateTransform transform = ctf.createTransform(sourceCrs, targetCrs);

        // 定义输入和输出点
        ProjCoordinate input = new ProjCoordinate(easting, northing);
        ProjCoordinate output = new ProjCoordinate();

        // 进行坐标转换
        transform.transform(input, output);

        // 输出转换后的经纬度
        System.out.println("经度：" + output.x + "，纬度：" + output.y);

        return output.x+","+output.y;
    }


    /**
     * 判断字符串 不为空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static void main(String[] args) {
        // 定义CGCS2000投影坐标系（3度带）
        String sourceCrsCode = "+proj=tmerc +lon_0=111 +k_0=1 +x_0=500000 +ellps=GRS80 +units=m +no_defs";

        // 定义CGCS2000坐标值
        // 东向坐标
        double easting = 3128034.63;
        // 北向坐标
        double northing = 449562.93;

        // 创建坐标转换器
        CoordinateTransformFactory ctf = new CoordinateTransformFactory();
        CRSFactory crsFactory = new CRSFactory();
        CoordinateReferenceSystem sourceCrs = crsFactory.createFromParameters(null, sourceCrsCode);
        // WGS84 经纬度坐标系
        CoordinateReferenceSystem targetCrs = crsFactory.createFromName("EPSG:4326");
        CoordinateTransform transform = ctf.createTransform(sourceCrs, targetCrs);

        // 定义输入和输出点
        ProjCoordinate input = new ProjCoordinate(easting, northing);
        ProjCoordinate output = new ProjCoordinate();

        // 进行坐标转换
        transform.transform(input, output);

        // 输出转换后的经纬度
        System.out.println("经度：" + output.x + "，纬度：" + output.y);
    }
    public static String  replaceSpace(String str) {
        return str.trim().replaceAll("\u00A0", "").replaceAll("\t","").replaceAll("\n","").replaceAll("\r","").replaceAll("\\s","");
    }
}
