package org.jeecg.modules.stm.essearch.stlib.controller;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.stm.common.service.IStCommonService;
import org.jeecg.modules.stm.doc.entity.DocFiles;
import org.jeecg.modules.stm.doc.service.IDocFilesService;
import org.jeecg.modules.stm.stlib.pojo.EsQueryFileVo;
import org.jeecg.modules.stm.stlib.pojo.EsQueryVo;
import org.jeecg.modules.stm.stlib.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import org.jeecg.common.es.JeecgElasticsearchTemplate;

import org.jeecg.modules.stm.stlib.constant.StLibbIndexs;

import jakarta.servlet.http.HttpServletRequest;

import org.jeecg.modules.stm.utils.ParseDocUtil;

@RestController
@RequestMapping("/stm/es/file")
public class SearchFileContentController {

    @Autowired
    private JeecgElasticsearchTemplate esTpl;
    @Autowired
    private IStCommonService iStCommonService;
    @Autowired
    private IDocFilesService docFilesService;

    @Value("${jeecg.path.upload}")
    private String uploadPath;

    @GetMapping(value = "/list")
    public Result<PageResult> searchPageList(EsQueryVo params,
                                             @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                             HttpServletRequest req) {

        int from = (pageNo-1)*pageSize;
        String name = params.getName();
        JSONArray objAryMust = new JSONArray();
        JSONArray objAryFilter = new JSONArray();
        JSONObject highlightObj = getJSONHighlight();

        if(!StringUtils.isEmpty(name)){
            JSONObject objMatch = new JSONObject();
            JSONObject objMatchName = new JSONObject();
            objMatchName.put("all", name);
            objMatch.put("match", objMatchName);
            objAryMust.add(objMatch);
        }
        if(!StringUtils.isEmpty(params.getSctype())){
            JSONObject objTerm = new JSONObject();
            JSONObject objType = new JSONObject();
            objType.put("sctype", params.getSctype());
            objTerm.put("term", objType);
            objAryFilter.add(objTerm);
        }

        JSONObject objBool = new JSONObject();
        objBool.put("must",objAryMust);
        objBool.put("filter",objAryFilter);
        JSONObject objQuery = new JSONObject();
        objQuery.put("bool",objBool);
        JSONArray orderJSONObject = null;//getJSONOrder();

        JSONObject buildQuery = esTpl.buildQuery(null, objQuery, from, pageSize,highlightObj,orderJSONObject);

        JSONObject ret = null;
        try {
            ret = esTpl.search(StLibbIndexs.index_file_name, buildQuery);
        } catch (Exception e){
            boolean isExist = esTpl.indexExists(StLibbIndexs.index_file_name);
            if(!isExist){
                EsQueryFileVo queryVo = new EsQueryFileVo();
                createDocLib(queryVo);
                ret = esTpl.search(StLibbIndexs.index_file_name, buildQuery);
            }
        }

        JSONObject retObj = ret.getJSONObject("hits");
        PageResult pageResult = null;
        if (retObj != null) {
            JSONObject totalObj  = retObj.getJSONObject("total");
            int total = totalObj.getInteger("value");
            JSONArray list = retObj.getJSONArray("hits");
            List<EsQueryFileVo> retList = new ArrayList<>();
            for(int i=0;i<list.size();i++) {
                JSONObject ojb = list.getJSONObject(i).getJSONObject("_source");
                JSONObject ojbHighlight = list.getJSONObject(i).getJSONObject("highlight");
                EsQueryFileVo queryVo = new EsQueryFileVo();
                String rname = ojb.getString("name");
                String fpath = ojb.getString("fpath");
                String fpathHight = null;
                if(ojbHighlight!=null) {
                    if (ojbHighlight.getJSONArray("name")!= null) {
                        rname = ojbHighlight.getJSONArray("name").get(0).toString();
                    }
                    if (ojbHighlight.getJSONArray("fpath")!= null) {
                        fpathHight = ojbHighlight.getJSONArray("fpath").get(0).toString();
                        int p = fpathHight.indexOf("/");
                        fpathHight = fpathHight.substring(p+1);

                    }
                    queryVo.setAllHilight(ojbHighlight.getJSONArray("contents.content"));
                }

                if(fpathHight==null||fpathHight.equals("")) {
                    if(fpath!=null&&fpath.trim().length()>0) {
                        int p = fpath.indexOf("/");
                        fpathHight = fpath.substring(p + 1);
                    }
                }
                queryVo.setName(rname);
                queryVo.setFpath(fpath);
                queryVo.setSctype(ojb.getString("sctype"));
                queryVo.setDocNo(ojb.getString("docNo"));
                queryVo.setBizNo(ojb.getString("bizNo"));
                queryVo.setFpathHight(fpathHight);
                retList.add(queryVo);
            }
            pageResult = new PageResult(total, retList);
            return Result.OK(pageResult);
        } else {
            return Result.OK("未查询到数据");
        }

    }

