package com.search.supersearch;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.search.supersearch.config.OSSConfig;
import com.search.supersearch.model.pojo.DocsIndex;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.microsoft.OfficeParser;
import org.apache.tika.sax.BodyContentHandler;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;

/**
 * 测试 elasticSearch client 索引相关的操作
 *
 * @author WT
 * @date 2021/12/28 16:27:45
 */
@Slf4j
@SpringBootTest
@ActiveProfiles("wr") //这里
public class OSSTest {

    @Resource
    OSSConfig ossConfig;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
//    @Value("${spring.profiles.active}")
//    String string;

    @Test
    @SneakyThrows
    public void run13() {
        String path = "/Users/wangrui/Desktop/IDP/归档.zip";
        File file = new File(path);
        if (isCompressedFile(file.getName())) {
//            File unzip = ZipUtil.unzip(file.getPath(), "./zip_tmp"+ IdUtil.fastSimpleUUID());
            File unzip = ZipUtil.unzip(file.getPath(), CharsetUtil.CHARSET_GBK);
            func(unzip);
            if (unzip.exists()) {
                cn.hutool.core.io.FileUtil.del(unzip);
            }
        }
//        System.out.println(string);
    }

    private void func(File file) throws Exception {
        File[] fs = file.listFiles();
        for (File f : fs) {
            if (f.isDirectory())    //若是目录，则递归打印该目录下的文件
            {
                func(f);
            }
            if (f.isFile())        //若是文件，直接打印
            {
                System.out.println(f.getName());
            }
        }
    }

    private boolean isCompressedFile(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
        return extension.equalsIgnoreCase("zip") ||
                extension.equalsIgnoreCase("rar") ||
                extension.equalsIgnoreCase("7z");
    }

