package jnpf.memberLog.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jnpf.ImRobotApi;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.enums.memberLog.MemberLogImEnum;
import jnpf.enums.memberLog.MemberLogImJumpEnum;
import jnpf.exception.QueryException;
import jnpf.from.ImRobotTypeEnum;
import jnpf.from.JumpUrlListModel;
import jnpf.from.SendRobotNoticeDataForm;
import jnpf.from.SingleSendRobotNoticeForm;
import jnpf.memberLog.mapper.WorkLogMapper;
import jnpf.memberLog.service.WorkLogService;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.memberLog.dto.*;
import jnpf.model.memberLog.po.LogComment;
import jnpf.model.memberLog.vo.*;
import jnpf.permission.UserApi;
import jnpf.permission.dto.v2.user.QueryPageUserDTO;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.user.MiniUserVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 工作日志服务实现
 *
 * @author yanwenfu
 * @create 2023-08-08
 */
@Slf4j
@Service
public class WorkLogServiceImpl implements WorkLogService {
    private static final List<String> EMPTY_LIST = List.of("-1");


    @Resource
    private WorkLogMapper workLogMapper;

    @Resource
    private UserProvider userProvider;

    @Resource
    private DataSourceTransactionManager transactionManager;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private UserApi userApi;
    @Autowired
    private ImRobotApi imRobotApi;

    @Override
    public PageInfo<LogCommentVo> getCommentList(String logId, CommentQueryDto queryDto) {

        queryDto.setLogId(logId);
        MiniMemberLogVo memberLog = workLogMapper.getLog(logId);
        // 分页查询数据
        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        PageInfo<LogCommentVo> page = new PageInfo<>(workLogMapper.getCommentList(queryDto));
        if (page.getSize() > 0) {
            Set<String> collect1 = page.getList().stream().map(LogCommentVo::getCreatorUserId).collect(Collectors.toSet());
            Set<String> collect2 = page.getList().stream().map(LogCommentVo::getReplyUserId).collect(Collectors.toSet());
            collect1.addAll(collect2);
            Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(new ArrayList<>(collect1), null);

            page.getList().forEach(v -> {
                setReturnCommentValue(v, memberLog, userMap);
            });
        }
        return page;
    }

    @Override
    public LogCommentVo addCommentReply(String logId, AddReplyDto addReplyDto) {

        String userId = userProvider.get().getUserId();
        // 查询父级信息
        LogComment comment = workLogMapper.getLogComment(addReplyDto.getPid());
        LogComment logComment = new LogComment();
        logComment.setId(FtbUtil.getId());
        logComment.setMemberLogId(logId);
        logComment.setContent(addReplyDto.getContent());
        logComment.setPic(addReplyDto.getPic());
        logComment.setFile(addReplyDto.getFile());
        logComment.setPid(addReplyDto.getPid());
        String path;
        String rootId = "0";
        if (null != comment) {
            path = comment.getPath() + logComment.getId() + ",";
            if (comment.getRootId().equals(rootId)) {
                rootId = comment.getId();
            } else {
                rootId = comment.getRootId();
            }
        } else {
            path = addReplyDto.getPid() + "," + logComment.getId() + ",";
        }
        logComment.setPath(path);
        logComment.setRootId(rootId);
        logComment.setCreatorUserId(userId);
        logComment.setLastModifyUserId(userId);
        // 获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 设置事务隔离级别，开启新事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        // 获得事务状态，相当于开启事物
        TransactionStatus transactionStatus = transactionManager.getTransaction(def);
        workLogMapper.addCommentReply(logComment);
        transactionManager.commit(transactionStatus);
        // 查询LogCommentVo
        LogCommentVo returnComment = workLogMapper.getLogCommentVo(logComment.getId());
        MiniMemberLogVo memberLog = workLogMapper.getLog(logId);
        Set<String> userIdSet = Stream.of(returnComment.getCreatorUserId(), returnComment.getReplyUserId()).collect(Collectors.toSet());
        Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(new ArrayList<>(userIdSet), null);
        setReturnCommentValue(returnComment, memberLog, userMap);

        //消息推送
        String replyUserName = returnComment.getReplyUserName();
        String replyUserHeadIcon = returnComment.getReplyUserHeadIcon();
        List<UserEntity> userEntityList = userApiV2Util.getUserNameForUserIdsReturnList(List.of(userId));
        String userName = "";
        if(CollectionUtil.isNotEmpty(userEntityList)){
            userName = userEntityList.get(0).getRealName();
        }
        String title = userName+"评论了你的"  + memberLog.getLogType();
        List<String> toUserIds = ListUtil.of(memberLog.getCreatorUserId());
        UserInfo loginUser = UserProvider.getUser();

        msgSendToSomePeople(title, addReplyDto.getContent(), toUserIds, logId, loginUser.getTenantId(), memberLog.getLogType());
        return returnComment;
    }

