package com.trs.digital.module.manager.controller.admin.search.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trs.digital.framework.common.exception.ServiceException;
import com.trs.digital.framework.common.pojo.PageResult;
import com.trs.digital.framework.common.util.object.BeanUtils;
import com.trs.digital.framework.security.core.LoginUser;
import com.trs.digital.module.manager.configure.HybaseFactory;
import com.trs.digital.module.manager.controller.admin.errorwold.vo.ErrorwoldSaveReqVO;
import com.trs.digital.module.manager.controller.admin.search.vo.AdvSearchReqVO;
import com.trs.digital.module.manager.controller.admin.search.vo.AdvSearchSaveLabelsReqVO;
import com.trs.digital.module.manager.controller.admin.search.vo.AdvSearchSaveLabelsReqVO2;
import com.trs.digital.module.manager.dal.dataobject.digsearch.DigSearchLogDO;
import com.trs.digital.module.manager.dal.dataobject.digsearch.DigVisitLogDO;
import com.trs.digital.module.manager.dal.dataobject.digsearch.TableFieldDO;
import com.trs.digital.module.manager.dal.dataobject.errorwold.ErrorwoldDO;
import com.trs.digital.module.manager.dal.mysql.digftp.DigFtpSourceMapper;
import com.trs.digital.module.manager.dal.mysql.digftp02.digftpsource02Mapper;
import com.trs.digital.module.manager.dal.mysql.digsearch.DigSearchLogMapper;
import com.trs.digital.module.manager.dal.mysql.digsearch.DigVisitLogMapper;
import com.trs.digital.module.manager.dal.mysql.errorwold.ErrorwoldMapper;
import com.trs.digital.module.manager.dal.mysql.oracle.OracleResourceMapper;
import com.trs.digital.module.manager.service.errorwold.ErrorwoldService;
import com.trs.digital.module.system.controller.admin.oauth2.vo.user.OAuth2UserInfoRespVO;
import com.trs.digital.module.system.dal.dataobject.dept.DeptDO;
import com.trs.digital.module.system.dal.dataobject.user.AdminUserDO;
import com.trs.digital.module.system.dal.mysql.dept.DeptMapper;
import com.trs.digital.module.system.dal.mysql.user.AdminUserMapper;
import com.trs.digital.module.system.service.dept.DeptService;
import com.trs.digital.module.system.service.user.AdminUserService;
import com.trs.hybase.client.TRSConnection;
import com.trs.hybase.client.TRSResultSet;
import com.trs.hybase.client.params.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.trs.digital.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Service
@Slf4j
public class SearchService {

    @Autowired
    HyBaseService hyBaseService;

    @Autowired
    DigVisitLogMapper digVisitLogMapper;
    @Autowired
    DigSearchLogMapper digSearchLogMapper;

    @Autowired
    DigFtpSourceMapper digFtpSourceMapper;
    @Autowired
    digftpsource02Mapper digftpsource02Mapper;
    @Autowired
    OracleResourceMapper oracleResourceMapper;

    @Autowired
    AdminUserMapper adminUserMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private AdminUserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ErrorwoldService errorwoldService;
    @Autowired
    private ErrorwoldMapper errorwoldMapper;

