package com.yeejoin.amos.knowledgebase.face.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.FileInfoModel;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName;
import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType;
import com.yeejoin.amos.knowledgebase.face.feign.DataFillter;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.*;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocContentMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import com.yeejoin.amos.knowledgebase.face.util.DocSortUtil;
import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;
import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden;

import java.util.*;


/**
 * <p>
 * 知识库文档存储 服务类
 * </p>
 *
 * @author 子杨
 * @since 2020-08-05
 */
@Component
public class DocContentService extends BaseService<KnowledgeDocContentModel, KnowledgeDocContent, DocContentMapper> implements DataFillter {



    private final String orderBy = new StringBuilder().append("ORDER BY FIELD(audit_status, '").append(Constants.DOC_AUDIT_STATUS_SAVED).append("', '")
            .append(Constants.DOC_AUDIT_STATUS_SUBMITTED).append("', '").append(Constants.DOC_AUDIT_STATUS_REJECTED).append("', '")
            .append(Constants.DOC_AUDIT_STATUS_PASSED).append("') ASC, create_time DESC").toString();

    @Autowired
    private DynamicsValueService dynamicsValueService;
    @Autowired
    private InteractionCountService interactionCountService;
    @Autowired
    private InteractionRecordService interactionRecordService;
    @Autowired
    private TagService tagService;
    @Autowired
    private TagInstanceService tagInstanceService;
    @Autowired
    private DynamicsGroupService dynamicsGroupService;
    @Autowired
    private TagValueService tagValueService;
    @Autowired
    private
    DocLibraryService docLibraryService;
    @Autowired
    private Sequence sequence;

    public Page queryDocPage(int offset, int end, Map<String, String[]> paramMap, String[] auditStatus, String[] docStatus,
                             Date createTimeLeft, Date createTimeRight) {
        QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
        if (!ValidationUtil.isEmpty(auditStatus)) {
            wrapper.in("audit_status", Arrays.asList(auditStatus));
        }
        if (!ValidationUtil.isEmpty(docStatus)) {
            wrapper.in("doc_status", Arrays.asList(docStatus));
        }
        if (!ValidationUtil.isEmpty(createTimeLeft)) {
            wrapper.ge("create_time", createTimeLeft);
        }
        if (!ValidationUtil.isEmpty(createTimeRight)) {
            wrapper.le("create_time", createTimeRight);
        }

        //动态字段过滤
        if (!ValidationUtil.isEmpty(paramMap)) {
            wrapper = assembleFilterWithDynamics(wrapper, paramMap);
        }
        // 角色权限过滤
        wrapper = assembleFilterWithRole(wrapper);


        Page page = queryDocPageByWrapper(offset, end, wrapper);
        if (!ValidationUtil.isEmpty(page.getRecords())) {
            List<Map<Object, KnowledgeDynamicsValueModel>> returnList = new ArrayList<>();
            for (Object obj : page.getRecords()) {
                KnowledgeDocContentModel contentModel = (KnowledgeDocContentModel) obj;
                contentModel.setSummary(null);
                contentModel.setHtmlContent(null);
                Map contentMap = Bean.BeantoMap(contentModel);
                List<KnowledgeDynamicsValueModel> listByInstance = dynamicsValueService.queryByInstanceId(contentModel.getSequenceNbr());
                Map<Object, Object> returnMap = Bean.listToMap(listByInstance, "fieldName", "fieldValue", KnowledgeDynamicsValueModel.class);
                contentMap.putAll(returnMap);
                returnList.add(contentMap);
            }
            page.setRecords(returnList);
        }
        return page;
    }

