package com.cf.imes.module.executor.service.zlib;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.compression.JdkZlibDecoder;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.compression.ZlibDecoder;
import com.cf.imes.module.executor.util.CompressTest;
import com.cf.imes.module.executor.util.ZLibUtils;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.util.*;
import java.util.zip.Inflater;

public class ZlibTest {

    private JdbcTemplate jdbcTemplate;

    @BeforeEach
    public void init() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://192.168.1.245:3306/cferp_test_1");
        druidDataSource.setUsername("mes_visitor");
        druidDataSource.setPassword("cf123456");
        //创建jdbc模板对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(druidDataSource);
        this.jdbcTemplate = jdbcTemplate;
    }

    @Test
    void getOrderBoxBlock() throws IOException {
        List<OrderBoxBlock> list = jdbcTemplate.query("select * from order_box_block limit 10", new BeanPropertyRowMapper<OrderBoxBlock>(OrderBoxBlock.class));
        for (OrderBoxBlock bean : list) {
            if (!Objects.isNull(bean.Data)) {
                byte[] bytes = Arrays.copyOfRange(bean.Data, 2, bean.Data.length - 1);
                System.out.println( new String(bean.Data));
                System.out.println( CompressTest.uncompress(new String(bytes)));
                //System.out.println(new String(ZLibUtils.decompress(bean.Data)));
                System.err.println("------------------------------------------");
            }
        }
    }

    @Test
    void getOrderBlockPlanResult() throws UnsupportedEncodingException {
        List<OrderBlockPlanResult> list = jdbcTemplate.query("select * from order_block_plan_result limit 1", new BeanPropertyRowMapper<OrderBlockPlanResult>(OrderBlockPlanResult.class));
        for (OrderBlockPlanResult bean : list) {
            if (!Objects.isNull(bean.PlaceData)) {
                System.out.println(new String(ZLibUtils.decompress(bean.PlaceData)));
                System.err.println("------------------------------------------");
            }
        }
    }

    @Test
    void test() {
        String source = "xxxxxxxxxxaassad";
        //压缩
        byte[] compress = ZLibUtils.compress(source.getBytes());
        String str = new String(compress);
        System.out.println(str);
        //解压
        System.out.println(new String(ZLibUtils.decompress(new ByteArrayInputStream(compress))));


    }

    public void insertByteArray(String tableName, byte[] data, String columnName) {
        final String sql = "INSERT INTO " + tableName + " (" + columnName + ") VALUES (?)";
        jdbcTemplate.update(
                conn -> {
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length);
                    return ps;
                }
        );
    }


    public static String uncompress(byte[] input) throws IOException {
        Inflater inflater = new Inflater();
        inflater.setInput(input);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
        try {
            byte[] buff = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buff);
                baos.write(buff, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.close();
        }
        inflater.end();
        byte[] output = baos.toByteArray();
        return new String(output, "UTF-8");
    }


    @Data
    public static class OrderBoxBlock {
        long BoxID;
        long ShardKey;
        long OrderNo;
        byte[] Data;
        long CompanyID;
    }

    @Data
    public static class OrderBlockPlanResult {
        long ID;
        LocalDateTime SaveTime;
        byte[] PlaceData;
        long CompanyID;
    }

    @Test
    void getRes() throws IOException {
        //创建url路径
        String url = "https://chenfeng.tech:777/api/v1/OrderBlockPlan/GetPlanOrderData";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        //接口参数
        map.add("id",1306667105);
        //头部类型
        headers.set("Cookie", ".AspNetCore.Cookies=CfDJ8CGzP7BhamtAnTFO8HhkPcxGBkdd4sCOIjQMV-nb37GAFKr4y6C0JA0B3JzRsDAckabiUgBXQaWyDNjCqVTvBNYwbHwVbI5b-eKdXwkIFqsJZObZA-RoLdsu1d9yy1LwBLQwJxDGKTSQzFtrs_eHDeDEuG8CWEF1Iq96X0goR_cFMn0EHWVeRnOlThmDzLkmTMhysVSludR6qV0HrD54GOv5MQvBzzcE-WlsrKTo5Uf0hT8z1fGMY8Hofa6UDh8yyJsz2LFTQTy4NpmklvyXIkwv0fw9bOynHLllUh5ToF0wgrxYFU3Rzgf863uAdtfRP1DY2Rqvf-51uvQHip-SIT_b5p7TaSRiG-M7pZTlI0oOVPZRhng7k-NeIJRdYQmj0h3G3WJHCTH7g1-YQjAGbYQkJFcZdAsZpR-kjOlp3sHpNCDUe0NucYrLNp4tTXesCL_-t8X5GsXMYGlX-oKU10I");
        //构造实体对象
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
        //发起请求,服务地址，请求参数，返回消息体的数据类型
        ResponseEntity<Resource> response = restTemplate.postForEntity(url, param, Resource.class);
        //body
        InputStream inputStream = response.getBody().getInputStream();
        BufferedOutputStream out = FileUtil.getOutputStream("C:\\Users\\Beal\\Desktop\\新建文件夹\\xx.txt");
        long copySize = IoUtil.copy(inputStream, out, IoUtil.DEFAULT_BUFFER_SIZE);
        IoUtil.close(inputStream);
        IoUtil.close(out);


    }
}