    /**
     * 消息推送到一些人
     *
     * @param content   内容
     * @param toUserIds 推送到用户id
     * @param logId     日志id
     * @param tenantId  租户id
     */
    private void msgSendToSomePeople(String title, String content, List<String> toUserIds, String logId, String tenantId, String logType) {
        //通知

        SingleSendRobotNoticeForm sendRobotNoticeForm = new SingleSendRobotNoticeForm();
        sendRobotNoticeForm.setToUserIds(toUserIds);
        sendRobotNoticeForm.setTenantId(tenantId);
        sendRobotNoticeForm.setRobotTypeEnum(ImRobotTypeEnum.FTB_XZS);

        //消息体
        SendRobotNoticeDataForm msgBody = new SendRobotNoticeDataForm();


        msgBody.setTitle(title);
        msgBody.setContent(content);
        msgBody.setScene(MemberLogImEnum.UPDATE_LOG.getScene());
        msgBody.setContentSummary(content);
        msgBody.setAppName(MemberLogImEnum.UPDATE_LOG.getTitle());
        msgBody.setLogo(MemberLogImEnum.UPDATE_LOG.getLogoUrl());

        //按钮
        LinkedList<JumpUrlListModel> jumpList = new LinkedList<>();
        JumpUrlListModel jump = new JumpUrlListModel();
        jump.setButtonName(MemberLogImJumpEnum.MEMBER_LOG.getButtonName());
        jump.setType(1);
        jump.setDisplayMethodEnum(JumpUrlListModel.DisplayMethodEnum.TRUE);
        jump.setMpId(MemberLogImJumpEnum.MEMBER_LOG.getMpId());
        String jumpUrl = String.format(MemberLogImJumpEnum.MEMBER_LOG.getUrl(), logId, UserProvider.getLoginUserId(), logType);
        jump.setUrl(jumpUrl);
        jumpList.add(jump);
        msgBody.setJumpUrlList(jumpList);

        sendRobotNoticeForm.setRobotNoticeDataForm(msgBody);
        ActionResult actionResult = imRobotApi.sendSingleRobotNotice(sendRobotNoticeForm);
        if (!ActionResult.success().getCode().equals(actionResult.getCode())) {
            log.error(actionResult.getMsg());
        }
    }

    private void setReturnCommentValue(LogCommentVo v, MiniMemberLogVo memberLog, Map<String, UserBoundVO> userMap) {
        // 查询日志创建人, 判断评论是否作者
        if (v.getCreatorUserId().equals(memberLog.getCreatorUserId())) {
            v.setCheckAuthor(ConstantUtil.NUM_TRUE);
        }
        // 处理回复人信息
        if (StringUtils.isNotEmpty(v.getReplyUserId())) {
            UserBoundVO user = userMap.get(v.getReplyUserId());
            if (null != user) {
                v.setReplyUserName(user.getUserName());
                v.setReplyUserHeadIcon(user.getHeadIcon());
            }
        }
        // 查询用户基础信息
        UserBoundVO user = userMap.get(v.getCreatorUserId());
        if (user != null) {
            v.setCreatorUserName(user.getUserName());
            v.setOrganizeId(user.getOrganizeId());
            v.setOrganizeName(user.getOrganizeName());
            v.setPositionId(user.getPositionId());
            v.setPositionName(user.getPositionName());
            v.setHeadIcon(UploaderUtil.uploaderImg(user.getHeadIcon()));
        }
    }

