package com.ruoyi.biemo.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hankcs.hanlp.corpus.document.sentence.Sentence;
import com.hankcs.hanlp.corpus.document.sentence.word.IWord;
import com.hankcs.hanlp.corpus.document.sentence.word.Word;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.NotionalTokenizer;
import com.ruoyi.biemo.business.domain.Category;
import com.ruoyi.biemo.business.domain.DocInfo;
import com.ruoyi.biemo.business.service.CategoryService;
import com.ruoyi.biemo.business.service.DocInfoService;
import com.ruoyi.biemo.core.page.Page;
import com.ruoyi.biemo.core.page.PageFactory;
import com.ruoyi.biemo.nlp.DependencyParserUtils;
import com.ruoyi.biemo.nlp.TextClassificationUtils;
import com.ruoyi.biemo.utils.MyObjects;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author makesoft
 * @version 1.0
 * @date 2021/1/14 11:19
 */
@RestController
@RequestMapping(value = "/makesoft/docInfo")
public class DocInfoController extends BaseController {

    @Autowired
    private DocInfoService docInfoService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询文章管理列表
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:list')")
    @GetMapping("/list")
    public Page<DocInfo> list(DocInfo docInfo)
    {
        Page<DocInfo> page =  docInfoService.selectDocInfoPage(docInfo,PageFactory.defaultPage());
        page.getRows().forEach(doc->{
            Category category = new Category();
            category = categoryService.selectCategoryById(doc.getCateId());
            if(category!=null&&category.getName()!=null){
                doc.setCateName(category.getName());
            }
        });
        return page;
    }

    /**
     * 导出文章管理列表
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:export')")
    @Log(title = "文章管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DocInfo docInfo)
    {
        List<DocInfo> list = docInfoService.selectDocInfoList(docInfo);
        ExcelUtil<DocInfo> util = new ExcelUtil<DocInfo>(DocInfo.class);
        util.exportExcel(response, list, "文章管理数据");
    }

    /**
     * 获取文章管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(docInfoService.selectDocInfoById(id));
    }

    /**
     * 获取文章管理详细信息 去掉内容标签
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:query')")
    @GetMapping(value = "/getInfoDelHtml/{id}")
    public AjaxResult getInfoDelHtml(@PathVariable("id") String docInfoId) throws IOException {
        DocInfo docInfo = docInfoService.selectDocInfoById(docInfoId);
        JSONObject result = new JSONObject();
        String content = docInfo.getContent();
        content = MyObjects.delHTMLTag(content);
        content = MyObjects.delSpace(content);
        JSONArray labels = new JSONArray();
        result.put("content",content);
        result.put("connections",new JSONArray());
        result.put("connectionCategories",MyObjects.connectionCategories);
        result.put("labelCategories",MyObjects.labelCategories);
        Sentence sentence = DependencyParserUtils.nerAnalysis(content);
        List<IWord> wordList = sentence.wordList;
        if(wordList!=null&&wordList.size()>0){
            int offset = 0;
            int id = 0;
            for(int i=0;i<wordList.size();i++){
                String value = wordList.get(i).getValue();
                String label = wordList.get(i).getLabel();
                if(MyObjects.wordsMapping.get(label)!=null){
                    Integer startIndex = offset;
                    Integer endIndex = offset+value.length();
                    Integer categoryId = MyObjects.wordsMapping.get(label);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",id);
                    jsonObject.put("categoryId",categoryId);
                    jsonObject.put("startIndex",startIndex);
                    jsonObject.put("endIndex",endIndex);
                    labels.add(jsonObject);
                }
                offset += value.length();
                id++;
            }
            result.put("labels",labels);
        }
        return AjaxResult.success("查询成功",result);
    }

    @PostMapping("/uploadPosTag")
    public AjaxResult uploadPosTag(@RequestBody JSONObject jsonObject) throws IOException {
        System.out.println(jsonObject);
        String content = jsonObject.getString("content");
        JSONArray labels = jsonObject.getJSONArray("labels");
        List<IWord> wordList = new ArrayList<>();
        if(labels!=null&&labels.size()>0){
            for(int i=0;i<labels.size();i++){
                Word word = new Word(null,null);
                JSONObject labelJSONObject = labels.getJSONObject(i);
                Integer startIndex = labelJSONObject.getInteger("startIndex");
                Integer endIndex = labelJSONObject.getInteger("endIndex");
                Integer categoryId = labelJSONObject.getInteger("categoryId");

                String value = content.substring(startIndex,endIndex);
                String label = MyObjects.wordsMappingIndex.get(categoryId);
                word.setLabel(label);
                word.setValue(value);
                wordList.add(word);
            }
            Sentence sentence = new Sentence(wordList);
            DependencyParserUtils.learn(sentence);
        }
        return  AjaxResult.success();
    }

    /**
     * 新增文章管理或修改文章
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:add')")
    @Log(title = "文章新增", businessType = BusinessType.INSERT)
    @RequestMapping
    public AjaxResult add(@RequestBody DocInfo docInfo)
    {
        docInfoService.insertOrUpdateDocInfo(docInfo);
        return AjaxResult.success();
    }

    /**
     * 删除文章管理
     */
    //@PreAuthorize("@ss.hasPermi('biemo:docInfo:remove')")
    @Log(title = "文章删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        docInfoService.deleteDocInfoByIds(ids);
        return AjaxResult.success();
    }

    @GetMapping("/analysis/{id}")
    public AjaxResult analysis(@PathVariable String id){
        return AjaxResult.success(docInfoService.analysis(id,false));
    }
    @GetMapping("/batchAnalysis/{ids}")
    public AjaxResult batchAnalysis(@PathVariable String[] ids){
        return AjaxResult.success(docInfoService.batchAnalysis(ids));
    }

    @GetMapping("/summary/{id}")
    public AjaxResult summary(@PathVariable String id){
        return AjaxResult.success(docInfoService.summary(id));
    }

    @GetMapping("/handleClassification/{id}")
    public AjaxResult handleClassification(@PathVariable String id){
        DocInfo docInfo = docInfoService.selectDocInfoById(id);
        JSONObject result = new JSONObject();
        String content = docInfo.getContent();
        content = MyObjects.delHTMLTag(content);
        content = MyObjects.delSpace(content);
        return AjaxResult.success("查询成功",TextClassificationUtils.getClassification(content));
    }

//    @PostMapping("/createEsIndex")
//    public void createEsIndex(){
//        DocInfo docInfo=new DocInfo();
//        docInfoService.insertEs(docInfo);
//    }

    @PostMapping ("/splitWord")
    public AjaxResult splitWord(@RequestBody DocInfo docInfo){
        List<String> strings = docInfoService.analyzeTitle(docInfo);
        docInfo.setAnalyzeTitle(strings);
        return AjaxResult.success("分词成功",docInfo);
    }

    //分词结果上传


}
