package cn.sagacloud.server.algorithm.test;

import com.alibaba.fastjson.JSON;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaTest <T>{

    @Test
    public void testAdd() {
        double a = 0.05d;
        double b = 0.01d;
        System.out.println(0.05d+0.01d);
        System.out.println(a + b);
        System.out.println(1.0D-0.42D);
        System.out.println(4.015D*100D);
        System.out.println(123.3D/100D);
    }
    @Test
    public void testGeneric(){
        JavaTest<String> test = new JavaTest<>();
        System.out.println(test.getTClass());
    }
    public Class<T> getTClass()
    {
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }
    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    public static Class getSuperClassGenricType(Class clazz, int index)
            throws IndexOutOfBoundsException {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }

    @Test
    public void testTCPConn() throws IOException {
//        String ip="127.0.0.1";   //服务器端ip地址
//        String ip="192.168.20.225";   //服务器端ip地址
        String ip="47.94.18.1";   //服务器端ip地址
//        String ip="47.94.18.1";   //服务器端ip地址
        int port=6666;        //端口号
        Socket sck=new Socket(ip,port);
        //2.传输内容
//        String content="这是一个java模拟客户端";
//        byte[] bstream=content.getBytes("utf8");  //转化为字节流
//        OutputStream os= sck.getOutputStream();   //输出流
//        os.write(bstream);

        byte[] bstream = new byte[256];
        InputStream inputStream = sck.getInputStream();
        inputStream.read(bstream);
        System.out.println(new String(bstream));
        //3.关闭连接
        sck.close();
    }

    @Test
    public void testFastJSON() throws IOException {
        InputStream inputStream = JavaTest.class.getClassLoader().getResourceAsStream("data_check.xlsx");
        XSSFWorkbook workBook = new XSSFWorkbook(inputStream);
        String str = JSON.toJSONString(workBook);
        System.out.println(str);
    }

    @Test
    public void testRegex(){
        String line = "This order was placed for QT3000! OK?";
//        String pattern = "(\\D*)(\\d+)(.*)";
        String pattern = "(\\d+)";

        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(line);
        if (m.find( )) {
            System.out.println("groupCount : " + m.groupCount());
            for(int i = 0; i < m.groupCount(); ++i) {
                System.out.println("Found value: " + m.group(i));
//                System.out.println("Found value: " + m.group(1));
//            System.out.println("Found value: " + m.group(2) );
//            System.out.println("Found value: " + m.group(3) );
            }
        } else {
            System.out.println("NO MATCH");
        }
    }


    @Test
    public void testMyRegex(){
        ArrayList<String> arr = new ArrayList<String>(Arrays.asList("F1", "F22M", "F4M2", "B1", "B1M", "B3M24", "RF", "RFM", "RFM2", null));

        // ^([F|B][1-9][0-9]{0,4}|RF)(M([1-9][0-9]{0,4})?)?$
        String pattern = "(\\d+)((M)(\\d+))?";
        pattern = "^((([F|B])([1-9][0-9]{0,4}))|RF)((M)([1-9]{1,4})?)?$";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        arr.forEach(item ->{
            Matcher m = r.matcher(item);
            System.out.println();
            System.out.println("txt : " + item);
            if (m.find()) {
                System.out.println("groupCount : " + m.groupCount());
                for(int i = 0; i <= m.groupCount(); ++i) {
                    System.out.println("Found value: " + m.group(i));
                }
            } else {
                System.out.println("NO MATCH");
            }
        });
    }

    @Test
    public void testFor(){
        int min = 0, max = 100;
        for(int i = min; i <= max; ++i){

        }
    }



    @Test
    public void testHttp() throws IOException {
        String url = "http://47.93.33.207:28888/image-service/common/file_get?systemId=revit&key=export/008ad414673411eabc92c34d06c92241.zip";
        url = "http://47.93.33.207:28888/image-service/common/file_get?systemId=revit&key=export/008ad414673411eabc92c34d06c9224钉钉1.zip";
        int fileLength = getFileLength(url);
        System.out.println(fileLength);

    }

    /**
     * 获取网络文件大小
     * @param url1
     * @return
     * @throws IOException
     */
    private int getFileLength(String url1) throws IOException{
        int length=0;
        URL url;
        try {
            url = new URL(url1);
            HttpURLConnection   urlcon=(HttpURLConnection)url.openConnection();
            //根据响应获取文件大小
            length=urlcon.getContentLength();
            urlcon.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return length;
    }


    @Test
    public void testPinyin() throws IOException {
        String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray('单');
//        Hanyu hanyu = new Hanyu()
//        pinyinArray = PinyinHelper.("");

        for(int i = 0; i < pinyinArray.length; ++i) {

            System.out.println(pinyinArray[i]);

        }

    }


    @Test
    public void test207() {
        Map<String, String> myMap = new HashMap<>();
        String keyA = "A";
        String keyB = "B";
        String keyC = "C";
        String keyD = "D";
        String keyE = "E";
        String keyF = "F";
        String keyG = "G";
        String keyH = "H";
        myMap.put(keyA, "str01A");
        myMap.put(keyB, "str01B");
        myMap.put(keyC, "str01C");

        System.out.println("myMap initial content:"+ myMap);

        myMap.merge(keyA, "merge01", String::concat);
        myMap.merge(keyD, "merge01", String::concat);
        System.out.println("Map merge demo content:"+ myMap);

        BiFunction<String, String, String> biFunc = new BiFunction<String, String, String>(){
            @Override
            public String apply(String t, String u) {
                String result = t;
                if (t == null) {
                    result = u;
                }
                else {
                    result += "," + u;
                }
                return result;
            }
        };

        myMap.merge(keyA, "BiFuncMerge01", biFunc);
        myMap.merge(keyE, "BiFuncMerge01", biFunc);
        System.out.println("merge"+ myMap);

        String msg = "msgCompute";
        myMap.compute(keyB, (k, v) -> (v == null) ? msg : v.concat(msg));
        myMap.compute(keyF, (k, v) -> (v == null) ? msg : v.concat(msg));
        System.out.println("compute"+ myMap);

        myMap.computeIfAbsent(keyC, k -> genValue(k));
        myMap.computeIfAbsent(keyG, k -> genValue(k));
        System.out.println("computeIfAbsent"+ myMap);

        myMap.computeIfPresent(keyC, biFunc);
        myMap.computeIfPresent(keyH, biFunc);
        System.out.println("computeIfPresent"+ myMap);
        //ThreadPoolExecutor
    }

    static String genValue(String str) {
        System.out.println("===");
        return str + "2";
    }

    @Test
    public void testCubeRoot() {
        System.out.println(getCubeRoot(27));
        System.out.println(getCubeRoot(0));
        System.out.println(getCubeRoot(100));
        System.out.println(getCubeRoot(12));
    }

    public static double getCubeRoot(double input){
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(1);
        boolean is_negative = false;
        if(input < 0){
            is_negative = true;
            input = -input;
        }
        double left = 0;
        double right = input;
        double delta = 0.00001;
        double tmp = (left + right) / 2;
        double result = tmp * tmp * tmp;
        double last_min = 2d;
        double current = 0d;
        while (Math.abs(result - input) > last_min){
            if(Math.abs(result - input) < last_min){
                last_min = Math.abs(result - input);
            }
            if(result > input){
                right = tmp;
            }else{
                left = tmp;
            }
            tmp =  (left + right) / 2;
            String tmp1 =  df.format(tmp);
            result = tmp * tmp * tmp;

        }
        return tmp;
    }

}
