package com.storlead.sales.service.impl.customer;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.message.pojo.entity.UserMessageNoticeConfigEntity;
import com.storlead.sales.pojo.dto.customer.BulletinDTO;
import com.storlead.sales.pojo.dto.customer.BulletinSearchDTO;
import com.storlead.sales.pojo.entity.customer.BulletinEntity;
import com.storlead.sales.pojo.entity.customer.BulletinReadEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.SysResourceEntity;
import com.storlead.sales.pojo.vo.customer.BulletinDetailVO;
import com.storlead.sales.pojo.vo.customer.BulletinReadVO;
import com.storlead.sales.pojo.vo.customer.BulletinVO;
import com.storlead.sales.pojo.vo.customer.RecordCommentVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.BulletinMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 公告主表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-10-25
 */
@Service
public class BulletinServiceImpl extends MyBaseServiceImpl<BulletinMapper, BulletinEntity> implements BulletinService {
    @Resource
    BulletinMapper bulletinMapper;
    @Resource
    private IUserRoleService userRoleService;
    @Resource
    BulletinReadService bulletinReadService;
    @Resource
    private SysResourceService sysResourceService;
    @Resource
    private IUserService userService;
    @Resource
    private MessageAssembleService assembleService;

    @Resource
    private RecordCommentService recordCommentService;


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> add(BulletinDTO bulletinDTO) {
        BulletinEntity bulletinEntity = new BulletinEntity();
        BeanUtils.copyProperties(bulletinDTO,bulletinEntity);
        if(StringUtils.isEmpty(bulletinEntity.getTitle())){
            return Result.error("标题不能为空");
        }
        if(StringUtils.isEmpty(bulletinEntity.getContent())){
            return Result.error("内容不能为空");
        }
        if(ObjectUtils.isEmpty(bulletinEntity.getBulletinType())){
            return Result.error("未设置通知范围");
        }
//        if(bulletinDTO.getBulletinType()==2&&StringUtils.isBlank(bulletinEntity.getNoticeUserIds())){
//            return Result.error("通知人员不能为空");
//        }
        if(bulletinDTO.getBulletinType()==2 && CollectionUtils.isEmpty(bulletinDTO.getNoticeUserIdList())){
            return Result.error("通知人员不能为空");
        }
        if (!CollectionUtils.isEmpty(bulletinDTO.getNoticeUserIdList())){
            String noticeUserIds = String.join(",", bulletinDTO.getNoticeUserIdList().stream().map(Object::toString).toArray(String[]::new));
            bulletinEntity.setNoticeUserIds(noticeUserIds);
        }
        boolean ok = this.save(bulletinEntity);
        if(bulletinDTO.getFileIds() != null && bulletinDTO.getFileIds().size() > 0){
            LambdaUpdateWrapper<SysResourceEntity> resourceWrapper = new LambdaUpdateWrapper<>();
            resourceWrapper.in(SysResourceEntity ::getId,bulletinDTO.getFileIds());
            resourceWrapper.set(SysResourceEntity::getResourceType, ResourceTypeEnum.BULLETIN.code);
            resourceWrapper.set(SysResourceEntity::getResourceTypeId,bulletinEntity.getId());
            boolean sysResourceList = sysResourceService.update(resourceWrapper);
        }

        if(ok){
            Set<Long> userIds;
            if(bulletinEntity.getBulletinType()==1){
                //查询所有人员
                List<UserEntity> userEntities = userService.activeUsers();
                userIds= userEntities.stream().map(UserEntity::getId).collect(Collectors.toSet());
                bulletinReadService.add(userIds,bulletinEntity.getId());
            }else {
                if(StringUtils.isNotEmpty(bulletinEntity.getNoticeUserIds())){
                    userIds = Arrays.stream(bulletinEntity.getNoticeUserIds().split(",")).map(Long::parseLong).collect(Collectors.toSet());
                    bulletinReadService.add(userIds,bulletinEntity.getId());
                }
            }
            String remindMode = bulletinEntity.getRemindMode();
            //发送消息
            if (bulletinEntity.getBulletinType() == 1){
                assembleService.sendBulletinMessages(bulletinEntity.getId(),"ADD_BULLETIN",remindMode);
            }else {
                Set<Long> toUserIds = new HashSet<>(bulletinDTO.getNoticeUserIdList());
                assembleService.sendBulletinMessages(bulletinEntity.getId(),"ADD_BULLETIN",toUserIds,remindMode);
            }

            return Result.result("公告发布成功");
        }else {
            return Result.error("公告发布失败");
        }
    }