    @Override
    public void addOrCancelLike(String logId) {

        String userId = userProvider.get().getUserId();
        // 查询用户是否有点赞记录
        LogAssociationVo association = workLogMapper.getLogAssociation(logId, userId, ConstantUtil.ASSOCIATION_LIKE);
        if (null == association) {
            // 无, 新增
            LogAssociationVo addVo = new LogAssociationVo(FtbUtil.getId(), logId, userId, 1, ConstantUtil.ASSOCIATION_LIKE, null);
            workLogMapper.addAssociationRecord(addVo);
        } else {
            // 有, 取消
            workLogMapper.deleteLikeRecord(association.getAssociationId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addForwardRecord(String logId, List<AddForwardDto> list) {

        List<LogAssociationVo> addList = new ArrayList<>();
        list.forEach(addForwardDto -> {
            LogAssociationVo addVo = new LogAssociationVo(FtbUtil.getId(), logId, addForwardDto.getUserId(), addForwardDto.getUserType(), ConstantUtil.ASSOCIATION_FORWARD, null);
            addList.add(addVo);
        });
        workLogMapper.addAssociationRecordBatch(addList);
    }

    @Override
    public LogStatVo getLogDataStat(StatQueryDto queryDto) throws Exception {

        String tenantId = StringUtils.isEmpty(queryDto.getTenantId()) ? userProvider.get().getTenantId() : queryDto.getTenantId();
        LogStatVo logStat = new LogStatVo();
        String[] split = queryDto.getBeginDate().split("-");
        logStat.setStatDate(split[0] + "年" + split[1] + "月");
        // 获取时间段
        DateStrVo dateStr = FtbUtil.getDateStr(queryDto.getBeginDate(), queryDto.getEndDate());
        logStat.getDateList().addAll(dateStr.getShowList());
        // 查询企业所有成员
        List<MiniUserVo> userList = getUserListByCondition(queryDto.getOrganizeId(), queryDto.getPositionId(), queryDto.getUserName(), tenantId);
        if (null == userList || userList.isEmpty()) {
            return logStat;
        }
        Map<String, MiniUserVo> allUserMap = userList.stream().collect(Collectors.toMap(MiniUserVo::getId, v -> v));
        List<String> userIds = userList.stream().map(MiniUserVo::getId).collect(Collectors.toList());

        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode().equals(1)) {
            List<String> managerUserIds = innerPowerUserVO.getUserIds();
            List<String> intersection = UserApiV2Util.getIntersection(managerUserIds, userIds);
            if (CollectionUtil.isNotEmpty(intersection)) {
                userIds = intersection;
            } else {
                return logStat;
            }
        } else if (innerPowerUserVO.getCode().equals(2)) {
            return logStat;
        }
        // 中文排序
        /*userList = userList.stream().filter(FtbUtil.distinctByKey1(MiniUserVo::getId))
                .sorted((o1, o2) -> Collator.getInstance(Locale.TRADITIONAL_CHINESE).compare(o1.getUserName(), o2.getUserName()))
                .collect(Collectors.toList());*/
        // 根据条件查询数据源
        List<LogDataVo> list = workLogMapper.getLogDataStat(queryDto, userIds);
        ConcurrentMap<String, List<LogDataVo>> logMap;
        if (list.isEmpty()) {
            logMap = new ConcurrentHashMap<>();
        } else {
            logMap = list.stream().collect(Collectors.groupingByConcurrent(LogDataVo::getCreatorUserId));
        }
        // 根据用户, 时间进行统计
        userIds.forEach(userId -> {
            MiniUserVo user = allUserMap.get(userId);
            // 筛选用户所有日期的数据
            List<LogDataVo> logList = logMap.get(user.getId());
            String[] array = new String[dateStr.getUseList().size()];
            Arrays.fill(array, "");
            if (null != logList && !logList.isEmpty()) {
                Map<String, LogDataVo> dateMap = logList.stream().collect(Collectors.toMap(LogDataVo::getCreatorTime, Function.identity()));
                for (int i = 0; i < dateStr.getUseList().size(); i++) {
                    String date = dateStr.getUseList().get(i);
                    LogDataVo vo = dateMap.get(date);
                    if (null != vo) {
                        array[i] = vo.getNum().toString();
                    }
                }
            }
            logStat.getUserList().add(user.getUserName());
            logStat.getUserIdList().add(user.getId());
            logStat.getDataList().add(array);
        });
        return logStat;
    }

    private List<MiniUserVo> getUserListByCondition(String organizeId, String positionId, String userName, String tenantId) {
        QueryPageUserDTO dto = new QueryPageUserDTO();
        dto.setTenantId(userProvider.get().getTenantId());
        dto.setPageSize(100000L);
        dto.setCurrentPage(1L);
        dto.setOrganizeId(organizeId);
        dto.setPositionId(positionId);
        dto.setKeyword(userName);
        PageListVO<UserBoundVO> userBoundVOPageListVO = userApiV2Util.pageListUserForWhere(dto);
        if (userBoundVOPageListVO != null && CollectionUtil.isNotEmpty(userBoundVOPageListVO.getList())) {
            return convertMiniUserVo(userBoundVOPageListVO.getList());
        }
        return new ArrayList<>();
    }

    private List<MiniUserVo> convertMiniUserVo(List<UserBoundVO> list) {
        List<MiniUserVo> ret = new ArrayList<>();
        for (UserBoundVO user : list) {
            MiniUserVo v = new MiniUserVo();
            v.setId(user.getId());
            v.setUserName(user.getUserName());
            v.setOrganizeId(user.getOrganizeId());
            v.setOrganizeName(user.getOrganizeName());
            v.setPositionId(user.getPositionId());
            v.setPositionName(user.getPositionName());
            v.setHeadIcon(UploaderUtil.uploaderImg(user.getHeadIcon()));
            ret.add(v);
        }
        return ret;
    }

    @Override
    public Workbook getLogDataStatWorkbook(StatQueryDto queryDto) throws Exception {

        LogStatVo logStat = getLogDataStat(queryDto);
        // 生成工作簿
        TemplateWorkSheet workSheet = new TemplateWorkSheet();
        workSheet.setSheetName(ConstantUtil.LOG_DATA_FORM);
        // 生成表头
        workSheet.setComplexRowNames(getRowNames(logStat, queryDto));
        workSheet.setTitleNum(2);
        int len = workSheet.getComplexRowNames()[0].length;
        // 合并单元格
        List<int[]> mergeCells = new ArrayList<>();
        int[] mergeCell = new int[]{0, 0, 0, len - 1};
        mergeCells.add(mergeCell);
        workSheet.setMergeCells(mergeCells);
        // 生成数据
        List<Object[]> dataList = new ArrayList<>();
        if (!logStat.getUserList().isEmpty()) {
            for (int i = 0; i < logStat.getUserList().size(); i++) {
                Object[] array = new Object[len];
                String[] dataArray = logStat.getDataList().get(i);
                for (int j = 0; j < len; j++) {
                    if (j == 0) {
                        array[j] = logStat.getUserList().get(i);
                    } else {
                        array[j] = dataArray[j - 1];
                    }
                }
                dataList.add(array);
            }
        }
        workSheet.setDataList(dataList);
        return TemplateExcelUtils.createWorkBook(Stream.of(workSheet).collect(Collectors.toList()), true);
    }

    @Override
    public PageInfo<MiniLogVo> getAppLogPage(LogQueryDto queryDto) {

        PageInfo<MiniLogVo> page;
        String userId = userProvider.get().getUserId();
        queryDto.setUserId(userId);
        switch (queryDto.getQueryType()) {
            case 0:
                // 全部 -> 我创建的, 别人抄送/汇报给我的
                PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
                page = new PageInfo<>(workLogMapper.getAllLogList(queryDto));
                break;
            case 1:
                // 我发出的 -> 我创建的
                PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
                page = new PageInfo<>(workLogMapper.getMyLogList(queryDto));
                break;
            case 2:
                // 我的部门 -> 我部门的人抄送/汇报给我, 我汇报/抄送给我部门的人
                UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, null);
                if (null == userPrimaryBoundOne) {
                    page = new PageInfo<>();
                    break;
                }
                // 查询我的部门下的所有成员
                List<String> organizeIds = List.of(userPrimaryBoundOne.getOrganizeId());
                List<UserPageListVO> orgUserList = userApiV2Util.getUserListForOrgIds(organizeIds, null);
                if (orgUserList.isEmpty()) {
                    page = new PageInfo<>();
                    break;
                }
                List<String> orgUserIds = orgUserList.stream().map(UserPageListVO::getId).distinct().collect(Collectors.toList());
                PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
                page = new PageInfo<>(workLogMapper.getMyOrganizeLogList(userId, orgUserIds, queryDto.getBeginDate(), queryDto.getEndDate()));
                break;
            default:
                page = new PageInfo<>();
                break;
        }
        if (page.getSize() > 0) {
            completePageInfo(page.getList());
        }
        return page;
    }

    private void completePageInfo(List<MiniLogVo> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        for (MiniLogVo miniLogVo : list) {
            String userId = miniLogVo.getUserId();
            if (StrUtil.isNotBlank(userId) && userId.contains(":")) {
                miniLogVo.setUserId(userId.split(":")[1]);
            }
        }

        // 查询每个日志下可以查看的内容
        ConcurrentMap<String, List<LogMemberFieldVo>> fieldMap = getLogFieldMap(list);
        // 设置用户信息
        List<String> userIds = list.stream().map(MiniLogVo::getUserId).collect(Collectors.toList());
        Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);

        list.forEach(v -> {
            UserBoundVO user = userMap.get(v.getUserId());
            if (null != user) {
                v.setUserName(user.getUserName());
                v.setHeadIcon(UploaderUtil.uploaderImg(user.getHeadIcon()));
            }
            // 设置可显示字段
            setFieldList(fieldMap, v);
        });
    }

