package org.nl.config.lucene;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.nl.acs.AcsConfig;
import org.nl.acs.auto.run.AbstractAutoRunnable;
import org.nl.system.service.param.ISysParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Slf4j
@Component
public class LuceneServiceAutoRun extends AbstractAutoRunnable {
    @Autowired
    private ISysParamService paramService;

    public LuceneServiceAutoRun() {
    }

    @Override
    public String getCode() {
        return LuceneServiceAutoRun.class.getSimpleName();
    }

    @Override
    public String getName() {
        return "Lucene索引服务";
    }

    private static volatile IndexWriter indexWriter;

    @Override
    public void autoRun() throws IOException {
        try {
            String luceneUrl = paramService.findByCode(AcsConfig.LUCENEURL).getValue();
            Directory directory = FSDirectory.open(new File(luceneUrl).toPath());
            IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
            indexWriter = new IndexWriter(directory, config);
        } catch (Exception e) {
            log.error("Lucene索引服务出现异常:{}", JSON.toJSONString(e));
            if (ObjectUtil.isNotEmpty(indexWriter)) {
                indexWriter.close();
            }
        }
    }
    /**在线程结束时，会自动关闭IndexWriter*/
    public static IndexWriter getIndexWriter() {
        return indexWriter;
    }

    @Override
    public void stop() {
        super.after();
        try {
            indexWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        indexWriter.deleteAll();
    }

    public static String getDate(String timeString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
        Date date = sdf.parse(timeString);
        timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
        return timeString;
    }

}