    @PostMapping("/createDocLib")
//   @RequiresPermissions("stm:es:file:createDocLib")
    public Result<String>  createDocLib(EsQueryFileVo queryVo) {
        List<DocFiles> listFile = docFilesService.list();
        try {
            if(listFile!=null&&listFile.size()>0) {
                createIndex();
                List<EsQueryFileVo> list = docFile2EsQueryFileVo(listFile);
                esTpl.deleteAll(StLibbIndexs.index_file_name);
                esTpl.curDataIndex=1;
                JSONArray ary = new JSONArray();
                for(int i=0;i<list.size();i++){
                    EsQueryFileVo esQueryFileVo = list.get(i);
                    String path = esQueryFileVo.getFpath();
                    List<Map<String,String>> conetntList = new ArrayList<Map<String,String>>();
                    String strFileContent = "";
                    String tmppath = uploadPath + "/" + path;
                    int scType = Integer.parseInt(esQueryFileVo.getSctype());
                    if(tmppath.endsWith(".docx")||tmppath.endsWith(".doc")){
                        List<Map<String, String>> retList = new ArrayList<>();
                        if(scType==1||scType==2) {
                            List<String[]> listDdata = null;
                            if (tmppath.endsWith(".docx")) {
                                listDdata = ParseDocUtil.docxParser(tmppath);
                            } else {
                                listDdata = ParseDocUtil.docParser(tmppath);
                            }
                            if(listDdata == null) continue;
                            for (int j = 0; j < listDdata.size(); j++) {
                                String[] tmpAry = listDdata.get(j);
                                Map<String, String> tmpMap = new HashMap<>();
                                StringBuffer sb = new StringBuffer();
                                if (tmpAry[1] == null || tmpAry[1].isEmpty()) {
                                    continue;
                                }
                                int p = tmpAry[1].indexOf("条");
                                sb.append("<b>").append(tmpAry[0]).append("</b>").append("<br/>");
                                if (p > 0) {
                                    sb.append("<b>").append(tmpAry[1].substring(0, p + 1)).append("</b>").append("&nbsp;").append(tmpAry[1].substring(p + 1));
                                } else {
                                    sb.append(tmpAry[1]);
                                }
                                sb.append(" ");
                                if (tmpAry[2] != null && !tmpAry[2].isEmpty()) {
                                    sb.append("<br/>").append(tmpAry[2]);
                                }

                                tmpMap.put("content", sb.toString());
                                retList.add(tmpMap);
                            }
                        } else {
                            if (tmppath.endsWith(".docx")) {
                                retList = ParseDocUtil.docxParserList(tmppath);
                                //retList= ParseDocUtil.splitText(strFileContent);
                            } else {
                                retList = ParseDocUtil.docParserList(tmppath);
                            }
                        }
                        esQueryFileVo.setContents(retList);

                    } else if(tmppath.endsWith(".pdf")) {
                        String strText = ParseDocUtil.pdfParserText(tmppath);
                        if(strText==null) continue;
                        int k = ParseDocUtil.getFileContentTp(strText);
                        if(k==1) {
                            List<String[]> listAry = ParseDocUtil.pdfParserToList(tmppath);
                            if(listAry!=null) {
                                List<String> tmpList = new ArrayList<String>();
                                for(int m=0;m<listAry.size();m++) {
                                    String[] aryTmp = listAry.get(m);
                                    StringBuffer sbTmp= new StringBuffer();
                                    sbTmp.append(aryTmp[0]).append("<br/>").append(aryTmp[1]);
                                    tmpList.add(sbTmp.toString());
                                }
                                List<Map<String, String>>  listNew =  ParseDocUtil.listToListMap("content",tmpList);
                                esQueryFileVo.setContents(listNew);
                            }
                        } else if(k==2) {
                            List<String> listStr = ParseDocUtil.handleText(strText);
                            List<Map<String, String>>  listTmp =  ParseDocUtil.listToListMap("content",listStr);
                            if(listTmp!=null) {
                                esQueryFileVo.setContents(listTmp);
                            }
                        } else {
                            List<Map<String, String>>  listTmp =  ParseDocUtil.splitText(strText);
                            if(listTmp!=null) {
                                esQueryFileVo.setContents(listTmp);
                            }
                        }
                    }
                    ary.add(esQueryFileVo);
                    esTpl.saveBatch(StLibbIndexs.index_file_name, ary);
                }
                return Result.OK("数据创建成功");
            } else {
                return Result.OK("未查到数据库总的数据");
            }

        } catch (Exception e) {
           e.printStackTrace();
            return Result.OK("数据创建失败");
        }
    }


    @PostMapping("/createIndex")
    public Result<String> createIndex(){
        try {
            if (esTpl.indexExists(StLibbIndexs.index_file_name)) {
                esTpl.deleteAll(StLibbIndexs.index_file_name);
                esTpl.removeIndex(StLibbIndexs.index_file_name);
            }
            JSONObject obj = JSONObject.parseObject(StLibbIndexs.zrch_risk_filedoc);
            esTpl.createIndex(StLibbIndexs.index_file_name,obj);
            esTpl.setIndexReplicasToZero(StLibbIndexs.index_file_name);
            esTpl.disableIndexTemplateILM(StLibbIndexs.index_file_name);
            return Result.OK("索引创建成功");
        } catch (Exception e) {
            //e.printStackTrace();
            return Result.error("索引创建失败");
        }
    }


    private JSONObject getJSONHighlight() {
        JSONObject obj = JSONObject.parseObject(StLibbIndexs.mapping_file_highlight);
        return obj;
    }

    private JSONArray getJSONOrder() {
        JSONArray obj = JSONArray.parseArray(StLibbIndexs.mapping_common_query_sort);
        return obj;
    }

    private List<EsQueryFileVo> docFile2EsQueryFileVo(List<DocFiles> files) {
        List<EsQueryFileVo> esList = new ArrayList<>();
        for(DocFiles file: files) {
            EsQueryFileVo esVo = new EsQueryFileVo();
            esVo.setId(file.getId());
            esVo.setName(file.getFileName());
            esVo.setIssued(file.getIssued());
            esVo.setIssuedTime(file.getIssuedDate());
            esVo.setIssued(file.getIssued());
            esVo.setDes(file.getDes());
            esVo.setFpath(file.getFilePath());
            if(file.getStp()==null){
                esVo.setSctype("");
            } else {
                esVo.setSctype(file.getStp().toString());
            }

            esList.add(esVo);
        }
        return esList;
    }


}