    private <T extends LogInfoVo> void setFieldList(ConcurrentMap<String, List<LogMemberFieldVo>> fieldMap, T v) {
        List<LogMemberFieldVo> logFieldList = fieldMap.get(v.getLogId());
        if (null != logFieldList && !logFieldList.isEmpty()) {
            v.getFieldList().addAll(logFieldList);
        }
    }

    private ConcurrentMap<String, List<LogMemberFieldVo>> getLogFieldMap(List<? extends LogInfoVo> list) {

        List<String> logIds = list.stream().map(LogInfoVo::getLogId).collect(Collectors.toList());
        List<LogMemberFieldVo> fieldList = workLogMapper.getViewableFieldList(logIds);
        return fieldList.stream().collect(Collectors.groupingByConcurrent(LogMemberFieldVo::getMemberLogId));
    }

    @Override
    public PageInfo<WebLogVo> getWebLogPage(LogWebQueryDto queryDto) throws QueryException {
        String loginUserId = UserProvider.getLoginUserId();
        List<String> managerUserIds = new ArrayList<>();
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode().equals(1)) {
            managerUserIds = innerPowerUserVO.getUserIds();
            if (StringUtils.isNotEmpty(queryDto.getUserId())) {
                if (managerUserIds.contains(queryDto.getUserId())) {
                    managerUserIds = List.of(queryDto.getUserId());
                } else {
                    managerUserIds=EMPTY_LIST;
                }
            }
        } else if (innerPowerUserVO.getCode().equals(2)) {
            managerUserIds = EMPTY_LIST;
        }
        if (!(innerPowerUserVO.getCode().equals(0)
                && StringUtils.isEmpty(queryDto.getUserId())
                && StringUtils.isEmpty(queryDto.getOrganizeId())
                && StringUtils.isEmpty(queryDto.getPositionId())
                && StringUtils.isEmpty(queryDto.getUserName())
        ) && userApiV2Util.checkIsContinue(managerUserIds)) {
            QueryPageUserDTO dto = new QueryPageUserDTO();
            dto.setTenantId(userProvider.get().getTenantId());

            dto.setPageSize(100000L);
            dto.setCurrentPage(1L);
            dto.setOrganizeId(queryDto.getOrganizeId());
            dto.setPositionId(queryDto.getPositionId());
            dto.setKeyword(queryDto.getUserName());
            PageListVO<UserBoundVO> userBoundVOPageListVO = userApiV2Util.pageListUserForWhere(dto);

            if (userBoundVOPageListVO != null && CollectionUtil.isNotEmpty(userBoundVOPageListVO.getList())) {
                List<String> stringList = userBoundVOPageListVO.getList().stream().map(UserBoundVO::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(managerUserIds)) {
                    List<String> intersection = UserApiV2Util.getIntersection(stringList, managerUserIds);
                    if (CollectionUtil.isNotEmpty(intersection)) {
                        managerUserIds = intersection;
                    } else {
                        managerUserIds=EMPTY_LIST;
                    }
                } else {
                    managerUserIds = stringList;
                }
            } else {
                managerUserIds=EMPTY_LIST;
            }
        }