    @Test
    @SneakyThrows
    public void run12() {
//        String path = "/Users/wangrui/Desktop/ossFiledownload/ff8081818b65f6a9018b65f834300000.pdf";
//        String path = "/Users/wangrui/Downloads/2021年04月【国家电投集团河南电力有限公司平顶山发电分公司】中国中标统计分析.pdf";
        String path = "/Users/wangrui/Desktop/【正文】山东鲁盈公司关于2023年度财务决算备案的报告.pdf";
        File file = new File(path);
        Tika tika = new Tika();
        Metadata metadata = new Metadata();
        tika.setMaxStringLength(-1);
        String detect = tika.detect(file);

        Parser parser = new AutoDetectParser();

        BodyContentHandler handler = new BodyContentHandler(-1);
        FileInputStream inputstream = null;
        try {
            inputstream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ParseContext context = new ParseContext();

        parser.parse(inputstream, handler, metadata, context);
        System.out.println(handler);
    }

    @Test
    @SneakyThrows
    public void run11() {
//        System.out.println(string);
    }

    @Test
    @SneakyThrows
    public void run10() {
        String path = "/Users/wangrui/Downloads/";
        Tika tika = new Tika();
        System.out.println(tika.detect(new File(path + "WechatIMG10.png")));
        System.out.println(tika.detect(new File(path + "副本_手绘风可爱抖音个人背景图__2023-09-07+18_22_51.jpeg")));
        System.out.println(tika.detect(new File(path + "43145422_团购收支明细_20230801~20230821_16926285100491730284573338.xlsx")));
        System.out.println(tika.detect(new File(path + "2021年04月【国家电投集团河南电力有限公司平顶山发电分公司】中国中标统计分析.pdf")));
    }

    @Test
    @SneakyThrows
    public void run9() {

        File file = new File("/Users/wangrui/Downloads/国家现行规范国家标准目录.doc");

        Parser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        FileInputStream inputstream = null;
        try {
            inputstream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ParseContext context = new ParseContext();

        parser.parse(inputstream, handler, metadata, context);

        System.out.println(handler);

        //getting the list of all meta data elements
        String[] metadataNames = metadata.names();

        for (String name : metadataNames) {
            System.out.println(name + ": " + metadata.get(name));
        }
    }

    @Test
    @SneakyThrows
    public void run8() {
        BodyContentHandler handler = new BodyContentHandler(-1);
        File file = new File("/Users/wangrui/Downloads/国家现行规范国家标准目录.doc");
        InputStream stream = FileUtil.getInputStream("/Users/wangrui/Downloads/国家现行规范国家标准目录.doc");
        AutoDetectParser parser = new AutoDetectParser();
        Metadata metadata = new Metadata();
        try {
            parser.parse(stream, handler, metadata);

            System.out.println(handler);
        } finally {
            stream.close();
        }
    }

    @Test
    @SneakyThrows
    public void run7() {
        Tika tika = new Tika();
        tika.setMaxStringLength(-1);
        String s = tika.parseToString(new File("/Users/wangrui/Downloads/国家现行规范国家标准目录.doc"));
        System.out.println(s);
    }

    @Test
    @SneakyThrows
    public void run6() {

        saveFile(new URL("https://platomixtest.oss-cn-beijing.aliyuncs.com/platomixtest/240138972d0c4e2aaa5fb25d7f22de09.docx?Expires=1696752246&OSSAccessKeyId=LTAI5tPoP9JgGLLDorkfyWEd&Signature=AemlnBmrER3C8J04zU9YFCF2W3I%3D"));
    }

    @Test
    @SneakyThrows
    public void run5() {

        Tika tika = new Tika();
        String s = tika.parseToString(new File("/Users/wangrui/Downloads/2020国家电投春招,待遇怎么样？.docx"));
        Metadata metadata = new Metadata();
        Reader parse = tika.parse(new File("/Users/wangrui/Downloads/2020国家电投春招,待遇怎么样？.docx"), metadata);
        String s1 = metadata.get("resourceName");
        System.out.println(s1);
        System.out.println(JSONUtil.toJsonStr(metadata));
        String detect = tika.detect(new File("/Users/wangrui/Downloads/2020国家电投春招,待遇怎么样？.docx"));
        System.out.println(detect);
        System.out.println("=================");
        for (String name : metadata.names()) {

            System.out.println(name + ": " + metadata.get(name));
        }
//        System.out.println(s);
    }

    @Test
    @SneakyThrows
    public void run4() {
        Tika tika = new Tika();
        File file = new File("/Users/wangrui/Downloads/WechatIMG10.png");
//        String s = tika.parseToString();
        OfficeParser parser = new OfficeParser();

        // 创建 BodyContentHandler 对象
        BodyContentHandler handler = new BodyContentHandler();

        // 创建 Metadata 对象
        Metadata metadata = new Metadata();

        // 创建 ParseContext 对象
        ParseContext context = new ParseContext();

        // 使用 OfficeParser 解析文件
        InputStream stream = new FileInputStream(file);
        parser.parse(stream, handler, metadata, context);

        // 输出文件内容
        System.out.println(handler);
    }

    @Test
    @SneakyThrows
    public void run3() {
        String bucketName = "platomixtest";
        String objectName = "platomixtest/platomixtest.txt";
        OSS oss = ossConfig.restOSSClient();
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = oss.getObject(bucketName, objectName);
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();
        if (content != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println("\n" + line);
            }
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            content.close();
        }
        oss.shutdown();
    }

    @Test
    public void run2() throws Exception {
        String bucketName = "platomixtest";
        OSS oss = ossConfig.restOSSClient();
        ObjectListing objectListing = oss.listObjects(bucketName);
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + ")");
        }
        oss.shutdown();
    }

    @Test
    public void run() throws Exception {
        // RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = "LTAI5tPoP9JgGLLDorkfyWEd";
        String accessKeySecret = "wRYrd8XK6gDMldbVc3KImiNQLwqear";
        String bucketName = "platomixtest";
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";

// 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
        ObjectListing objectListing = ossClient.listObjects(bucketName);
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + ")");
        }
// 关闭OSSClient。
        ossClient.shutdown();
    }

    private String saveFile(URL url) throws IOException, TikaException {
        Tika tika = new Tika();
        Metadata metadata = new Metadata();
        InputStream stream = TikaInputStream.get(url, metadata);
//        Reader parse = tika.parse(stream,metadata);

        String s = tika.parseToString(url);
        DocsIndex docsIndex = new DocsIndex();

        elasticsearchClient.index(i -> i.index("test_docs4").document(docsIndex));
        return s;
    }
}
