import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.jutil.jdk.string.SnowFlake;
import cn.reghao.tnb.search.api.dto.IndexCount;
import cn.reghao.tnb.search.app.SearchApplication;
import cn.reghao.tnb.search.app.lucene.LuceneDocument;
import cn.reghao.tnb.search.app.lucene.LuceneIndex;
import cn.reghao.tnb.search.app.lucene.LuceneSearch;
import cn.reghao.tnb.search.app.model.po.Wenshu;
import cn.reghao.tnb.search.app.model.po.WenshuLucene;
import cn.reghao.tnb.search.app.model.vo.ElasticQuery;
import cn.reghao.tnb.search.app.service.WenshuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2025-03-18 15:51:21
 */
@Slf4j
@ActiveProfiles("dev")
@SpringBootTest(classes = SearchApplication.class)
public class WenshuTest {
    void setLogLevel() {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger rootLogger = loggerContext.getLogger("ROOT");
        rootLogger.setLevel(Level.INFO);
    }

    SnowFlake idGenerator = new SnowFlake(1, 1);
    private void addLuceneIndex(List<Wenshu> wenshuList) {
        long id = idGenerator.nextId();
        List<Document> luceneDocumentList = wenshuList.stream()
                .map(wenshu -> new WenshuLucene(""+id, wenshu))
                .map(wenshuLucene -> luceneDocument.getDocumentByWenshuLucene(wenshuLucene))
                .collect(Collectors.toList());

        List<Document> wenshuDocumentList = wenshuList.stream()
                .map(wenshu -> luceneDocument.getDocumentByWenshu(wenshu))
                .collect(Collectors.toList());

        String indexName = "wenshu";
        try {
            luceneIndex.createIndex(indexName, wenshuDocumentList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    LuceneIndex luceneIndex;
    @Autowired
    LuceneSearch luceneSearch;
    @Autowired
    LuceneDocument luceneDocument;
    @Autowired
    WenshuService wenshuService;

    public void walkDir(Path path) throws IOException {
        Files.walkFileTree(path, new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                File file1 = file.toFile();
                String filePath = file1.getAbsolutePath();
                if (filePath.endsWith("csv")) {
                    wenshuService.processFile(filePath);
                    log.info("index {} done...", filePath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    }

    @Test
    public void indexWenshuLucene() throws IOException {
        String indexName = "wenshu_lucene";
        String baseDir = "/home/reghao/disk/2/wenshu/";
        Path path = Paths.get(baseDir);
        walkDir(path);

        IndexCount indexCount = luceneIndex.countIndex(indexName);
        System.out.printf("max: %s, num: %s\n", indexCount.getMaxDocs(), indexCount.getNumDocs());
        wenshuService.printResult();
    }

    @Test
    public void deleteAllWenshuLucene() throws IOException {
        wenshuService.deleteAll();
    }

    @Test
    public void queryTest() {
        setLogLevel();

        String indexName = "wenshu_lucene";
        int pn = 1;
        int ps = 10;
        String queryString = "拐卖";
        ElasticQuery elasticQuery = new ElasticQuery.Builder()
                .pageSize(10)
                .pageNumber(1)
                .indexName(indexName)
                .queryFiledNames(List.of("caseName", "fullText"))
                .highlightFiledNames(List.of("caseName", "fullText"))
                .queryString(queryString)
                .build();

        PageList<WenshuLucene> pageList = luceneSearch.queryWithHighlight(elasticQuery, WenshuLucene.class);
        long total = pageList.getTotalSize();
        List<WenshuLucene> list = pageList.getList();
        WenshuLucene wenshu = list.get(0);
        String id = wenshu.getId();
        String caseName = wenshu.getCaseName();
        System.out.printf("%s -> %s\n", id, caseName);
    }
}