    public PageResult select(AdvSearchReqVO reqVO) {


        if (reqVO.getMetaId() !=null && reqVO.getMetaId() == 2) {
            Map<String, String[]> navigation = reqVO.getNavigation();
            // 如果 navigation 为空，初始化为默认值
            if (navigation == null) {
                navigation = new HashMap<>();
                navigation.put("sourcename", new String[]{"ftp", "oracle"});
                reqVO.setNavigation(navigation);
            }
            // 获取 sourcename 字段并进行处理
            String[] sourcename = navigation.get("sourcename");
            if (sourcename != null) {
                List<String> list = new ArrayList<>(Arrays.asList(sourcename));
                list.remove("ftp2");  // 移除 "ftp2"

                // 更新 sourcename 字段，如果 list 为空则恢复默认值
                navigation.put("sourcename", list.isEmpty() ? new String[]{"ftp", "oracle"} : list.toArray(new String[0]));
            } else {
                // 如果没有 "sourcename" 字段，则设置默认值
                navigation.put("sourcename", new String[]{"ftp", "oracle"});
            }
        }


        SearchParams searchParams = new SearchParams();
        if(reqVO.getSort()!=null){
            String sort = buildSort(reqVO.getSort());
            searchParams.setSortMethod(sort);
        }

        if(reqVO.getIsAip()!=null && reqVO.getIsAip() == 1){
            searchParams.setProperty("hybase.search.nosort", "true");
        }

        searchParams.setProperty("search.synonym.extend", "term");
//        searchParams.setColorColumns("file_name,doc_title,doc_content,doc_abstract,doc_keywords,doc_content_translate");
        searchParams.setColorColumns("doc_title,doc_content,doc_abstract,doc_keywords,doc_content_translate");
//        searchParams.setColorColumns("doc_content");
//        searchParams.setColorColumns("doc_abstract");
        if(reqVO.getType()!=null&&reqVO.getType()==3){
            searchParams.setReadColumns("doc_title");
        }else{
            DigSearchLogDO searchLogDO = new DigSearchLogDO();
            digSearchLogMapper.insert(searchLogDO);
        }
        //搜索词纠错
        QueryWrapper<ErrorwoldDO> queryWrapper = new QueryWrapper<ErrorwoldDO>();
        queryWrapper.eq("error_word", reqVO.getKeyword());
        List<ErrorwoldDO> errorwoldDOS = errorwoldMapper.selectList(queryWrapper);
       String trueWord = "";
        String errorWord = reqVO.getKeyword();
        if(errorwoldDOS.size()>0){
            for (ErrorwoldDO errorwoldDO : errorwoldDOS){
                trueWord = errorwoldDO.getTrueWord();
            }
            if(reqVO.getIsuse()!=null&&reqVO.getIsuse()==1){
                reqVO.setKeyword(errorWord);
            }else {
                reqVO.setKeyword(trueWord);
            }

        }

        List<TableFieldDO> searchList = getFieldDOList(reqVO.getType());
        String condition = condition(reqVO, searchList);
        if(reqVO.getCheckstatus()!=null && reqVO.getCheckstatus()==0){
            condition+= " AND check_status:0 ";
        }

        String condition_temp = condition;
        AdminUserDO user = userService.getUser(getLoginUserId());
        String username = "";
        if(user!=null){
            username = user.getUsername();
        }
        if(reqVO.getMetaId()==3){
            condition+= " AND ("+condition_temp+" AND (username:"+username+"))";
        }else{
            if(StringUtils.isNotBlank(username)){
                condition = "("+condition+" NOT (sourcename#LIST:user))";
                condition+= " OR ("+condition_temp+" AND (username:"+username+"))";
            }
        }

        log.info(String.format("where：%s", condition));
//        log.info(String.format("sort：%s", sort));
        String tablename = "";
        if(reqVO.getMetaId()==1){
            tablename = "system.dig_ftp;system.dig_ftp02;system.dig_oracle;system.dig_user";
        }else if(reqVO.getMetaId()==3){
            tablename = "system.dig_user";
        }else{
            tablename = "system.dig_ftp;system.dig_oracle;system.dig_user";
        }
        JSONObject categoryresult = hyBaseService.categoryQuery(tablename, condition, "people_lable","people_lable;org_lable;area_lable",5, searchParams);
        PageResult<Map<String, Object>> result = hyBaseService.select(tablename, condition, Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), searchParams);
        //lightHigh(reqVO, result.getList(), searchList);
        result.setPageNo(reqVO.getPageNo());
        result.setPageSize(reqVO.getPageSize());
        result.setCategory(categoryresult);
        if(StringUtils.isNotBlank(trueWord)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("trueWord",trueWord);
            jsonObject.put("errorWord",errorWord);
            result.setCorrectData(jsonObject);
        }
        return result;

    }

    private void lightHigh(AdvSearchReqVO reqVO, List<Map<String, Object>> data, List<TableFieldDO> searchList) {
        if (reqVO.getType() == 1 && StringUtils.isNotBlank(reqVO.getKeyword())) {
            for (Map<String, Object> map : data) {
                for (TableFieldDO fieldDO : searchList) {
                    Object value = map.get(fieldDO.getFieldName());
                    map.put(fieldDO.getFieldName(), String.valueOf(value).replace(reqVO.getKeyword(), "<span style=\"color:red; font-weight: 600;\">" + reqVO.getKeyword() + "</span>"));
                }
            }
        } else if (reqVO.getType() == 2) {
            for (Map<String, Object> map : data) {
                for (int i = 0; i < reqVO.getAdvField().length; i++) {
                    if (reqVO.getFieldType()[i].equals("string")) {
                        Object value = map.get(reqVO.getAdvField()[i]);
                        map.put(reqVO.getAdvField()[i], String.valueOf(value).replace(String.valueOf(reqVO.getAdvValue()[i]), "<span style=\"color:red; font-weight: 600;\">" + String.valueOf(reqVO.getAdvValue()[i]) + "</span>"));
                    }
                }
            }
        }
    }

    private String buildSort(LinkedHashMap<String, String> map) {
        StringBuffer sb = new StringBuffer();
        map.forEach((k, v) -> {
            if(v.equals("desc")){
                sb.append("-"+k);
                //sb.append((v.equals("desc") ? "-" : "+") + k + ",");
            }
            if(v.equals("asc")){
                sb.append("+"+k);
                //sb.append((v.equals("desc") ? "-" : "+") + k + ",");
            }
        });
        String sort = sb.toString();
        if (StringUtils.isNotBlank(sort)) {
            //sort = sb.append("-doc_isindex,").toString();
            if(sort.lastIndexOf(",")!=-1){
                sort = sort.substring(0, sort.lastIndexOf(","));
            }

        } else {
            //sort = "-RELEVANCE,-file_updatetime,-doc_isindex";
            sort = "-RELEVANCE,-file_updatetime";
        }
        return sort;
    }
    private List<TableFieldDO> getFieldDOList(Integer type) {
        List<TableFieldDO> fieldDOList = new ArrayList<TableFieldDO>();
        TableFieldDO param1 = new TableFieldDO();
        param1.setFieldName("doc_title");
//        param1.setFieldName("file_name");
        fieldDOList.add(param1);
        if(type!=null&&type!=3){
            TableFieldDO param2 = new TableFieldDO();
            param2.setFieldName("doc_content");
            fieldDOList.add(param2);
            TableFieldDO param3 = new TableFieldDO();
            param3.setFieldName("doc_content_translate");
            fieldDOList.add(param3);
/*            TableFieldDO param4 = new TableFieldDO();
            param4.setFieldName("doc_title_translate");
            fieldDOList.add(param4);*/
/*            TableFieldDO param4 = new TableFieldDO();
            param4.setFieldName("doc_keywords");
            fieldDOList.add(param4);*/
            TableFieldDO param5 = new TableFieldDO();
            param5.setFieldName("doc_abstract");
            fieldDOList.add(param5);
        }

        /*TableFieldDO param3 = new TableFieldDO();
        param3.setFieldName("file_crtime");
        fieldDOList.add(param3);
        TableFieldDO param4 = new TableFieldDO();
        param4.setFieldName("sourcename");
        fieldDOList.add(param4);
        TableFieldDO param5 = new TableFieldDO();
        param5.setFieldName("file_type");
        fieldDOList.add(param5);*/
        return  fieldDOList;
    }

    public String condition(AdvSearchReqVO reqVO, List<TableFieldDO> searchList) {
        String condition = buildCondition(reqVO, searchList);
        if(reqVO.getCondition()!=null&&reqVO.getCondition() == 1){//条件检索
            String navCondition = buildNavCondition(reqVO.getNavigation());
            if (StringUtils.isNotBlank(navCondition)) {
                if (StringUtils.isNotBlank(condition)) {
                    condition = condition + String.format(" AND (%s)", navCondition);
                } else {
                    condition = navCondition;
                }
            }
        }

        if (reqVO.getStarttime()!=null) {
            if (!StringUtils.isBlank(condition)) {
                condition = condition + " AND ";
            }
            condition = condition + " file_updatetime "+ String.format(":[%s TO %s]", reqVO.getStarttime(), reqVO.getEndtime());
        }

/*        if (reqVO.getStarttime()!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                condition = condition + " AND file_updatetime>="+sdf.parse(reqVO.getStarttime())  ;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        if (reqVO.getEndtime()!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                condition = condition + " AND file_updatetime>="+sdf.parse(reqVO.getEndtime())  ;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }*/
        if (StringUtils.isBlank(condition)) {
            condition = "*:*";
        }
        return condition;
    }

    private String buildNavCondition(Map<String, String[]> navMap) {
        StringBuffer sb = new StringBuffer();
        if (navMap.size() > 0) {
            navMap.forEach((k, v) -> {
                if (v.length > 0) {
                    if (sb.length() > 0) {
                        sb.append(" AND ");
                    }
                    sb.append(String.format("%s#LIST:%s", k, Arrays.stream(v).map(String::valueOf).collect(Collectors.joining(","))));
                }
            });
        }
        return sb.toString();
    }

    private String buildCondition(AdvSearchReqVO reqVO, List<TableFieldDO> searchList) {
        StringBuffer sb = new StringBuffer();
        //快速检索
        if (reqVO.getType()!=null&&(reqVO.getType() == 1||reqVO.getType() == 3||(reqVO.getType() == 2&&reqVO.getAdvValue().length==1&&"".equals(reqVO.getAdvValue()[0] )))) {
            if (StringUtils.isNotBlank(reqVO.getKeyword())) {
                sb.append("(");
                int i = 0;
                for (TableFieldDO fieldDO : searchList) {
                    if (i > 0) {
                        sb.append(" OR ");
                    }
                    sb.append(fieldDO.getFieldName() + ":" + reqVO.getKeyword().replaceAll("\\s", ""));
                    i++;
                }
                sb.append(")");
            } else {
            }
        } else if (reqVO.getType()!=null&&reqVO.getType() == 2) {//高级检索
/*            if (StringUtils.isNotBlank(reqVO.getKeyword())) {
                sb.append("(");
                int i = 0;
                for (TableFieldDO fieldDO : searchList) {
                    if (i > 0) {
                        sb.append(" OR ");
                    }
                    sb.append(fieldDO.getFieldName() + ":" + reqVO.getKeyword().replaceAll("\\s", ""));
                    i++;
                }
                sb.append(")");
            }*/

            if (reqVO.getAdvField() != null && reqVO.getAdvField().length > 0
                    && reqVO.getAdvValue() != null && reqVO.getAdvValue().length > 0) {
                String[] advField = reqVO.getAdvField();
                Object[] advValue = reqVO.getAdvValue();
                String[] fieldType = reqVO.getFieldType();
                String[] fieldConnect = reqVO.getFieldConnect();
                if (reqVO.getAdvField().length >= 1) {
                    if(!"doc_adv".equals(advField[0])&&!"doc_adv_one".equals(advField[0])&&!"doc_adv_all".equals(advField[0])&&!"doc_adv_not".equals(advField[0])){
                        if (StringUtils.isNotBlank(reqVO.getKeyword())) {
                            sb.append("(");
                            int i = 0;
                            for (TableFieldDO fieldDO : searchList) {
                                if (i > 0) {
                                    sb.append(" OR ");
                                }
                                sb.append(fieldDO.getFieldName() + ":" + reqVO.getKeyword().replaceAll("\\s", ""));
                                i++;
                            }
                            sb.append(")");
                            sb.append(" AND ");
                        }
                    }

                    if (true||reqVO.getConnect() != null && reqVO.getConnect().length > 0) {
                        String[] connect = reqVO.getConnect();
                        for (int i = 0; i < advField.length; i++) {
                            if (i > 0) {
                                if(i==1&&sb.toString().contains("*:*")){
                                    sb.append(" AND ");
                                }else {
                                    sb.append(" " + connect[i - 1] + " ");
                                }

                            }
                            if (fieldType[i].equals("string")) {
                                //sb.append(advField[i] + ":" + String.valueOf(advValue[i]));
                                if("doc_adv".equals(advField[i])||"doc_adv_one".equals(advField[i])||"doc_adv_all".equals(advField[i])||"doc_adv_not".equals(advField[i])){
                                    if(i==0&&" ".equals(advValue[0])){
                                        sb.append("*:* ");
                                    }else {
                                        sb.append("(");
                                        if(advValue[i]!=null&&advValue[i].toString().split(" ").length>1){
                                            String[] advValues = advValue[i].toString().split(" ");
                                            for (int j = 0; j < advValues.length; j++) {
                                                if (j > 0 && "doc_adv_all".equals(advField[i])) {
                                                    sb.append(" AND ");
                                                } else if (j > 0 && "doc_adv_one".equals(advField[i])) {
                                                    sb.append(" OR ");
                                                } else if (j > 0) {
                                                    sb.append(" OR ");
                                                }
                                                sb.append("(");
                                                int z = 0;
                                                for (TableFieldDO fieldDO : searchList) {
                                                    if (z > 0) {
                                                        sb.append(" OR ");
                                                    }
                                                    sb.append(fieldDO.getFieldName() + ":" + String.valueOf(advValues[j]).replaceAll("\\s", ""));
                                                    z++;
                                                }
                                                sb.append(")");
                                            }
                                        }else {
                                            sb.append("(");
                                            int j = 0;
                                            for (TableFieldDO fieldDO : searchList) {
                                                if (j > 0) {
                                                    sb.append(" OR ");
                                                }
                                                sb.append(fieldDO.getFieldName() + ":" + String.valueOf(advValue[i]).replaceAll("\\s", ""));
                                                j++;
                                            }
                                            sb.append(")");
                                        }


                                        sb.append(")");
                                    }

                                }else {

                                    //sb.append(advField[i] + ":" + String.valueOf(advValue[i]));
                                    //高级搜索
                                    if(i>0 && fieldConnect!=null){
                                        sb.append(" (*:* "+fieldConnect[i-1]+ " ");
                                    }
                                    if(i>0 && fieldConnect==null){
                                        sb.append("(");
                                    }
                                    if("doc_title".equals(advField[i])){
                                        String[] advValues = advValue[i].toString().split(" ");
                                        sb.append("(");
                                        for (int j = 0; j < advValues.length; j++) {
                                            if(j>0){
                                                sb.append(" OR ");
                                            }
                                            sb.append(advField[i] + ":" + String.valueOf(advValues[j]));
                                        }
                                        sb.append(")");
                                        if(i>0){
                                            sb.append(")");
                                        }
                                    } else if ("doc_content".equals(advField[i])) {
                                        String[] advValues = advValue[i].toString().split(" ");
                                        sb.append("(");
                                        for (int j = 0; j < advValues.length; j++) {
                                            if(j>0){
                                                sb.append(" OR ");
                                            }
                                            sb.append(advField[i] + ":" + String.valueOf(advValues[j]));
                                        }
                                        sb.append(")");
                                        if(i>0){
                                            sb.append(")");
                                        }
                                    } else if ("doc_keywords".equals(advField[i])) {
                                        String[] advValues = advValue[i].toString().split(" ");
                                        sb.append("(");
                                        for (int j = 0; j < advValues.length; j++) {
                                            if(j>0){
                                                sb.append(" OR ");
                                            }
                                            sb.append(advField[i] + ":" + String.valueOf(advValues[j]));
                                        }
                                        sb.append(")");
                                        if(i>0){
                                            sb.append(")");
                                        }
                                    }  else if ("doc_title_content".equals(advField[i])) {
                                        String[] advValues = advValue[i].toString().split(" ");
                                        sb.append("(");
                                        for (int j = 0; j < advValues.length; j++) {
                                            if(j>0){
                                                sb.append(" OR ");
                                            }
                                            sb.append( "(doc_title:" + String.valueOf(advValues[j])+" OR doc_content:"+String.valueOf(advValues[j])+")"  );
                                        }
                                        sb.append(")");
                                        if(i>0){
                                            sb.append(")");
                                        }
                                    } else if ("doc_title_content_keywords".equals(advField[i])) {
                                        String[] advValues = advValue[i].toString().split(" ");
                                        sb.append("(");
                                        for (int j = 0; j < advValues.length; j++) {
                                            if(j>0){
                                                sb.append(" OR ");
                                            }
                                            sb.append( "(doc_title:" + String.valueOf(advValues[j])+" OR doc_content:"+String.valueOf(advValues[j])+" OR doc_keywords:"+String.valueOf(advValues[j])+")"  );
                                        }
                                        sb.append(")");
                                        if(i>0){
                                            sb.append(")");
                                        }
                                    }else{
                                        String[] advValues = advValue[i].toString().split(" ");
                                        for (int j = 0; j < advValues.length; j++) {
                                            sb.append( "(doc_title:" + String.valueOf(advValues[j])+" OR doc_content:"+String.valueOf(advValues[j])+" OR doc_keywords:"+String.valueOf(advValues[j])+" OR doc_content_translate:"+String.valueOf(advValues[j])+")"  );
                                        }
                                    }

                                }


                                //sb.append("(doc_title:" + String.valueOf(advValue[i]).replaceAll("\\s", "") + " OR doc_content:" + String.valueOf(advValue[i]).replaceAll("\\s", "") +  ")" );

                            } else if (fieldType[i].equals("date") || fieldType[i].equals("datetime")) {
                                List<String> value = (List<String>) advValue[i];
                                sb.append(advField[i] + String.format(":[%s TO %s]", value.get(0), value.get(1)));
                            }
                        }
                    } else {
                        //throw new ServiceException(501, "高级检索连接词不能为空!");
                    }
                } else {
                    for (int i = 0; i < advField.length; i++) {
                        if (fieldType[i].equals("string")) {
                            sb.append(" AND ");
                            sb.append(advField[i] + ":" + String.valueOf(advValue[i]).replaceAll("\\s", ""));
                        } else if (fieldType[i].equals("date") || fieldType[i].equals("datetime")) {
                            List<String> value = (List<String>) advValue[i];
                            sb.append(" AND ");
                            sb.append(advField[i] + String.format(":[%s TO %s]", value.get(0), value.get(1)));
                        }
                    }
                }
            } else {
                //throw new ServiceException(501, "高级检索字段或值不能为空!");
            }
        }
        return sb.toString();
    }


    public void update(AdvSearchSaveLabelsReqVO reqVO) {
        if(!"".equals(reqVO.getUid())){
            Map<String, Object> map = new HashMap<>();
            if(StringUtils.isNotBlank(reqVO.getDocLable()))
                map.put("doc_lable",reqVO.getDocLable());
            if(reqVO.getDocKeywords()!=null)
                map.put("doc_keywords",reqVO.getDocKeywords());
            //map.put("doc_visit",reqVO.getDocVisit());
            String tablename = "";
            if("ftp".equals(reqVO.getSourcename())){
                tablename = "system.dig_ftp";
            } else if ("ftp02".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            } else if ("ftp2".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            }  else if ("oracle".equals(reqVO.getSourcename())) {
                tablename = "system.dig_oracle";
            }
            hyBaseService.updateHybaseById(tablename, reqVO.getUid(), map);
        }
    }

    public void visit(AdvSearchSaveLabelsReqVO reqVO) {
        if(!"".equals(reqVO.getUid())){
            String tablename = "";
            if("ftp".equals(reqVO.getSourcename())){
                tablename = "system.dig_ftp";
            } else if ("ftp02".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            } else if ("ftp2".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            }  else if ("oracle".equals(reqVO.getSourcename())) {
                tablename = "system.dig_oracle";
            }
            SearchParams param = new SearchParams();
            Long docVisit = hyBaseService.selectVisitByDataid(tablename, "docid:"+reqVO.getDocid()+"", 0L, 1L, param);
            if(docVisit==null||docVisit>=0){
                Map<String, Object> map = new HashMap<>();
                if(reqVO.getDocid()!=null)
                    //map.put("doc_visit",Integer.valueOf(reqVO.getDocIsIndex()+1));
                    map.put("doc_visit",docVisit+1);
                hyBaseService.updateHybaseById(tablename, reqVO.getUid(), map);
            }
        }
    }

    public void collect(AdvSearchSaveLabelsReqVO reqVO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userid = ((LoginUser) authentication.getPrincipal()).getId();

        if(!"".equals(reqVO.getUid())){
            String tablename = "";
            if("ftp".equals(reqVO.getSourcename())){
                tablename = "system.dig_ftp";
            } else if ("ftp02".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            } else if ("ftp2".equals(reqVO.getSourcename())) {
                tablename = "system.dig_ftp02";
            }  else if ("oracle".equals(reqVO.getSourcename())) {
                tablename = "system.dig_oracle";
            }
            SearchParams param = new SearchParams();
            Map<String, Object> result = hyBaseService.selectColsByDataid(tablename, "docid:"+reqVO.getDocid()+"", 0L, 1L, param);
            Long docCollect =  Long.parseLong(result.get("doc_collect")+"");
            if(docCollect==null||docCollect>=0){
                Map<String, Object> map = new HashMap<>();
                if(reqVO.getDocid()!=null)
                    map.put("doc_collect",docCollect+1);
                hyBaseService.updateHybaseById(tablename, result.get("uid")+"", map);
            }

            SearchParams param2 = new SearchParams();
            List list = hyBaseService.selectlist("system.dig_daiban", "userid:"+userid +" AND docid:"+reqVO.getDocid(), 0L, 100L, param2);
            if(list.size()<=0){
                result.put("userid",userid);
                result.put("crtime",new Date());
                hyBaseService.insertHybase("system.dig_collect", result);
            }

        }
    }

    public void uncollect(AdvSearchSaveLabelsReqVO reqVO) {
        if(!"".equals(reqVO.getUid())){
            hyBaseService.deleteHybaseById("system.dig_collect", reqVO.getUid()+"");
        }
    }

    public PageResult collectlist(AdvSearchReqVO reqVO) {
        SearchParams param = new SearchParams();

        String condition = "  ";
        if (reqVO.getStarttime()!=null) {
            condition = condition + " AND crtime "+ String.format(":[%s TO %s]", reqVO.getStarttime(), reqVO.getEndtime());
        }
        if (reqVO.getNavigation()!=null&&reqVO.getNavigation().size()>0) {
            condition = condition+ " AND " + buildNavCondition(reqVO.getNavigation());
        }
        if(reqVO.getSort()!=null&&reqVO.getSort().size()>0){
            StringBuffer sb = new StringBuffer();
            reqVO.getSort().forEach((k, v) -> {
                sb.append((v.equals("desc") ? "-" : "+") + k + ",");
            });
            String sort = sb.toString();
            param.setSortMethod(sort);
        }
        PageResult<Map<String, Object>> result = hyBaseService.select("dig_collect", "userid:"+reqVO.getUserid()+""+ condition , Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);
        //lightHigh(reqVO, result.getList(), searchList);
        result.setPageNo(reqVO.getPageNo());
        result.setPageSize(reqVO.getPageSize());
        return result;
    }

    public List collectselectlist(AdvSearchReqVO reqVO) {
        SearchParams param = new SearchParams();
        List result = hyBaseService.selectlist("dig_collect", "userid:"+reqVO.getUserid()+" AND docid#LIST:"+reqVO.getDocid(), Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);
        //lightHigh(reqVO, result.getList(), searchList);
        return result;
    }


    public void clicklog(AdvSearchSaveLabelsReqVO reqVO) {
        if(!"".equals(reqVO.getUid())){
            DigVisitLogDO visitLogDO = new DigVisitLogDO();
            visitLogDO.setDocid(reqVO.getDocid());
            visitLogDO.setUid(reqVO.getUid());
            digVisitLogMapper.insert(visitLogDO);
        }
    }

    public void searchlog(AdvSearchSaveLabelsReqVO reqVO) {
        if(!"".equals(reqVO.getUid())){
            DigSearchLogDO searchLogDO = new DigSearchLogDO();
            searchLogDO.setDocid(reqVO.getDocid());
            searchLogDO.setUid(reqVO.getUid());
            digSearchLogMapper.insert(searchLogDO);
        }
    }

    public JSONObject indexdata() {
        JSONObject json = new JSONObject();
        Long visitCount = digVisitLogMapper.selectCount();
        Long searchCount = digSearchLogMapper.selectCount();
        Long RCount1 = digFtpSourceMapper.selectCount();
        Long RCount2 = digftpsource02Mapper.selectCount();
        Long RCount3 = oracleResourceMapper.selectCount();
        Long rourceCount = RCount1+RCount2+RCount3;
        Long userCont = adminUserMapper.selectCount();
        json.put("visitCount",visitCount);
        json.put("searchCount",searchCount);
        json.put("rourceCount",rourceCount);
        json.put("userCont",userCont);
        return json;
    }

    public JSONObject indexdataline() {
        JSONObject json = new JSONObject();
        List xmonth = new ArrayList<>();
        List ycount = new ArrayList<>();


        List<Map<String,String>> list = MonthStartEndDateTime();
        for (Map map : list) {
            QueryWrapper<DigSearchLogDO> qw = new QueryWrapper<DigSearchLogDO>();
            qw.between("create_time",map.get("start"),map.get("end"));
            Long searchCount = digSearchLogMapper.selectCount(qw);
            ycount.add(searchCount);
            xmonth.add(map.get("month"));
        }

        json.put("xmonth",xmonth);
        json.put("ycount",ycount);
        return json;
    }

    private List<Map<String,String>> MonthStartEndDateTime(){
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 存储每个月的开始和结束时间
        List<Map<String, String>> monthStartEndList = new ArrayList<>();
        // 日期格式化器
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 遍历过去12个月
        for (int i = 0; i < 12; i++) {
            // 当前月份向前推
            YearMonth yearMonth = YearMonth.from(currentDateTime).minusMonths(i);
            // 获取月初（第一天的00:00）
            LocalDateTime startOfMonth = yearMonth.atDay(1).atStartOfDay();
            // 获取月末（最后一天的23:59）
            LocalDateTime endOfMonth = yearMonth.atEndOfMonth().atTime(LocalTime.MAX);

            // 格式化时间
            String formattedStart = startOfMonth.format(dateTimeFormatter);
            String formattedEnd = endOfMonth.format(dateTimeFormatter);
            String formattedMonth = yearMonth.format(monthFormatter);

            // 添加到Map
            Map<String, String> map = new HashMap<>();
            map.put("month", formattedMonth);
            map.put("start", formattedStart);
            map.put("end", formattedEnd);
            monthStartEndList.add(map);
        }

        // 倒序排列
        Collections.reverse(monthStartEndList);
        return monthStartEndList;
    }

    public List<DeptDO> deptlist(AdvSearchReqVO reqVO) {
        Collection<Long> parentIds = Collections.singleton(Long.valueOf(reqVO.getUserid()));
        return deptMapper.selectListByParentId(parentIds);
    }


    public JSONArray docdeptlist(AdvSearchReqVO reqVO) {
        SearchParams param = new SearchParams();
        String condition = "  ";
        if (reqVO.getStarttime()!=null) {
            condition = condition + " AND file_updatetime "+ String.format(":[%s TO %s]", reqVO.getStarttime(), reqVO.getEndtime());
        }
        // 获取当前登录用户
        JSONArray categoryresult = hyBaseService.categoryQuery2("dig_daiban", "docid:"+reqVO.getDocid()+""+condition, "userid","userid",1000, param);
        return categoryresult;

    }

    public void daiban(AdvSearchSaveLabelsReqVO2 reqVO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long loginuserid = ((LoginUser) authentication.getPrincipal()).getId();
        // 获得部门信息
        if (reqVO.getUserid() != null) {
            SearchParams param1 = new SearchParams();

//            List list = hyBaseService.selectlist("system.dig_daiban", "docid:"+reqVO.getDocid(), 0L, 100L, param1);
            /*List list = hyBaseService.selectlist("system.dig_daiban", "userid:"+reqVO.getUserid()+" AND docid:"+reqVO.getDocid(), 0L, 100L, param1);
            for(int j=0;j<list.size();j++){
                Map<String, Object> map = (Map<String, Object>)list.get(j);
                if(!"".equals(map.get("uid"))){
                    hyBaseService.deleteHybaseById("system.dig_daiban", map.get("uid")+"");
                }
            }*/
            List list = hyBaseService.selectlist("system.dig_daiban", "batch_no#LIST:1,2 AND docid:"+reqVO.getDocid(), 0L, 100L, param1);
            for(int j=0;j<list.size();j++){
                Map<String, Object> map = (Map<String, Object>)list.get(j);
                if(!"".equals(map.get("uid"))){
                    hyBaseService.deleteHybaseById("system.dig_daiban", map.get("uid")+"");
                }
            }

//            String[] userids = reqVO.getUserid().split(",");
            String[] userids = reqVO.getUserid();
            for (int i = 0; i < userids.length; i++) {
                String userid = userids[i];

                String tablename = "";
                if("ftp".equals(reqVO.getSourcename())){
                    tablename = "system.dig_ftp";
                } else if ("ftp02".equals(reqVO.getSourcename())) {
                    tablename = "system.dig_ftp02";
                } else if ("ftp2".equals(reqVO.getSourcename())) {
                    tablename = "system.dig_ftp02";
                } else if ("oracle".equals(reqVO.getSourcename())) {
                    tablename = "system.dig_oracle";
                }

                SearchParams param = new SearchParams();
                Map<String, Object> result = hyBaseService.selectColsByDataid(tablename, "docid:"+reqVO.getDocid()+"", 0L, 1L, param);


                if(i==0){
                    result.put("batch_no","2");
                    result.put("userid",loginuserid);
                    result.put("crtime",new Date());
                    hyBaseService.insertHybase("system.dig_admin_daiban", result);
                }

                if(!"".equals(userid)&&userid.contains("u")){


                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("batch_no","2");
                    hyBaseService.updateHybaseById(tablename, result.get("uid")+"", updateMap);

                    result.put("userid",userid);
                    result.put("batch_no","2");
                    result.put("crtime",new Date());
                    hyBaseService.insertHybase("system.dig_daiban", result);
                }
            }

        }
    }

    public void dealdaiban(AdvSearchSaveLabelsReqVO2 reqVO) {

        if(reqVO.getIsAdmin()!=null&&reqVO.getIsAdmin()==1){
            SearchParams param1 = new SearchParams();
            Map<String, Object> result1 = hyBaseService.selectColsByDataid("system.dig_ftp02", "docid:"+reqVO.getDocid()+"", 0L, 1L, param1);
            Map<String, Object> updateMap1 = new HashMap<>();
            updateMap1.put("batch_no","3");
            hyBaseService.updateHybaseById("system.dig_ftp02", result1.get("uid")+"", updateMap1);

            Map<String, Object> updateMap2 = new HashMap<>();
            updateMap2.put("batch_no","3");
            hyBaseService.updateHybaseById("system.dig_admin_daiban", reqVO.getUid(), updateMap2);

            SearchParams param = new SearchParams();
            List list = hyBaseService.selectlist("system.dig_daiban", "docid:"+reqVO.getDocid()+" AND batch_no:2", 0L, 100L, param);
            if(list.size()>0){
                List<Map<String, Object>> list2 = (List<Map<String, Object>>)list;
                for (Map<String, Object> map: list2) {
                    Map<String, Object> updateMap3 = new HashMap<>();
                    updateMap3.put("batch_no","3");
                    hyBaseService.updateHybaseById("system.dig_daiban", map.get("uid")+"", updateMap3);
                }
            }
        }else{
            Map<String, Object> updateMap1 = new HashMap<>();
            updateMap1.put("batch_no","3");
            hyBaseService.updateHybaseById("system.dig_daiban", reqVO.getUid(), updateMap1);

            SearchParams param = new SearchParams();
            Map<String, Object> result = hyBaseService.selectColsByDataid("system.dig_daiban", "docid:"+reqVO.getDocid()+" AND batch_no:2", 0L, 1L, param);
            if(result.size()<=0){
                SearchParams param2 = new SearchParams();
                Map<String, Object> result2 = hyBaseService.selectColsByDataid("system.dig_ftp02", "docid:"+reqVO.getDocid()+"", 0L, 1L, param2);

                Map<String, Object> updateMap2 = new HashMap<>();
                updateMap2.put("batch_no","3");
                hyBaseService.updateHybaseById("system.dig_ftp02", result2.get("uid")+"", updateMap2);


                SearchParams param3 = new SearchParams();
                Map<String, Object> result3 = hyBaseService.selectColsByDataid("system.dig_admin_daiban", "docid:"+reqVO.getDocid()+"", 0L, 1L, param3);

                Map<String, Object> updateMap3 = new HashMap<>();
                updateMap3.put("batch_no","3");
                hyBaseService.updateHybaseById("system.dig_admin_daiban", result3.get("uid")+"", updateMap3);

            }
        }

    }

    public void undaiban(AdvSearchSaveLabelsReqVO2 reqVO) {
        if(!"".equals(reqVO.getUid())){
            hyBaseService.deleteHybaseById("system.dig_daiban", reqVO.getUid()+"");
        }
    }

    public PageResult daibanlist(AdvSearchReqVO reqVO) {
        SearchParams param = new SearchParams();

        String condition = "  ";
        if (reqVO.getStarttime()!=null) {
            condition = condition + " AND crtime "+ String.format(":[%s TO %s]", reqVO.getStarttime(), reqVO.getEndtime());
        }
        if (reqVO.getNavigation()!=null&&reqVO.getNavigation().size()>0) {
            condition = " AND "+buildNavCondition(reqVO.getNavigation()) + condition;
        }
        // 获取当前登录用户
        AdminUserDO user = userService.getUser(getLoginUserId());

        if (user.getId() != null) {
            PageResult<Map<String, Object>> result = null;
            if(reqVO.getIsAdmin()!=null&&reqVO.getIsAdmin()==1){
                result = hyBaseService.select("dig_admin_daiban", "userid:"+user.getId()+""+ condition , Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);
            }else{
                result = hyBaseService.select("dig_daiban", "userid:"+"u_"+user.getId()+""+ condition , Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);

            }
            //lightHigh(reqVO, result.getList(), searchList);
            result.setPageNo(reqVO.getPageNo());
            result.setPageSize(reqVO.getPageSize());
            return result;
        }
/*        if (user.getDeptId() != null) {
            PageResult<Map<String, Object>> result = hyBaseService.select("dig_daiban", "userid:"+user.getDeptId()+""+ condition , Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);
            //lightHigh(reqVO, result.getList(), searchList);
            result.setPageNo(reqVO.getPageNo());
            result.setPageSize(reqVO.getPageSize());
            return result;
        }*/
        return null;

    }

    public List daibanselectlist(AdvSearchReqVO reqVO) {
        SearchParams param = new SearchParams();
        AdminUserDO user = userService.getUser(getLoginUserId());
        List result = hyBaseService.selectlist("dig_daiban", "userid:"+"u_"+user.getId()+" AND docid#LIST:"+reqVO.getDocid(), Long.valueOf(reqVO.getPageNo() - 1) * reqVO.getPageSize(), Long.valueOf(reqVO.getPageSize()), param);
        //lightHigh(reqVO, result.getList(), searchList);
        return result;
    }


}
