package com.ruoyi.biemo.nlp;

import com.hankcs.hanlp.classification.classifiers.IClassifier;
import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier;
import com.hankcs.hanlp.classification.models.NaiveBayesModel;
import com.hankcs.hanlp.corpus.io.IOUtil;
import com.ruoyi.biemo.utils.TestUtility;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 情感分析
 */
public class SentimentAnalysisUtils {
    public static final String CORPUS_FOLDER = TestUtility.ensureTest2Data("ChnSentiCorp", "http://hanlp.linrunsoft.com/release/corpus/ChnSentiCorp.zip");
//    public static final String MODEL_PATH = "D:\\code\\TextBigData\\data\\test\\sentiment-classification-model.ser";
    public static final String MODEL_PATH = "/usr/local/textjar/analysis-hanlp/data/test/sentiment-classification-model.ser";


    public static String analysis(String text){
        String result = "";
        try {
            IClassifier classifier = new NaiveBayesClassifier(trainOrLoadModel());
            result = classifier.classify(text);
        } catch (Exception ioException) {
            ioException.printStackTrace();
        }
        return result;
    }

    public static String analysis1(String text,IClassifier classifier){
        String result = "";
        try {
            result = classifier.classify(text);
        } catch (Exception ioException) {
            ioException.printStackTrace();
        }
        return result;
    }

    //训练模型
    public static NaiveBayesModel trainOrLoadModel() throws IOException
    {
        NaiveBayesModel model = (NaiveBayesModel) IOUtil.readObjectFrom(MODEL_PATH);
        if (model != null) return model;

        File corpusFolder = new File(CORPUS_FOLDER);
        if (!corpusFolder.exists() || !corpusFolder.isDirectory())
        {
            System.err.println("没有文本分类语料，请阅读IClassifier.train(java.lang.String)中定义的语料格式与语料下载：") ;
            System.exit(1);
        }

        IClassifier classifier = new NaiveBayesClassifier(); // 创建分类器，更高级的功能请参考IClassifier的接口定义
        classifier.train(CORPUS_FOLDER);                     // 训练后的模型支持持久化，下次就不必训练了
        model = (NaiveBayesModel) classifier.getModel();
        IOUtil.saveObjectTo(model, MODEL_PATH);
        return model;
    }

    public static Object analysisImport(MultipartFile[] files, String name) {
        if(files!=null&&files.length>0){
            File file1 = new File(CORPUS_FOLDER+"/"+name);
            if(!file1.getParentFile().exists()){
                file1.mkdirs();
            }
            if(!file1.exists()){
                file1.mkdirs();
            }
            for(int i=0;i<files.length;i++){
                MultipartFile file = files[i];
                try {
                   File file2 =  new File(file1.getCanonicalPath()+"/"+ file.getOriginalFilename());
                    file.transferTo(file2);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            IClassifier classifier = new NaiveBayesClassifier();
            try {
                classifier.train(CORPUS_FOLDER);
                NaiveBayesModel model = (NaiveBayesModel) classifier.getModel();
                IOUtil.saveObjectTo(model, MODEL_PATH);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        return "ok";
    }

    public static List<String> getCurrSentiments(){
        File file = new File(CORPUS_FOLDER);
        File[] dirs = file.listFiles();
        List<String> result = new ArrayList<>();
        if(dirs!=null&&dirs.length>0){
            for(int i=0;i<dirs.length;i++){
                if(dirs[i].isDirectory()){
                    result.add(dirs[i].getName());
                }
            }
        }
        return result;
    }

    public static void removeSentiments(String[] sentimentsArray) {
        if(sentimentsArray!=null&&sentimentsArray.length>0){
            File file = new File(CORPUS_FOLDER);
            for(int i=0;i<sentimentsArray.length;i++){
                File f = new File(file.getAbsolutePath()+"/"+sentimentsArray[i]);
                deleteFile(f);
            }
        }
    }

    public static void main(String[] args) {
        String[] arr = new String[]{"测试","中性"};
        removeSentiments(arr);
    }

    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
                System.out.println("文件名：" + f.getName());
            }
        }
        //文件夹删除
        file.delete();
        System.out.println("目录名：" + file.getName());
        return true;
    }
}