    /**
     * @return com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel
     * @author 杨博超
     * @description 创建文档
     * @Param [docContentModel]
     **/
    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public KnowledgeDocContentModel createDoc(KnowledgeDocContentModel docContentModel) {
        Long sequenceNbr = sequence.nextId();
        docContentModel.setAgencyCode(RequestContext.getAgencyCode());
        docContentModel.setUserId(RequestContext.getExeUserId());
        docContentModel.setCreateTime(new Date());
        docContentModel.setDocStatus(Constants.DOC_STATUS_UNPUBLISHED);
        docContentModel.setAuditStatus(Constants.DOC_AUDIT_STATUS_SAVED);
        docContentModel.setSequenceNbr(sequenceNbr);
        String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
        if (ValidationUtil.isEmpty(inputerOrg)) {
            throw new RequestForbidden("非录入者角色用户无权录入");
        }
        docContentModel.setOrgCode(inputerOrg);
        String textContent = String.valueOf(docContentModel.getTextContent());
        docContentModel.setSummary(textContent.substring(0,Math.min(300, textContent.length())));
        if (ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) {
            docContentModel.setHaveAttachment(false);
        }

        //保存基础信息
        dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), sequenceNbr, DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey());

        // 保存标签实例
        List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), sequenceNbr, Constants.MARKING_TYPE_DOC);
        tagInstanceService.saveInstance(docContentModel.getDocContentTags(), sequenceNbr, Constants.MARKING_TYPE_CONTENT);
        QuoteCountFlushTiming.needFlushTag();
        //保存附件信息
        saveAttachments(docContentModel.getAttachments(), sequenceNbr);
        //生成排序字段信息
        docContentModel.setSortStr(DocSortUtil.getSortStr(docTags));
        docLibraryService.fillDirectoryName(Arrays.asList(docContentModel));
        return this.createWithModel(docContentModel);
    }


    private boolean saveAttachments(List<AttachmentModel> attachmentModels, Long docSeq) {
        if (!ValidationUtil.isEmpty(attachmentModels)) {
            for (AttachmentModel attachmentModel : attachmentModels) {
                FileInfoModel fileInfoModel = new FileInfoModel();
                fileInfoModel.setAgencyCode(RequestContext.getAgencyCode());
                fileInfoModel.setEntityId(String.valueOf(docSeq));
                fileInfoModel.setEntityType(KnowledgeDocContentModel.class.getSimpleName());
                fileInfoModel.setFilename(attachmentModel.getFilename());
                fileInfoModel.setOriginalFileName(attachmentModel.getOriginalFileName());
                fileInfoModel.setFileType(attachmentModel.getFileType());

                FeignClientResult<FileInfoModel> result = Systemctl.fileInfoClient.createByEntity(fileInfoModel);
            }
        }
        return true;
    }

    private boolean deleteAttachments(Long docSeq) {
        try {
            List<FileInfoModel> fileInfoModels = FeignUtil.remoteCall(() -> Systemctl.fileInfoClient.queryByEntity(RequestContext.getAgencyCode(), KnowledgeDocContentModel.class.getSimpleName(), String.valueOf(docSeq)));
            if (!ValidationUtil.isEmpty(fileInfoModels)) {
                Map<Long, Object> map = Bean.listToMap(fileInfoModels, "sequenceNbr", "filename", FileInfoModel.class);
                String ids = this.seperotorStrCollection(map.keySet());
                Systemctl.fileInfoClient.deleteFileInfo(ids);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除文件出错.");
        }
        return true;
    }

    private KnowledgeDocContentModel fillAttachments(KnowledgeDocContentModel docContentModel) {
        try {
            List<FileInfoModel> fileInfoModels = FeignUtil.remoteCall(() -> Systemctl.fileInfoClient.queryByEntity(RequestContext.getAgencyCode(), KnowledgeDocContentModel.class.getSimpleName(), String.valueOf(docContentModel.getSequenceNbr())));

            if (!ValidationUtil.isEmpty(fileInfoModels)) {
                List<AttachmentModel> attachments = new ArrayList<>();
                for (FileInfoModel fileInfoModel : fileInfoModels) {
                    AttachmentModel attachmentModel = new AttachmentModel();
                    attachmentModel.setFilename(fileInfoModel.getFilename());
                    attachmentModel.setFileType(fileInfoModel.getFileType());
                    attachmentModel.setOriginalFileName(fileInfoModel.getOriginalFileName());
                    attachmentModel.setFileUrl(fileInfoModel.getFileUrl());
                    attachments.add(attachmentModel);
                }
                docContentModel.setAttachments(attachments);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docContentModel;

    }


    private String seperotorStrCollection(Collection<Long> stringCollection) {
        String returnStr = "";
        if (!ValidationUtil.isEmpty(stringCollection)) {
            for (Long seq : stringCollection) {
                returnStr += String.valueOf(seq) + ",";
            }
            returnStr = returnStr.substring(0, returnStr.length() - 1);
        }
        return returnStr;
    }


    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public KnowledgeDocContentModel updateDoc(KnowledgeDocContentModel docContentModel) {

        KnowledgeDocContentModel oldModel = this.queryOneDocDetail(docContentModel.getSequenceNbr());

        if (ValidationUtil.isEmpty(oldModel)) {
            throw new DataNotFound("找不到指定的文档.");
        }
        //判断文档的可编辑状态。
        if (Constants.DOC_STATUS_PUBLISHED.equals(oldModel.getDocStatus())
                || Constants.DOC_AUDIT_STATUS_PASSED.equals(oldModel.getAuditStatus())
                || Constants.DOC_AUDIT_STATUS_SUBMITTED.equals(oldModel.getAuditStatus())) {
            throw new BadRequest("当前文档状态不可编辑.");
        }
        //如果文档为驳回状态，更改为待提交
        if (ValidationUtil.equals(Constants.DOC_AUDIT_STATUS_REJECTED, oldModel.getAuditStatus())) {
            oldModel.setAuditStatus(Constants.DOC_AUDIT_STATUS_SAVED);
        }
        if (!ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) {
            oldModel.setHaveAttachment(docContentModel.getHaveAttachment());
        }
        String textContent = String.valueOf(docContentModel.getTextContent());
        docContentModel.setSummary(textContent.substring(0,Math.min(300, textContent.length())));

        //保存基础信息
        dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), docContentModel.getSequenceNbr(), DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey());

        // 保存标签实例
        tagInstanceService.deleteByTargetSeq(oldModel.getSequenceNbr());//删除已有的标签
        List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), oldModel.getSequenceNbr(), Constants.MARKING_TYPE_DOC);
        tagInstanceService.saveInstance(docContentModel.getDocContentTags(), oldModel.getSequenceNbr(), Constants.MARKING_TYPE_CONTENT);

        // 重新保存附件信息
        deleteAttachments(oldModel.getSequenceNbr());//删除已有的文件信息
        saveAttachments(docContentModel.getAttachments(), oldModel.getSequenceNbr());//保存新的文件信息.
        oldModel.setDocTitle(docContentModel.getDocTitle());
        oldModel.setDirectoryId(docContentModel.getDirectoryId());
        docLibraryService.fillDirectoryName(Arrays.asList(oldModel));
        oldModel.setHtmlContent(docContentModel.getHtmlContent());
        //生成排序字段信息
        oldModel.setSortStr(DocSortUtil.getSortStr(docTags));
        docLibraryService.fillDirectoryName(Arrays.asList(oldModel));
        this.updateWithModel(oldModel);
        return Bean.copyExistPropertis(oldModel, docContentModel);
    }

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public List<Long> deleteDoc(List<Long> idList) {
        for (Long id : idList) {
            KnowledgeDocContentModel docContentModel = this.queryBySeq(id);
            if (ValidationUtil.isEmpty(docContentModel)) {
                throw new BadRequest("指定的文档不存在.");
            }
            if (Constants.DOC_STATUS_PUBLISHED.equals(docContentModel.getDocStatus())
                    || Constants.DOC_AUDIT_STATUS_PASSED.equals(docContentModel.getAuditStatus())
                    || Constants.DOC_AUDIT_STATUS_SUBMITTED.equals(docContentModel.getAuditStatus())) {
                throw new BadRequest("当前文档状态不可删除.");
            }
            this.dynamicsValueService.deleteByInstanceId(docContentModel.getSequenceNbr());
            this.tagInstanceService.deleteByTargetSeq(docContentModel.getSequenceNbr());

            this.deleteBySeq(id);
        }
        return idList;
    }


    public KnowledgeDocContentModel queryOneDocDetail(Long sequenceNbr) {
        KnowledgeDocContentModel docContentModel = this.queryBySeq(sequenceNbr);
        if (!ValidationUtil.isEmpty(docContentModel)) {
            //填充基础信息字段
            List<KnowledgeDynamicsValueModel> dynamicsValueModels = this.dynamicsValueService.queryByInstanceId(sequenceNbr);
            Map<String, Object> map = Bean.listToMap(dynamicsValueModels, "fieldName", "fieldValue", KnowledgeDynamicsValueModel.class);
            docContentModel.setDocBaseInfo(map);

            //文档标签
            List<KnowledgeTagInstanceModel> docTags = new ArrayList<>();
            //文档内容标签
            List<KnowledgeTagInstanceModel> docContentTags = new ArrayList<>();

            // 获取文档相关的所有标签
            List<KnowledgeTagInstanceModel> tagInstanceModelList = tagInstanceService.queryListByTargetSeq(docContentModel.getSequenceNbr());
            if (!tagInstanceModelList.isEmpty()) {
                Map<Object, KnowledgeTagInstanceModel> instanceModelMap = Bean.listToMap(tagInstanceModelList, "sequenceNbr", KnowledgeTagInstanceModel.class);
                // 获取所有的标签的值
                List<KnowledgeTagValueModel> tagValueModelList = tagValueService.queryTagValuesByDocId(docContentModel.getSequenceNbr());
                tagValueModelList.forEach(tagValue -> {
                    KnowledgeTagInstanceModel instanceModel = instanceModelMap.get(tagValue.getInstanceSeq());
                    if (instanceModel != null) {
                        List<KnowledgeTagValueModel> tagValues = instanceModel.getTagValues();
                        if (tagValues == null) {
                            tagValues = new ArrayList<>();
                            instanceModel.setTagValues(tagValues);
                        }
                        tagValues.add(tagValue);
                    }
                });
                tagInstanceModelList.forEach(instanceModel -> {
                    switch (instanceModel.getMarkingType()) {
                        case Constants.MARKING_TYPE_DOC:
                            docTags.add(instanceModel);
                            break;
                        default:
                            docContentTags.add(instanceModel);
                    }
                });
            }
            KnowledgeInteractionRecordModel recordModel = interactionRecordService.queryUniqueModel(RequestContext.getExeUserId(), KnowledgeDocContentModel.class.getSimpleName(),
                    String.valueOf(docContentModel.getSequenceNbr()), OperateType.COLLECT.name());

            fillAttachments(docContentModel);
            docContentModel.setDocTags(docTags);
            docContentModel.setDocContentTags(docContentTags);
            docContentModel.setCollected(!ValidationUtil.isEmpty(recordModel));
            docContentModel.setUserName(RemoteData.getUserRealNamById(docContentModel.getUserId()));
            docLibraryService.fillDirectoryName(Arrays.asList(docContentModel));
        }
        return docContentModel;
    }


    /**
     * @return boolean
     * @author 杨博超
     * @description 给文档点赞
     * @Param [sequenceNbr]
     **/
    public Map<String, Object> like(Long sequenceNbr) {
        excludeOperate(sequenceNbr, OperateType.LIKE, OperateType.DIS_LIKE);
        return queryLikeOrDis(sequenceNbr);
    }

    /**
     * @return boolean
     * @author 杨博超
     * @description 给文档吐槽
     * @Param [sequenceNbr]
     **/
    public Map<String, Object> disLike(Long sequenceNbr) {
        excludeOperate(sequenceNbr, OperateType.DIS_LIKE, OperateType.LIKE);
        return queryLikeOrDis(sequenceNbr);
    }

    /**
     * 互斥操作
     *
     * @param sequenceNbr 文档id
     * @param expect      期望操作类型
     * @param exclusions  互斥操作类型
     */
    private void excludeOperate(Long sequenceNbr, OperateType expect, OperateType... exclusions) {
        KnowledgeInteractionRecordModel recordModel = initInteractionRecordModel(sequenceNbr, expect);
        KnowledgeInteractionRecordModel oldModel = interactionRecordService.queryUniqueModel(recordModel.getUserId(), recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType());
        if (ValidationUtil.isEmpty(oldModel)) {
            interactionRecordService.createInteractionRecord(recordModel);
            for (OperateType exclusion : exclusions) {
                recordModel = initInteractionRecordModel(sequenceNbr, exclusion);
                oldModel = interactionRecordService.queryUniqueModel(recordModel.getUserId(), recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType());
                if (!ValidationUtil.isEmpty(oldModel)) {
                    interactionRecordService.deleteInteractionRecord(oldModel);
                }
            }
        } else {
            interactionRecordService.deleteInteractionRecord(oldModel);
        }
    }


    private KnowledgeInteractionRecordModel initInteractionRecordModel(Long sequenceNbr, OperateType operateType) {
        KnowledgeInteractionRecordModel recordModel = new KnowledgeInteractionRecordModel();
        recordModel.setAgencyCode(RequestContext.getAgencyCode());
        recordModel.setUserId(RequestContext.getExeUserId());
        recordModel.setEntityType(KnowledgeDocContentModel.class.getSimpleName());
        recordModel.setEntityId(String.valueOf(sequenceNbr));
        recordModel.setOperateType(operateType.name());
        recordModel.setRecUserId(RequestContext.getExeUserId());
        return recordModel;
    }

    /**
     * 分页查询文档，按审核状态+创建时间排序
     *
     * @param offset  起始
     * @param end     终止
     * @param wrapper 查询条件
     * @return
     */
    public Page queryDocPageByWrapper(int offset, int end, QueryWrapper<KnowledgeDocContent> wrapper) {
        Page page = new Page();
        int count = this.count(wrapper);
        page.setTotal(count);
        if (count > 0) {
            wrapper.last(orderBy + " LIMIT " + offset + ", " + end);
            List<KnowledgeDocContent> list = this.list(wrapper);
            page.setRecords(Bean.toModels(list, KnowledgeDocContentModel.class));
        }
        return page;
    }

    public Page queryDocPageByIdsAndParams(Page page, String docStatus, Collection<Long> sequenceNbr, Date createTimeLeft, Date createTimeRight) {
        QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
        wrapper.in("sequence_nbr", sequenceNbr).eq("doc_status", docStatus);
        if (!ValidationUtil.isEmpty(createTimeLeft)) {
            wrapper.ge("create_time", createTimeLeft);
        }
        if (!ValidationUtil.isEmpty(createTimeRight)) {
            wrapper.le("create_time", createTimeRight);
        }
        wrapper.orderByDesc("sequence_nbr");
        page = (Page) this.page(page, wrapper);
        if (!ValidationUtil.isEmpty(page.getRecords())) {
            page.setRecords(Bean.toModels(page.getRecords(), KnowledgeDocContentModel.class));
        }
        return page;
    }


    /**
     * 根据ID列表查询文档列表
     *
     * @param sequenceNbr ID列表
     * @return List
     */
    public List<KnowledgeDocContentModel> queryByIds(@Condition(Operator.in) Collection<Long> sequenceNbr) {
        return this.queryForList(null, false, sequenceNbr);
    }

    /**
     * 获取文档被引用数量
     *
     * @param sequenceNbr 文档ID
     * @return 数量
     */
    public int getReference(Long sequenceNbr) {
        return interactionCountService.getOperateCount(InteractionCountService.QUOTE_TYPE_ALL, InteractionCountService.QUOTE_ENTITY_DOCUMENT, sequenceNbr.toString());
    }


    /**
     * @return java.util.List<com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel>
     * @author 杨博超
     * @description 根据字符串模糊查询文档(搜索项为标签名和文档名)
     * @Param [queryString]
     **//*
    public List<KnowledgeDocContentModel> searchForDoc(Page page, String queryString) {

        List<KnowledgeDocContentModel> list = new ArrayList<>();

        if (!ValidationUtil.isEmpty(queryString)) {

            Map<String, Object> dataFillterParams = DataFillter.dataFillterByRoleName(this);

            String[] docStatus = (String[]) dataFillterParams.get(DataFillter.docStatus);
            String[] auditStatus = (String[]) dataFillterParams.get(DataFillter.docStatus);
            ;
            String userId = (String) dataFillterParams.get(DataFillter.userId);
            String orgCode = (String) dataFillterParams.get(DataFillter.orgCode);

            List<Map<String, Long>> docIds = this.getBaseMapper().searchForDocIds(RequestContext.getAgencyCode(),
                    queryString, docStatus, auditStatus, userId, orgCode, page.offset(), page.getSize());

            if (!ValidationUtil.isEmpty(docIds)) {
                for (Map<String, Long> map : docIds) {
                    Long docId = map.get("docSeq");
                    KnowledgeDocContentModel contentModel = this.queryOneDocDetail(docId);

                    List<KnowledgeTagInstanceModel> tagsToShow = new ArrayList<>();
                    for (KnowledgeTagInstanceModel contentTag : contentModel.getDocContentTags()) {
                        if (contentTag.getTagName().contains(queryString)) {
                            tagsToShow.add(contentTag);
                        }
                    }

                    for (KnowledgeTagInstanceModel docTag : contentModel.getDocTags()) {
                        if (docTag.getTagName().contains(queryString)) {
                            tagsToShow.add(docTag);
                        }
                    }

                    contentModel.setTagsToShow(tagsToShow);
                    contentModel.setDocContentTags(null);
                    contentModel.setDocTags(null);
                    contentModel.setHtmlContent(null);
                    list.add(contentModel);
                }
            }

        }

        return list;
    }*/

    //智能检索数据过滤
    @Override
    public Map<String, Object> assembleParams(List<String> roleNameList, String orgCode) {
        Map<String, Object> dataPrivilegemap = new HashMap<>();
        if (!ValidationUtil.isEmpty(roleNameList)) {

            Set<String> auditStatusSet = new HashSet<>();
            Set<String> docStatusSet = new HashSet<>();
            KnowledgeRoleName knowledgeRoleName = KnowledgeRoleName.getMaxScore(roleNameList, Comparator.comparingInt(KnowledgeRoleName::getSearchScore));
            if (ValidationUtil.isEmpty(knowledgeRoleName)) {
                switch (knowledgeRoleName) {
                    case TAG_MANAGER:
                        dataPrivilegemap.put("noData", true);
                        break;
                    case AUDITOR:
                    case INPUTER:
                    case VIEWER:
                        auditStatusSet.add(Constants.DOC_AUDIT_STATUS_PASSED);
                        docStatusSet.add(Constants.DOC_STATUS_PUBLISHED);
                        dataPrivilegemap.put(docStatus, docStatusSet.toArray(new String[docStatusSet.size()]));
                        dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()]));
                        break;
                    default:
                        throw new BadRequest("错误的用户角色.");
                }
            }

        }


        return dataPrivilegemap;
    }

    public Map<String, Object> queryLikeOrDis(Long sequenceNbr) {
        Map<String, Object> res = new HashMap<>();
        KnowledgeInteractionRecordModel recordModel = new KnowledgeInteractionRecordModel();
        recordModel.setUserId(RequestContext.getExeUserId());
        recordModel.setEntityType(KnowledgeDocContentModel.class.getSimpleName());
        recordModel.setEntityId(sequenceNbr.toString());
        recordModel.setOperateType(OperateType.LIKE.name());
        KnowledgeInteractionRecordModel myLike = interactionRecordService.queryUniqueModel(recordModel.getUserId(), recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType());
        int likeNum = interactionRecordService.countByInstance(recordModel.getOperateType(), recordModel.getEntityType(), recordModel.getEntityId());
        recordModel.setOperateType(OperateType.DIS_LIKE.name());
        KnowledgeInteractionRecordModel myDislike = interactionRecordService.queryUniqueModel(recordModel.getUserId(), recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType());
        int dislikeNum = interactionRecordService.countByInstance(recordModel.getOperateType(), recordModel.getEntityType(), recordModel.getEntityId());
        res.put("like", !ValidationUtil.isEmpty(myLike));
        res.put("disLike", !ValidationUtil.isEmpty(myDislike));
        res.put("likeNum", likeNum);
        res.put("dislikeNum", dislikeNum);
        return res;
    }

    /**
     * 查询最新文档
     *
     * @param top       条数
     * @param docStatus 文档状态
     * @return
     */
    public List<KnowledgeDocContentModel> queryNewDocsWithStatus(int top, String docStatus) {
        return this.queryForTopList(top, "rec_date", false, docStatus);
    }

    public List<KnowledgeDocContent> queryIdListByStatus(String docStatus) {
        QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
        wrapper.eq("doc_status", docStatus);
        wrapper.select("SEQUENCE_NBR");
        return getBaseMapper().selectList(wrapper);
    }

    public KnowledgeDocContent updateHtmlContent(Long id, String htmlContent) {
        KnowledgeDocContent docContent = this.getById(id);
        if (ValidationUtil.isEmpty(docContent)) {
            throw new DataNotFound("没有找到文档");
        }
        docContent.setHtmlContent(htmlContent);
        this.updateById(docContent);
        return docContent;
    }

    /**
     * 根据角色数据权限过滤
     */
    public QueryWrapper<KnowledgeDocContent> assembleFilterWithRole(QueryWrapper<KnowledgeDocContent> wrapper) {
        //获取用户录入者角色部门
        String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
        //获取用户审核者角色部门
        String auditorOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.AUDITOR.getRoleName());
        if (!ValidationUtil.isEmpty(inputerOrg) || !ValidationUtil.isEmpty(auditorOrg)) {
            //可查看自己的数据
            wrapper.and(w -> {
                if (!ValidationUtil.isEmpty(inputerOrg)) {
                    w.eq("user_id", RequestContext.getExeUserId());
                    if (!ValidationUtil.isEmpty(auditorOrg)) {
                        w.or();
                    }
                }
                if (!ValidationUtil.isEmpty(auditorOrg)) {
                    String[] auditStatus = {Constants.DOC_AUDIT_STATUS_PASSED, Constants.DOC_AUDIT_STATUS_SUBMITTED};
                    w.likeRight("org_code", auditorOrg).in("audit_status", Arrays.asList(auditStatus));
                }
            });
        } else {
            throw new RequestForbidden("用户角色错误");
        }
        return wrapper;
    }

    /**
     * 动态字段过滤
     */
    public QueryWrapper<KnowledgeDocContent> assembleFilterWithDynamics(QueryWrapper<KnowledgeDocContent> wrapper, Map<String, String[]> paramMap) {
        KnowledgeDynamicsGroupModel groupModel = dynamicsGroupService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
        if (ValidationUtil.isEmpty(groupModel)) {
            throw new DataNotFound("缺少动态字段配置");
        }
        Set<Long> instanceIds = dynamicsValueService.intersection(RequestContext.getAgencyCode(), groupModel.getSequenceNbr(), paramMap);
        if (ValidationUtil.isEmpty(instanceIds)) {
            //没有任何数据
            wrapper.eq("sequence_nbr", 1).eq("sequence_nbr", 0);
        } else {
            wrapper.in("sequence_nbr", instanceIds);
        }
        return wrapper;
    }

    public List<Long> getAllPublishedDocIds(){
        return this.baseMapper.getAllPublishedDocIds();
    }

    //根据分类id列表查询所有的文档id
    public List queryContentSeqListByCategorySeqList(List<Long> groupSeqList) {
        List<KnowledgeDocContentModel> refModelList = queryListByCategorySeqList(groupSeqList);
        Set<Object> docCotentId = Bean.listToMap(refModelList, "sequenceNbr", KnowledgeDocContentModel.class).keySet();
        return new ArrayList(docCotentId);
    }
    //根据分组id列表查询所有的关系
    private List<KnowledgeDocContentModel> queryListByCategorySeqList(@Condition(Operator.in) List<Long> directoryId) {
        return this.queryForList(null, false, directoryId);
    }
}