    @Override
    public BulletinDetailVO getBulletinDetailVOById(Long id,Long userId) {
        if (!ObjectUtils.isEmpty(id)) {
            BulletinEntity bulletinEntity = getById(id);
            if(!ObjectUtils.isEmpty(bulletinEntity)){
                BulletinDetailVO bulletinDetailVO = new BulletinDetailVO();
                BeanUtils.copyProperties(bulletinEntity,bulletinDetailVO);
                bulletinDetailVO.setId(bulletinEntity.getId())
                        .setTitle(bulletinEntity.getTitle())
                        .setContent(bulletinEntity.getContent())
                        .setNoticeTime(bulletinEntity.getNoticeTime())
                        .setBulletinType(bulletinEntity.getBulletinType())
                        .setDeadlineDate(bulletinEntity.getDeadlineDate())
                        .setColumnValue(bulletinEntity.getColumnValue())
                        .setRemindMode(bulletinEntity.getRemindMode())
                        .setNoticeUserIds(bulletinEntity.getNoticeUserIds())
                        .setFormerOwnerBy(bulletinEntity.getFormerOwnerBy());
//              填充阅读对象
                LambdaUpdateWrapper<SysResourceEntity> resourceWrapper = new LambdaUpdateWrapper<>();
                resourceWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.BULLETIN.code);
                resourceWrapper.eq(SysResourceEntity::getResourceTypeId,bulletinEntity.getId());
                resourceWrapper.eq(SysResourceEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                List<SysResourceEntity> sysResourceEntities = sysResourceService.list(resourceWrapper);
                bulletinDetailVO.setFiles(sysResourceEntities);
                fillReadVOForDetail(bulletinDetailVO);
                Long publisherId = bulletinEntity.getCreateBy();
                UserEntity userEntity = userService.getById(publisherId);
                String publisherName = userEntity.getRealName();

                bulletinDetailVO.setPublisher(publisherName); // 发布者
                bulletinDetailVO.setIsTalk(bulletinEntity.getIsTalk()); // 是否评论
                LambdaQueryWrapper<BulletinReadEntity> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(BulletinReadEntity::getBulletinId,bulletinEntity.getId());
                wrapper.eq(BulletinReadEntity::getHasRead,true);
                wrapper.eq(BulletinReadEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                int count = bulletinReadService.count(wrapper);
                bulletinDetailVO.setReadCount(count); //阅读人数

                Long currentUserId = LoginUserUtil.getCurrentUserId();
                List<RecordCommentVO> commentVOS = recordCommentService.listCommont(Integer.valueOf(120),Arrays.asList(id));
                if (!CollectionUtils.isEmpty(commentVOS)) {
                    Map<Long, List<RecordCommentVO>> groupMap = commentVOS.stream().collect(Collectors.groupingBy(RecordCommentVO::getRecordId));
                        List<RecordCommentVO> vs = groupMap.get(id);
                        if (!CollectionUtils.isEmpty(vs)) {
                            canDelete(vs,currentUserId,bulletinEntity.getOwnerBy());
                        }
                    bulletinDetailVO.setCommentls(vs);

                }
//                LocalDateTime now = LocalDateTime.now();//记录查看时间
//                LambdaUpdateWrapper<BulletinReadEntity> queryWrapper = new LambdaUpdateWrapper<>();
//                queryWrapper.eq(BulletinReadEntity::getBulletinId,bulletinEntity.getId());
//                queryWrapper.eq(BulletinReadEntity::getReadUserId,userId);
//                queryWrapper.set(BulletinReadEntity::getHasRead,true);
//                queryWrapper.set(BulletinReadEntity::getCreateTime,now);
//                List<BulletinReadEntity> bulletinReadEntities = bulletinReadService.list(queryWrapper);
//                Boolean B = bulletinReadService.update(queryWrapper);
                return bulletinDetailVO;
            }
        }
        return null;
    }

    @Override
    public BulletinDetailVO getBulletinDetailVOById(Long id) {
        if (!ObjectUtils.isEmpty(id)) {
            BulletinEntity bulletinEntity = getById(id);
            if(!ObjectUtils.isEmpty(bulletinEntity)){
                BulletinDetailVO bulletinDetailVO = new BulletinDetailVO();
                BeanUtils.copyProperties(bulletinEntity,bulletinDetailVO);
                bulletinDetailVO.setId(bulletinEntity.getId())
                        .setTitle(bulletinEntity.getTitle())
                        .setContent(bulletinEntity.getContent())
                        .setNoticeTime(bulletinEntity.getNoticeTime())
                        .setBulletinType(bulletinEntity.getBulletinType())
                        .setDeadlineDate(bulletinEntity.getDeadlineDate())
                        .setColumnValue(bulletinEntity.getColumnValue())
                        .setRemindMode(bulletinEntity.getRemindMode())
                        .setNoticeUserIds(bulletinEntity.getNoticeUserIds())
                        .setFormerOwnerBy(bulletinEntity.getFormerOwnerBy());
//              填充阅读对象
                LambdaUpdateWrapper<SysResourceEntity> resourceWrapper = new LambdaUpdateWrapper<>();
                resourceWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.BULLETIN.code);
                resourceWrapper.eq(SysResourceEntity::getResourceTypeId,bulletinEntity.getId());
                resourceWrapper.eq(SysResourceEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                List<SysResourceEntity> sysResourceEntities = sysResourceService.list(resourceWrapper);
                bulletinDetailVO.setFiles(sysResourceEntities);
                fillReadVOForDetail(bulletinDetailVO);
                Long publisherId = bulletinEntity.getCreateBy();
                UserEntity userEntity = userService.getById(publisherId);
                String publisherName = userEntity.getRealName();
                bulletinDetailVO.setPublisher(publisherName); // 发布者
                bulletinDetailVO.setIsTalk(bulletinEntity.getIsTalk()); // 是否评论
                LambdaQueryWrapper<BulletinReadEntity> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(BulletinReadEntity::getBulletinId,bulletinEntity.getId());
                wrapper.eq(BulletinReadEntity::getHasRead,true);
                wrapper.eq(BulletinReadEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
                int count = bulletinReadService.count(wrapper);
                bulletinDetailVO.setReadCount(count); //阅读人数
                return bulletinDetailVO;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> edit(BulletinDTO bulletinDTO) {
        BulletinEntity bulletinEntity = new BulletinEntity();
        BeanUtils.copyProperties(bulletinDTO,bulletinEntity);
        if(bulletinEntity.getId()==null){
            return Result.error("id不能为空");
        }
        if(StringUtils.isEmpty(bulletinEntity.getTitle())){
            return Result.error("标题不能为空");
        }
        if(ObjectUtils.isEmpty(bulletinEntity.getBulletinType())){
            return Result.error("未设置通知范围");
        }
        if(StringUtils.isEmpty(bulletinEntity.getContent())){
            return Result.error("内容不能为空");
        }
        if(bulletinDTO.getBulletinType()==2 && CollectionUtils.isEmpty(bulletinDTO.getNoticeUserIdList())){
            return Result.error("通知人员不能为空");
        }
        if (!CollectionUtils.isEmpty(bulletinDTO.getNoticeUserIdList())){
            String noticeUserIds = String.join(",", bulletinDTO.getNoticeUserIdList().stream().map(Object::toString).toArray(String[]::new));
            bulletinEntity.setNoticeUserIds(noticeUserIds);
        }
//        if(!canEdit(bulletinDTO.getId())){
//            return Result.error("没有编辑权限");
//        }
        sysResourceService.deleteByResourceId(ResourceTypeEnum.BULLETIN.code,bulletinEntity.getId());
        if(bulletinDTO.getFileIds() != null && bulletinDTO.getFileIds().size() > 0){
            LambdaUpdateWrapper<SysResourceEntity> resourceWrapper = new LambdaUpdateWrapper<>();
            resourceWrapper.in(SysResourceEntity ::getId,bulletinDTO.getFileIds());
            resourceWrapper.set(SysResourceEntity::getResourceType, ResourceTypeEnum.BULLETIN.code);
            resourceWrapper.set(SysResourceEntity::getResourceTypeId,bulletinEntity.getId());
            resourceWrapper.set(SysResourceEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            boolean sysResourceList = sysResourceService.update(resourceWrapper);
        }
        BulletinEntity preBulletin = this.getById(bulletinEntity.getId());
        boolean ok = this.updateById(bulletinEntity);
        if(ok){
            if(!Objects.equals(preBulletin.getContent(),bulletinDTO.getContent())){
                Set<Long> userIds = new HashSet<>();
                if(bulletinEntity.getBulletinType()==1){
                    //查询所有人员
                    List<UserEntity> userEntities = userService.activeUsers();
                    userIds= userEntities.stream().map(UserEntity::getId).collect(Collectors.toSet());
                    bulletinReadService.edit(userIds,bulletinDTO.getId(),true);
                }else {
                    if(StringUtils.isNotEmpty(bulletinEntity.getNoticeUserIds())){
                        userIds = Arrays.stream(bulletinEntity.getNoticeUserIds().split(",")).map(Long::parseLong).collect(Collectors.toSet());
                        bulletinReadService.edit(userIds,bulletinDTO.getId(),true);
                    }
                }
//                bulletinMessageService.editBulletinMessage(bulletinEntity,userIds);
            }else {
                if(preBulletin.getBulletinType()==2&&bulletinDTO.getBulletinType()==2){
                    if(StringUtils.isNotEmpty(bulletinEntity.getNoticeUserIds())){
                        Set<Long> userIds = Arrays.stream(bulletinEntity.getNoticeUserIds().split(",")).map(Long::parseLong).collect(Collectors.toSet());
                        bulletinReadService.edit(userIds,bulletinDTO.getId(),true);
                    }
                    Set<Long> userIds =diff(bulletinEntity.getNoticeUserIds(),preBulletin.getNoticeUserIds());
//                    bulletinMessageService.editBulletinMessage(bulletinEntity,userIds);
                } else {
                    Set<Long> userIds= new HashSet<>();
                    if(bulletinEntity.getBulletinType()==1){
                        //查询所有人员
                        List<UserEntity> userEntities = userService.activeUsers();
                        userIds = userEntities.stream().map(UserEntity::getId).collect(Collectors.toSet());
                        bulletinReadService.edit(userIds,bulletinDTO.getId(),true);
                    }else {
                        if(StringUtils.isNotEmpty(bulletinEntity.getNoticeUserIds())){
                            userIds = Arrays.stream(bulletinEntity.getNoticeUserIds().split(",")).map(Long::parseLong).collect(Collectors.toSet());
                            bulletinReadService.edit(userIds,bulletinDTO.getId(),true);
                        }
                    }
//                    bulletinMessageService.editBulletinMessage(bulletinEntity,userIds);
                }
            }
            String remindMode = bulletinEntity.getRemindMode();
            //发送消息
            if (bulletinEntity.getBulletinType() == 1){
                assembleService.sendBulletinMessages(bulletinEntity.getId(),"ADD_BULLETIN",remindMode);
            }else {
                Set<Long> toUserIds = new HashSet<>(bulletinDTO.getNoticeUserIdList());
                assembleService.sendBulletinMessages(bulletinEntity.getId(),"ADD_BULLETIN",toUserIds,remindMode);
            }
            return Result.result("公告修改成功");
        }else {
            return Result.error("公告修改失败");
        }
    }

    /**
     * 求newUserIds 有 preUserIds 没有的id
     * @param newUserIds
     * @param preUserIds
     * @return
     */
    private Set<Long> diff(String newUserIds, String preUserIds) {
        if(StringUtils.isBlank(newUserIds)){
            return  new HashSet<>();
        }
        Set<Long> newUserSet = Arrays.stream(newUserIds.split(",")).map(Long::parseLong).collect(Collectors.toSet());
        if(StringUtils.isBlank(preUserIds)){
            return newUserSet;
        }
        Set<Long> preUserSet = Arrays.stream(preUserIds.split(",")).map(Long::parseLong).collect(Collectors.toSet());
        return newUserSet.stream().filter((t)->!preUserSet.contains(t)).collect(Collectors.toSet());
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> delete(Long bulletinId) {
        //超管 和创建者可以删除
        LoginUser loginUser = LoginUserUtil.getLoginUser();
/*        UserRoleType userRole = userRoleService.getUserRole(loginUser);
        BulletinEntity bulletin = this.getById(bulletinId);
        if(bulletin==null){
            return Result.error("公告不存在！");
        }
        //只有超管和创建者可以删除
        if(!Objects.equals(userRole,UserRoleType.Admin)&&!Objects.equals(loginUser.getId(),bulletin.getCreateBy())){
            return Result.error("沒有权限！");
        }*/
        LambdaUpdateWrapper<BulletinEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BulletinEntity::getId, bulletinId);
        updateWrapper.set(BulletinEntity::getIsDelete, CommonConstant.DEL_FLAG_1);
        boolean isOk = this.update(updateWrapper);
        if(isOk) {
            //删除read 记录
            bulletinReadService.delete(bulletinId);
            return Result.result("删除成功！");
        }
        return Result.error("删除失败!");
    }

    @Override
    public Result<?> listVO(BulletinSearchDTO bulletinSearchDTO) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        IPage<BulletinVO> page = new Page<>();
        // 超管能查出所有公告
        // if(loginUser.getRoleType()==UserRoleType.Admin){
        //     LambdaQueryWrapper<BulletinEntity> wrapper = Wrappers.lambdaQuery();
        //     if(!Objects.isNull(bulletinSearchDTO.getStartDate())){
        //         wrapper.ge(BulletinEntity::getCreateTime, LocalDateTime.of(bulletinSearchDTO.getStartDate(), LocalTime.MIN));
        //     }
        //     if(!Objects.isNull(bulletinSearchDTO.getEndDate())){
        //         wrapper.le(BulletinEntity::getCreateTime, LocalDateTime.of(bulletinSearchDTO.getEndDate(), LocalTime.MAX));
        //     }
        //     wrapper.eq(bulletinSearchDTO.getId() != null, BulletinEntity::getId, bulletinSearchDTO.getId());
        //     wrapper.eq(BulletinEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        //     wrapper.orderByDesc(BulletinEntity::getId);
        //     IPage<BulletinEntity> tmpPage = page(new Page<>(bulletinSearchDTO.getPageIndex(), bulletinSearchDTO.getPageSize()), wrapper);
        //     page = transToVo(tmpPage);
        // }else {
        page = bulletinMapper.listVO(new Page<>(bulletinSearchDTO.getPageIndex(), bulletinSearchDTO.getPageSize()), bulletinSearchDTO, loginUser.getId());
        // }
        List<BulletinVO> records = page.getRecords();
        List<Long> allUserIds = new ArrayList<>();

        for (BulletinVO record : records) {
            String noticeUserIds = record.getNoticeUserIds();
            if (noticeUserIds != null && !noticeUserIds.isEmpty()) {
                // 使用逗号分割字符串
                String[] userIdArray = noticeUserIds.split(",");
                // 将分割后的 ID 添加到 allUserIds 列表中
                for (String userId : userIdArray) {
                    allUserIds.add(Long.parseLong(userId));
                }
            }

            // 填充 files 字段
            LambdaQueryWrapper<SysResourceEntity> resourceWrapper = Wrappers.lambdaQuery();
            resourceWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.BULLETIN.code);
            resourceWrapper.eq(SysResourceEntity::getResourceTypeId, record.getId());
            resourceWrapper.eq(SysResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            List<SysResourceEntity> sysResourceEntities = sysResourceService.list(resourceWrapper);
            record.setFiles(sysResourceEntities);
        }

        SysBaseField.orgFileds(page.getRecords());
        // 填充创建人头像
        filledCreateUrl(records);
        // 填充是否可编辑
        // filledCanUpdate(records);
        // 填充readVO
        filledReadVO(records);
        // 将查看到的记录更新成已阅读
        updateRead(records);
        // 填充已读统计
        filledReadTotal(records);
        BulletinVO.dictFileds(records);
        BulletinVO.orgFileds(records);
        List<Long> ids = records.stream().map(BulletinVO::getId).collect(Collectors.toList());
        List<RecordCommentVO> commentVOS = recordCommentService.listCommont(Integer.valueOf(120),ids);
        if (!CollectionUtils.isEmpty(commentVOS)) {
            Map<Long, List<RecordCommentVO>> groupMap = commentVOS.stream().collect(Collectors.groupingBy(RecordCommentVO::getRecordId));
            for (BulletinVO bulletin : records) {
                List<RecordCommentVO> vs = groupMap.get(bulletin.getId());
                if (!CollectionUtils.isEmpty(vs)) {
                    canDelete(vs,currentUserId,bulletin.getOwnerBy());
                }
                bulletin.setCommentls(vs);
            }
        }
        return Result.result(page);
    }

    /**
     *
     * @param comments  评论
     * @param currentUserId 当前用户-
     * @param businessOwner 业务归属人
     */
    public void canDelete(List<RecordCommentVO> comments, Long currentUserId, Long businessOwner) {
        if (comments == null || comments.isEmpty()) {
            return;
        }
        for (RecordCommentVO comment : comments) {
            // 判断当前用户是否能删除该评论
            if (currentUserId.equals(businessOwner) || currentUserId.equals(comment.getOwnerBy())) {
                comment.setCanDelete(true);
            } else {
                comment.setCanDelete(false);
            }
            // 如果有子评论，递归处理
            if (comment.getCommentList() != null && !comment.getCommentList().isEmpty()) {
                canDelete(comment.getCommentList(), currentUserId, businessOwner);
            }
        }
    }


    @Override
    public Result<?> unreadCount() {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        LambdaQueryWrapper<BulletinReadEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BulletinReadEntity::getReadUserId,currentUserId);
        wrapper.eq(BulletinReadEntity::getHasRead,false);
        wrapper.eq(BulletinReadEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        int count = bulletinReadService.count(wrapper);
        HashMap<String, Object> resultAttributes = new HashMap<>();
        resultAttributes.put("count",count);
        return Result.result(resultAttributes);
    }

    /**
     * 填充创建人头像
     * @param records
     */
    private void filledCreateUrl(List<BulletinVO> records) {
        Set<Long> userIds = records.stream().map(BulletinVO::getCreateBy).collect(Collectors.toSet());
        List<UserEntity> userListByStaffIds = userService.getUserListByStaffIds(userIds);
        Map<Long, List<UserEntity>> userMap = userListByStaffIds.stream().collect(Collectors.groupingBy(UserEntity::getId));
        records.forEach(
                (record)->{
                    List<UserEntity> users = userMap.get(record.getCreateBy());
                    if(CollectionUtil.isNotEmpty(users)){
                        UserEntity userEntity = users.get(0);
                        record.setStaffName(userEntity.getRealName());
                        record.setStaffPhoto(userEntity.getAvatar());
                    }
                }
        );
    }

    /**
     * 填充是否可以编辑
     * @param records
     */
//    private void filledCanUpdate(List<BulletinVO> records) {
//        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        records.forEach(
//                (record)->{
//                    if(loginUser.getRoleType()==UserRoleType.Admin|| Objects.equals(record.getCreateBy(),loginUser.getId())){
//                        record.setCanUpdate(Boolean.TRUE);
//                        record.setCanDelete(Boolean.TRUE);
//                    }else {
//                        record.setCanUpdate(Boolean.FALSE);
//                        record.setCanDelete(Boolean.FALSE);
//                    }
//                }
//        );
//    }

    private void filledReadTotal(List<BulletinVO> records) {
        records.forEach(
                (record)->{
                    List<BulletinReadVO> readVOs = record.getReadVOs();
                    if(CollectionUtils.isEmpty(readVOs)){
                        record.setReadTotal(0);
                        record.setReadCount(0);
                    }else {
                        Long hasReadCount = readVOs.stream().filter(BulletinReadEntity::getHasRead).count();
                        record.setReadTotal(readVOs.size());
                        record.setReadCount(hasReadCount.intValue());
                    }
                }
        );
    }

    private void updateRead(List<BulletinVO> records) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long curUserId = loginUser.getId();
        Set<Long> readIds = new HashSet<>();
        records.forEach(
                (record)->{
                    List<BulletinReadVO> readVOs = record.getReadVOs();
                    if(readVOs!=null){
                        readVOs.forEach(
                                (readVO)->{
                                    if(!readVO.getHasRead() && Objects.equals(curUserId, readVO.getReadUserId())){
                                        readVO.setHasRead(Boolean.TRUE);
                                        readIds.add(readVO.getId());
                                    }
                                }
                        );
                    }
                }
        );
        if(CollectionUtils.isEmpty(readIds)){
            return;
        }
        LambdaUpdateWrapper<BulletinReadEntity> wrapper = Wrappers.lambdaUpdate();
        wrapper.in(BulletinReadEntity::getId,readIds);
        wrapper.set(BulletinReadEntity::getHasRead,Boolean.TRUE);
        bulletinReadService.update(wrapper);
    }

    private void filledReadVO(List<BulletinVO> records) {
        if(records==null||records.size()==0){
            return;
        }
        //查询阅读
        Set<Long> bulletinIds = records.stream().map(BulletinVO::getId).collect(Collectors.toSet());
        Map<Long,List<BulletinReadVO>> readMap = bulletinReadService.getMapByBulletinIds(bulletinIds);
        if(CollectionUtils.isEmpty(readMap)){
            return;
        }
        records.forEach(
                (record)->{
                    record.setReadVOs(readMap.get(record.getId()));
                }
        );
    }

    private void fillReadVOForDetail(BulletinDetailVO record) {
        if (record == null) {
            return;
        }
        // 查询阅读
        Long bulletinId = record.getId();
        List<BulletinReadVO> readVOs = bulletinReadService.listByBulletinIds(Collections.singleton(bulletinId));
        if (CollectionUtils.isEmpty(readVOs)) {
            return;
        }
        record.setReadVOs(readVOs);
    }

    /**
     * 查找所有通知人id
     * @param bulletinId
     * @return
     */
    private Set<Long> sendMessageUser(Long bulletinId){
        List<BulletinReadVO> bulletinReadVOS = bulletinReadService.listByBulletinById(bulletinId);
        return bulletinReadVOS.stream().map(BulletinReadVO::getReadUserId).collect(Collectors.toSet());
    }
    /**
     * 类型转换
     * @param tmpPage
     * @return
     */
    private IPage<BulletinVO> transToVo(IPage<BulletinEntity> tmpPage) {
        Page<BulletinVO> bulletinPage = new Page<BulletinVO>();
        bulletinPage.setTotal(tmpPage.getTotal());
        bulletinPage.setSize(tmpPage.getSize());
        bulletinPage.setCurrent(tmpPage.getCurrent());
        List<BulletinVO> bulletinVOS = new ArrayList<>();
        List<BulletinEntity> records = tmpPage.getRecords();
        records.forEach(
                (t)->{
                    BulletinVO bulletinVO = new BulletinVO();
                    BeanUtils.copyProperties(t,bulletinVO);
                    bulletinVOS.add(bulletinVO);
                }
        );
        bulletinPage.setRecords(bulletinVOS);
        return bulletinPage;
    }

    private boolean canEdit(Long bulletinId){
//        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        UserRoleType userRole = userRoleService.getUserRole(loginUser);
//        BulletinEntity bulletin = this.getById(bulletinId);
//        if(bulletin==null){
//            return false;
//        }
//        //只有超管和创建者可以删除
//        if(!Objects.equals(userRole,UserRoleType.Admin)&&!Objects.equals(loginUser.getId(),bulletin.getCreateBy())){
//            return false;
//        }
        return true;
    }
}