        // 查询日志列表
        PageInfo<WebLogVo> page;
        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        page = new PageInfo<>(workLogMapper.getWebLogListByAuth(queryDto.getQueryType(), queryDto.getBeginDate(), queryDto.getEndDate(), queryDto.getContent(), managerUserIds, loginUserId, "1"));


        if (page.getSize() > 0 && CollectionUtil.isNotEmpty(page.getList())) {
            List<WebLogVo> recordList = page.getList();
            List<String> userIds = recordList.stream().map(WebLogVo::getCreatorUserId).collect(Collectors.toList());
            Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
            ConcurrentMap<String, List<LogMemberFieldVo>> fieldMap = getLogFieldMap(recordList);
            recordList.forEach(v -> {
                // 设置用户信息
                UserBoundVO user = userMap.get(v.getCreatorUserId());
                if (null != user) {
                    v.setCreatorUserName(user.getUserName());
                    v.setPositionName(user.getPositionName());
                    v.setOrganizeName(user.getOrganizeName());
                }
                // 设置可显示字段
                setFieldList(fieldMap, v);
            });
        }
        return page;
    }

    private MiniUserVo changeToMiniUserVo(PartUserInfoVo user) {

        return new MiniUserVo(user);
    }

    @Override
    public PageInfo<MiniLogVo> getAppLogPageByCondition(ConditionLogQueryDto queryDto) throws QueryException {

        if (StringUtils.isEmpty(queryDto.getContent()) && StringUtils.isEmpty(queryDto.getOrganizeName())
                && StringUtils.isEmpty(queryDto.getPositionName()) && StringUtils.isEmpty(queryDto.getCreatorUserName())) {
            throw new QueryException("请输入查询内容");
        }
        // 查询符合条件的人
        List<MiniUserVo> userList = userApi.getUserByName(queryDto.getPositionName(), queryDto.getOrganizeName(), queryDto.getCreatorUserName());
        List<String> userIds = userList.stream().map(MiniUserVo::getId).collect(Collectors.toList());
        if (StringUtils.isEmpty(queryDto.getContent()) && userIds.isEmpty()) {
            return new PageInfo<>();
        }
        // 查询数据
        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        PageInfo<MiniLogVo> page = new PageInfo<>(workLogMapper.getLogListByCondition(userProvider.get().getUserId(), queryDto.getContent(), userIds));
        if (page.getSize() > 0) {
            completePageInfo(page.getList());
        }
        return page;
    }

    @Override
    public PageInfo<MiniLogVo> getAppLogPageByUser(ConditionLogQueryDto queryDto) {

        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        PageInfo<MiniLogVo> page = new PageInfo<>(workLogMapper.getLogListByUser(queryDto.getUserId(), queryDto.getBeginDate(), queryDto.getEndDate()));
        if (page.getSize() > 0) {
            completePageInfo(page.getList());
        }
        return page;
    }

    @Override
    public void deleteCommentReply(String commentId) {

        // 查询评论
        LogComment logComment = workLogMapper.getLogComment(commentId);
        if (logComment.getPid().equals("0")) {
            // 一级评论删除, 下级全删
            workLogMapper.deleteLogCommentByPath(commentId, userProvider.get().getUserId());
        } else {
            // 其他评论删除, 下级不删
            workLogMapper.deleteLogCommentById(commentId, userProvider.get().getUserId());
        }
    }

    @Override
    public Integer getCommentTotalNum(String logId) {

        return workLogMapper.getCommentTotalNum(logId);
    }

    @Override
    public LogStatVo getLogDataStatPage(StatQueryDto queryDto) {

        String tenantId = StringUtils.isEmpty(queryDto.getTenantId()) ? userProvider.get().getTenantId() : queryDto.getTenantId();
        LogStatVo logStat = new LogStatVo(queryDto.getPageSize());
        String[] split = queryDto.getBeginDate().split("-");
        logStat.setStatDate(split[0] + "年" + split[1] + "月");
        // 获取时间段
        DateStrVo dateStr = FtbUtil.getDateStr(queryDto.getBeginDate(), queryDto.getEndDate());
        logStat.getDateList().addAll(dateStr.getShowList());
        // 查询企业所有成员
        List<MiniUserVo> userList = getUserListByCondition(queryDto.getOrganizeId(), queryDto.getPositionId(), queryDto.getUserName(), tenantId);
        if (null == userList || userList.isEmpty()) {
            return logStat;
        }
        List<String> userIds = userList.stream().map(MiniUserVo::getId).collect(Collectors.toList());
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode().equals(1)) {
            List<String> managerUserIds = innerPowerUserVO.getUserIds();
            List<String> intersection = UserApiV2Util.getIntersection(managerUserIds, userIds);
            if (CollectionUtil.isNotEmpty(intersection)) {
                userIds = intersection;
            } else {
                return logStat;
            }
        } else if (innerPowerUserVO.getCode().equals(2)) {
            return logStat;
        }
        logStat.getPaginationVO().setTotal(userList.size());
        logStat.getPaginationVO().setCurrentPage((long) queryDto.getCurrentPage());

        userIds = userIds.stream()
                .skip(((long) queryDto.getCurrentPage() - 1) * queryDto.getPageSize())
                .limit(queryDto.getPageSize())
                .collect(Collectors.toList());
        // 根据条件查询数据源
        List<LogDataVo> list = workLogMapper.getLogDataStat(queryDto, userIds);
        ConcurrentMap<String, List<LogDataVo>> logMap;
        if (list.isEmpty()) {
            logMap = new ConcurrentHashMap<>();
        } else {
            logMap = list.stream().collect(Collectors.groupingByConcurrent(LogDataVo::getCreatorUserId));
        }
        Map<String, MiniUserVo> userMap = userList.stream().collect(Collectors.toMap(MiniUserVo::getId, Function.identity()));
        // 根据用户, 时间进行统计
        userIds.forEach(userId -> {
            MiniUserVo user = userMap.get(userId);
            // 筛选用户所有日期的数据
            List<LogDataVo> logList = logMap.get(userId);
            String[] array = new String[dateStr.getUseList().size()];
            Arrays.fill(array, "");
            if (null != logList && !logList.isEmpty()) {
                Map<String, LogDataVo> dateMap = logList.stream().collect(Collectors.toMap(LogDataVo::getCreatorTime, Function.identity()));
                for (int i = 0; i < dateStr.getUseList().size(); i++) {
                    String date = dateStr.getUseList().get(i);
                    LogDataVo vo = dateMap.get(date);
                    if (null != vo) {
                        array[i] = vo.getNum().toString();
                    }
                }
            }
            logStat.getUserList().add(user.getUserName());
            logStat.getUserIdList().add(user.getId());
            logStat.getDataList().add(array);
        });
        return logStat;
    }

    private String[][] getRowNames(LogStatVo logStat, StatQueryDto queryDto) {
        OrganizeGeneralDetailVO organizeGeneralDetailVO = userApiV2Util.organizeInfoById(queryDto.getOrganizeId(),null);
        String organizeName = "全部";
        if(organizeGeneralDetailVO!=null){
            organizeName = organizeGeneralDetailVO.getOrganizeTreeName();
        }
        if(StringUtils.isNotEmpty(queryDto.getOrganizeName())){
            organizeName = queryDto.getOrganizeName();
        }
        String[][] rowNames = new String[2][logStat.getDateList().size() + 1];
        // 第一行数据
        String title = "";
        if (StringUtils.isNotEmpty(queryDto.getUserName())) {
            title += "姓名：" + queryDto.getUserName() + "  ";
        }
        title += "部门：" + organizeName + "  岗位：" + queryDto.getPositionName() + "  类型：" + queryDto.getQueryType();
        rowNames[0][0] = title;
        for (int i = 0; i < rowNames.length; i++) {
            for (int j = 0; j < rowNames[i].length; j++) {
                if (i == 0) {
                    if (j == 0) {
                        rowNames[i][j] = title;
                    } else {
                        rowNames[i][j] = "";
                    }
                } else {
                    if (j == 0) {
                        rowNames[i][j] = logStat.getStatDate();
                    } else {
                        rowNames[i][j] = logStat.getDateList().get(j - 1);
                    }
                }
            }
        }
        return rowNames;
    }
}
