package org.dromara.wflow.workflow.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.biz.domain.ActHiTaskinst;
import org.dromara.biz.domain.BizTask;
import org.dromara.biz.domain.BizTaskWork;
import org.dromara.biz.domain.bo.BizTaskFeedbackBo;
import org.dromara.biz.domain.bo.BizTaskWorkBo;
import org.dromara.biz.domain.vo.BizTaskVo;
import org.dromara.biz.domain.vo.BizTaskWorkVo;
import org.dromara.biz.mapper.ActHiTaskinstMapper;
import org.dromara.biz.mapper.BizTaskMapper;
import org.dromara.biz.mapper.BizTaskWorkMapper;
import org.dromara.biz.service.IBizTaskFeedbackService;
import org.dromara.biz.service.IBizTaskLogService;
import org.dromara.biz.service.IBizTaskService;
import org.dromara.biz.service.IBizTaskWorkService;
import org.dromara.common.core.config.properties.ImServerProperties;
import org.dromara.common.core.constant.WflowContants;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.im.domain.ImGroup;
import org.dromara.im.domain.dto.GroupInviteDTO;
import org.dromara.im.domain.dto.GroupMessageDTO;
import org.dromara.im.mapper.ImGroupMapper;
import org.dromara.im.mapper.ImGroupMemberMapper;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysRoleMapper;
import org.dromara.system.mapper.SysUserRoleMapper;
import org.dromara.system.service.ISysDeptService;
import org.dromara.system.service.ISysOssService;
import org.dromara.system.service.ISysUserService;
import org.dromara.wflow.bean.vo.UserVo;
import org.dromara.wflow.minio.util.FileUtil;
import org.dromara.wflow.service.OrgRepositoryService;
import org.dromara.wflow.workflow.bean.bo.RuansiTaskFeedbackBo;
import org.dromara.wflow.workflow.bean.bo.RuansiTaskXiaFaBo;
import org.dromara.wflow.workflow.bean.bo.RuansiTaskXiaFaMJBo;
import org.dromara.wflow.workflow.bean.dto.NotifyDto;
import org.dromara.wflow.workflow.bean.process.enums.BizTaskLogTypeEnum;
import org.dromara.wflow.workflow.service.NotifyService;
import org.dromara.wflow.workflow.service.RuanseeBizTaskWorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class RuanseeBizTaskWorkServiceImpl implements RuanseeBizTaskWorkService {

    @Autowired
    private IBizTaskWorkService bizTaskWorkService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IBizTaskLogService bizTaskLogService;

    @Autowired
    private ISysOssService sysOssService;

    @Autowired
    private BizTaskMapper bizTaskMapper;

    @Autowired
    private IBizTaskService bizTaskService;

    @Autowired
    private BizTaskWorkMapper bizTaskWorkMapper;

    @Autowired
    private IBizTaskFeedbackService bizTaskFeedbackService;

    @Autowired
    private ActHiTaskinstMapper actHiTaskinstMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ImServerProperties imServerProperties;

    private static final String PC_CLIENT_ID = "e5cd7e4891bf95d1d19206ce24a7b32e";

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ImGroupMapper imGroupMapper;

    @Autowired
    private ImGroupMemberMapper imGroupMemberMapper;

    @Autowired
    private OrgRepositoryService orgRepositoryService;

    @Autowired
    private NotifyService notifyService;

    @Override
    public Boolean xiafa(RuansiTaskXiaFaBo xiaFaBo) {
//        List<RuansiTaskXiaFaBo.CapacityAndPoliceNo> depts = xiaFaBo.getDepts();
        BizTask bizTask = bizTaskMapper.selectByTaskNo(xiaFaBo.getTaskNo());
        List<Long> userIds = xiaFaBo.getUserIds();

        int successCount = 0;
        for (Long userId : userIds) {
            UserVo userVo = orgRepositoryService.getUserDetail(userId.toString());
            if (ObjectUtil.isNull(userVo)) {
                log.error("用户不存在：{}", userId);
                continue;
            }
            BizTaskWorkBo bizTaskWorkBo = new BizTaskWorkBo();
            bizTaskWorkBo.setTaskNo(xiaFaBo.getTaskNo());
            bizTaskWorkBo.setDeptId(userVo.getDeptId());
            if (CollectionUtil.isNotEmpty(userVo.getDepts())) {
                bizTaskWorkBo.setDeptName(userVo.getDepts().get(0));
            }
            bizTaskWorkBo.setSponsorId(userId);
//            SysUserVo sysUserVo = sysUserService.selectUserById(userId);
            bizTaskWorkBo.setSponsorName(userVo.getNickName());

//            bizTaskWorkBo.setCapacityId(entity.getCapacityIds().toString());
            bizTaskWorkBo.setCreateTime(new Date());
            if (CollectionUtil.isNotEmpty(xiaFaBo.getOssId())) {
//                bizTaskWorkBo.setOssId(String.join(",", xiaFaBo.getOssId()));
                List<Long> ossIdList = xiaFaBo.getOssId(); // 假设返回类型为 List<Long>
                String result = ossIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                bizTaskWorkBo.setOssId(result);
            }
            bizTaskWorkBo.setStatus(WflowContants.BIZ_TASK_WORK_STATUS_TO_POLICE_QIANSHOU);//待民警签收
            bizTaskWorkBo.setWorkContent(xiaFaBo.getContent());
            Boolean aBoolean = bizTaskWorkService.insertByBo(bizTaskWorkBo);
            if (aBoolean) {
                successCount++;
            }
        }
        StringJoiner imageUrlJoiner = new StringJoiner(",");
        StringJoiner fileUrlJoiner = new StringJoiner(",");
        if (CollectionUtil.isNotEmpty(xiaFaBo.getOssId())) {
            List<SysOssVo> sysOssVos = sysOssService.listByIds(xiaFaBo.getOssId());
            for (SysOssVo sysOssVo : sysOssVos) {
                String url = sysOssVo.getUrl();
                if (FileUtil.isImage(sysOssVo.getFileName())) {
                    imageUrlJoiner.add(url);
                } else {
                    fileUrlJoiner.add(url);
                }
            }
        }
        Boolean save = bizTaskLogService.saveToBizTaskLog(xiaFaBo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.XIAFA.getCode(), BizTaskLogTypeEnum.XIAFA.getDesc(), imageUrlJoiner.toString(), fileUrlJoiner.toString());
        LambdaUpdateWrapper<BizTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BizTask::getTaskNo, xiaFaBo.getTaskNo())
                .set(BizTask::getUpdateTime, new Date())
                .set(BizTask::getStatus, WflowContants.BIZ_TASK_STATUS_TO_POLICE_QIANSHOU);
        int update = bizTaskMapper.update(null, updateWrapper);
        // 任务下发同步创建群聊并邀请相关人员进群
        try {
            createGroupChatAndInviteFriends(xiaFaBo);
        } catch (Exception e) {
            log.error("创建群聊失败", e);
        }
        // 推送消息给代办人
        for (Long userId : userIds) {
            notifyService.pushMessage("您有新的任务待处理",StrUtil.builder("您有新的任务待处理【", bizTask.getTitle(), "】").toString(), userId);
        }
        return (successCount == userIds.size()) && save && update > 0;
    }

    @Override
    public Boolean xiafaMJ(RuansiTaskXiaFaMJBo xiaFaBo) {
        BizTask bizTask = bizTaskMapper.selectByTaskNo(xiaFaBo.getTaskNo());
        BizTaskWork bizTaskWork = bizTaskWorkMapper.selectById(xiaFaBo.getId());
        if (bizTaskWork == null) {
            return false;
        } else {
            StringJoiner imageUrlJoiner = new StringJoiner(",");
            StringJoiner fileUrlJoiner = new StringJoiner(",");
            if (CollectionUtil.isNotEmpty(xiaFaBo.getOssId())) {
                List<SysOssVo> sysOssVos = sysOssService.listByIds(xiaFaBo.getOssId());
                for (SysOssVo sysOssVo : sysOssVos) {
                    String url = sysOssVo.getUrl();
                    if (FileUtil.isImage(sysOssVo.getFileName())) {
                        imageUrlJoiner.add(url);
                    } else {
                        fileUrlJoiner.add(url);
                    }
                }
            }
            bizTaskWork.setSponsorId(xiaFaBo.getSponsorId());
            SysUserVo sysUserVo = sysUserService.selectUserById(xiaFaBo.getSponsorId());
            if (sysUserVo != null) {
                bizTaskWork.setSponsorName(sysUserVo.getNickName());
            }
            bizTaskWork.setWorkContent(xiaFaBo.getContent());
            if (ObjectUtil.isNotEmpty(xiaFaBo.getOssId())) {
//                bizTaskWork.setOssId(String.join(",", xiaFaBo.getOssId().toString()));
                List<Long> ossIdList = xiaFaBo.getOssId(); // 假设返回类型为 List<Long>
                String result = ossIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                bizTaskWork.setOssId(result);
            }
            bizTaskWork.setStatus("1");
            int i = bizTaskWorkMapper.updateById(bizTaskWork);
            //判断是否所有基层单位都已下发，已下发完毕，则修改bizTask状态为40
            boolean bizUpdated = checkUpdateBizTaskStatus(xiaFaBo.getTaskNo());

            Boolean save = bizTaskLogService.saveToBizTaskLog(xiaFaBo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.XIAFA.getCode(), BizTaskLogTypeEnum.XIAFA.getDesc(), imageUrlJoiner.toString(), fileUrlJoiner.toString());
            // 下发民警时同步把相关人员拉近群聊
            ImGroup imGroup = imGroupMapper.selectByTaskNo(xiaFaBo.getTaskNo());
            if (imGroup != null) {
                List<Long> userIds = new ArrayList<>();
                userIds.add(xiaFaBo.getSponsorId());
                userIds.add(LoginHelper.getUserId());
                inviteFriends(imGroup.getId(), userIds);
            }
            // 推送消息给主办人
            notifyService.pushMessage("您有新的任务待处理",StrUtil.builder("您有新的任务待处理【", bizTask.getTitle(), "】").toString(), xiaFaBo.getSponsorId());
            return i > 0 && bizUpdated && save;
        }
    }

    /**
     * 判断是否所有基层单位都已下发，已下发完毕，则修改bizTask状态为40
     */
    private boolean checkUpdateBizTaskStatus(String taskNo) {
        LambdaQueryWrapper<BizTaskWork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizTaskWork::getTaskNo, taskNo);
        queryWrapper.eq(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_TO_DEPT_FENPEI);
        Long count = bizTaskWorkMapper.selectCount(queryWrapper);
        if (count == 0) {
            LambdaUpdateWrapper<BizTask> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BizTask::getTaskNo, taskNo)
                    .set(BizTask::getUpdateTime, new Date())
                    .set(BizTask::getStatus, WflowContants.BIZ_TASK_STATUS_TO_POLICE_QIANSHOU);
            int update = bizTaskMapper.update(null, updateWrapper);
            return update > 0;
//            return bizTaskMapper.updateStatus(taskNo, WflowContants.BIZ_TASK_STATUS_TO_POLICE_QIANSHOU) > 0;
        }
        return true;
    }

    /**
     * 签收工作，bizTask状态改为41(待民警反馈)
     *
     * @param taskNo
     * @return
     */
    @Transactional
    @Override
    public Boolean qianshou(String taskNo) {
        /*LambdaUpdateWrapper<BizTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BizTask::getTaskNo, taskNo)
                .set(BizTask::getStatus, WflowContants.BIZ_TASK_STATUS_TO_POLICE_FEEDBACK);
        int update1 = bizTaskMapper.update(null, updateWrapper);*/
        boolean bizStatusUpdated = updateBizStatusByAllFeedbackQianshou(taskNo);


        Long userId = LoginHelper.getUserId();
        int update2 = bizTaskWorkMapper.update(null, new LambdaUpdateWrapper<BizTaskWork>()
                .eq(BizTaskWork::getTaskNo, taskNo)
                .eq(BizTaskWork::getSponsorId, userId)
                .set(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_TO_POLICE_FEEDBACK)
        );
        Boolean save = bizTaskLogService.saveToBizTaskLog(taskNo, userId.toString(), BizTaskLogTypeEnum.QIANSHOU.getCode(), BizTaskLogTypeEnum.QIANSHOU.getDesc(), null, null);
        return bizStatusUpdated && update2 > 0 && save;
    }

    @Override
    public Boolean feedback(RuansiTaskFeedbackBo bo) {
        BizTask bizTask = bizTaskMapper.selectByTaskNo(bo.getTaskNo());
        String level = bizTask.getLevel();
        String title = bizTask.getTitle();
        StringJoiner imageUrlJoiner = new StringJoiner(",");
        StringJoiner fileUrlJoiner = new StringJoiner(",");
        if (CollectionUtil.isNotEmpty(bo.getOssId())) {
            imageUrlJoiner = new StringJoiner(",");
            fileUrlJoiner = new StringJoiner(",");
            List<SysOssVo> sysOssVos = sysOssService.listByIds(bo.getOssId());
            for (SysOssVo sysOssVo : sysOssVos) {
                String url = sysOssVo.getUrl();
                if (FileUtil.isImage(sysOssVo.getFileName())) {
                    imageUrlJoiner.add(url);
                } else {
                    fileUrlJoiner.add(url);
                }
            }
        }
        // 保存反馈日志
        Boolean taskLogSave = bizTaskLogService.saveToBizTaskLog(bo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.FEEDBACK.getCode(), BizTaskLogTypeEnum.FEEDBACK.getDesc(), imageUrlJoiner.toString(), fileUrlJoiner.toString());
        // 更新bizTaskWork状态为40(待民警反馈)
        int bizTaskWorkUpdateCount = bizTaskWorkMapper.update(null, new LambdaUpdateWrapper<BizTaskWork>()
                .eq(BizTaskWork::getId, bo.getWorkId())
                .set(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_TO_POLICE_COMPLETE)
        );

        // 更新bizTask状态为50(待中心审批)
        //判断一下，所有反馈是否完成，所有反馈都完成，则更新bizTask状态为50(待中心审批)
        updateBizStatusByAllFeedbackDone(bo.getTaskNo());

        //添加记录到biz_task_feedback表
        BizTaskFeedbackBo bizTaskFeedbackBo = saveToFeedBack(bo, imageUrlJoiner, fileUrlJoiner);
        //是否发送到群聊
        Boolean sendToGroup = bo.getSendToGroup();
        if (sendToGroup) {
            //发送到群聊
            BizTaskVo bizTaskVo = bizTaskMapper.selectVoOne(new LambdaQueryWrapper<BizTask>().eq(BizTask::getTaskNo, bo.getTaskNo()));
            boolean b = sendMsgToGroup(bizTaskVo, bo, bizTaskFeedbackBo);
        }
        // 同步推送消息给合战中心领导或者情指中心领导
        if ("普通任务".equals(level) || "敏感任务".equals(level)){
            // 推送给合战中心领导
            Long hezhanleader = sysRoleMapper.selectRoleIdByRoleName("合战中心领导");
            List<Long> hezhanleaderUsers = sysUserRoleMapper.selectUserIdsByRoleId(hezhanleader);
            for (Long hezhanleaderUser : hezhanleaderUsers) {
                notifyService.pushMessage("您有新的任务待处理",StrUtil.builder("您有新的任务待处理【", bizTask.getTitle(), "】").toString(), hezhanleaderUser);
            }
        }else if ("指令任务".equals(level) || "线索核查".equals(level) || "特殊任务".equals(level) || "情指任务".equals(level)){
            // 推送给情指中心领导
            Long qinzhizhongxin = sysRoleMapper.selectRoleIdByRoleName("情指中心");
            List<Long> qinzhizhongxinUsers = sysUserRoleMapper.selectUserIdsByRoleId(qinzhizhongxin);
            for (Long qinzhizhongxinUser : qinzhizhongxinUsers) {
                notifyService.pushMessage("您有新的任务待处理",StrUtil.builder("您有新的任务待处理【", bizTask.getTitle(), "】").toString(), qinzhizhongxinUser);
            }
        }
        return bizTaskWorkUpdateCount > 0 && taskLogSave && ObjectUtil.isNotNull(bizTaskFeedbackBo);
    }

    private boolean sendMsgToGroup(BizTaskVo bizTaskVo, RuansiTaskFeedbackBo ruansiTaskFeedbackBo, BizTaskFeedbackBo taskFeedbackBo) {
        ImGroup imGroup = imGroupMapper.selectByTaskNo(bizTaskVo.getTaskNo());
        if (Objects.isNull(imGroup)) {
            log.error("任务{}对应的群组不存在", bizTaskVo.getTaskNo());
            return false;
        }
        GroupMessageDTO groupMessageDTO = new GroupMessageDTO();
        groupMessageDTO.setGroupId(imGroup.getId());
        Map<String, Object> feedBackMsgMap = new HashMap<>();
        feedBackMsgMap.put("taskName", bizTaskVo.getTitle());
        String feedbackContent = ruansiTaskFeedbackBo.getContent();

        feedBackMsgMap.put("feedbackContent", feedbackContent);
        feedBackMsgMap.put("url", "http://localhost:80?taskNo=" + bizTaskVo.getTaskNo());
        feedBackMsgMap.put("taskNo", bizTaskVo.getTaskNo());
        if (ObjectUtil.isNotNull(taskFeedbackBo)) {
            feedBackMsgMap.put("feedbackId", taskFeedbackBo.getId());
        }
        groupMessageDTO.setContent(JSONUtil.toJsonStr(feedBackMsgMap));
        //反馈消息类型
        groupMessageDTO.setType(5);
        return sendRequestToImServer("/message/group/send", JSONUtil.toJsonStr(groupMessageDTO));
    }

    /**
     * 判断所有反馈是否完成，完成之后才更新状态为50(待中心审批)
     *
     * @param taskNo
     */
    private void updateBizStatusByAllFeedbackDone(String taskNo) {
        BizTaskWorkBo bizTaskWorkBo = new BizTaskWorkBo();
        bizTaskWorkBo.setTaskNo(taskNo);
        List<BizTaskWorkVo> bizTaskWorkVos = bizTaskWorkService.queryList(bizTaskWorkBo);
        // 检查是否存在未完成的任务
        /*boolean hasIncomplete = bizTaskWorkVos.stream().anyMatch(
                bizTaskWorkVo -> !WflowContants.BIZ_TASK_WORK_STATUS_TO_POLICE_COMPLETE.equals(bizTaskWorkVo.getStatus())
        );*/
        boolean canUpdateBizStatus = bizTaskWorkVos.stream()
                .allMatch(v ->
                        "3".equals(v.getStatus()) ||
                                "4".equals(v.getStatus()) ||
                                "5".equals(v.getStatus())
                );

        // 仅在所有任务完成时更新状态
        if (canUpdateBizStatus) {
            bizTaskService.updateStatus(taskNo, WflowContants.BIZ_TASK_STATUS_TO_CENTER_SP);
        }
    }

    /**
     * 判断所有反馈是否签收，签收之后才更新状态为41，已签收待反馈
     *
     * @param taskNo
     */
    private boolean updateBizStatusByAllFeedbackQianshou(String taskNo) {
        BizTaskWorkBo bizTaskWorkBo = new BizTaskWorkBo();
        bizTaskWorkBo.setTaskNo(taskNo);
        List<BizTaskWorkVo> bizTaskWorkVos = bizTaskWorkService.queryList(bizTaskWorkBo);
        // 检查是否存在未签收的任务
        boolean hasIncomplete = bizTaskWorkVos.stream().anyMatch(
                bizTaskWorkVo -> WflowContants.BIZ_TASK_WORK_STATUS_TO_POLICE_QIANSHOU.equals(bizTaskWorkVo.getStatus())
        );
        Boolean aBoolean = false;
        // 仅在所有任务完成时更新状态
        if (!hasIncomplete) {
            aBoolean = bizTaskService.updateStatus(taskNo, WflowContants.BIZ_TASK_STATUS_TO_POLICE_FEEDBACK);
        } else {
            aBoolean = true;
        }
        return aBoolean;
    }

    /**
     * 保存到biz_task_feedback表
     *
     * @param bo
     * @param imageUrlJoiner
     * @param fileUrlJoiner
     * @return
     */
    private BizTaskFeedbackBo saveToFeedBack(RuansiTaskFeedbackBo bo, StringJoiner imageUrlJoiner, StringJoiner fileUrlJoiner) {
        BizTaskFeedbackBo bizTaskFeedbackBo = new BizTaskFeedbackBo();
        bizTaskFeedbackBo.setTaskNo(bo.getTaskNo());
        bizTaskFeedbackBo.setUserId(LoginHelper.getUserId());
        bizTaskFeedbackBo.setUserName(Objects.requireNonNull(LoginHelper.getLoginUser()).getNickname());
        bizTaskFeedbackBo.setContent(bo.getContent());
        bizTaskFeedbackBo.setImage(imageUrlJoiner.toString());
        bizTaskFeedbackBo.setFile(fileUrlJoiner.toString());
        //work_id
        bizTaskFeedbackBo.setWorkId(bo.getWorkId());
        bizTaskFeedbackBo.setCreateTime(new Date());
        Boolean feedBackInsert = bizTaskFeedbackService.insertByBo(bizTaskFeedbackBo);
        if (feedBackInsert) {
            return bizTaskFeedbackBo;
        }
        return null;
    }

    @Override
    public Boolean xiafaByQingZhi(RuansiTaskXiaFaBo xiaFaBo) {
        BizTask bizTask = bizTaskMapper.selectByTaskNo(xiaFaBo.getTaskNo());
        List<Long> userIds = xiaFaBo.getUserIds();
        List<RuansiTaskXiaFaBo.CapacityAndPoliceNo> depts = xiaFaBo.getDepts();
        int successCount = 0;
        for (RuansiTaskXiaFaBo.CapacityAndPoliceNo entity : depts) {
            BizTaskWorkBo bizTaskWorkBo = new BizTaskWorkBo();
            bizTaskWorkBo.setTaskNo(xiaFaBo.getTaskNo());
            bizTaskWorkBo.setDeptId(entity.getDeptId());
            SysDeptVo sysDeptVo = sysDeptService.selectDeptById(Long.valueOf(entity.getDeptId()));
            if (!Objects.isNull(sysDeptVo)) {
                bizTaskWorkBo.setDeptName(sysDeptVo.getDeptName());
            }
            bizTaskWorkBo.setCreateTime(new Date());
            if (CollectionUtil.isNotEmpty(xiaFaBo.getOssId())) {
//                bizTaskWorkBo.setOssId(String.join(",", xiaFaBo.getOssId().toString()));
                List<Long> ossIdList = xiaFaBo.getOssId(); // 假设返回类型为 List<Long>
                String result = ossIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                bizTaskWorkBo.setOssId(result);
            }
            bizTaskWorkBo.setStatus(WflowContants.BIZ_TASK_WORK_STATUS_TO_DEPT_FENPEI);//待民警签收
            bizTaskWorkBo.setWorkContent(xiaFaBo.getContent());
            Boolean aBoolean = bizTaskWorkService.insertByBo(bizTaskWorkBo);
            if (aBoolean) {
                successCount++;
            }
        }
        StringJoiner imageUrlJoiner = new StringJoiner(",");
        StringJoiner fileUrlJoiner = new StringJoiner(",");
        if (CollectionUtil.isNotEmpty(xiaFaBo.getOssId())) {
            List<SysOssVo> sysOssVos = sysOssService.listByIds(xiaFaBo.getOssId());
            for (SysOssVo sysOssVo : sysOssVos) {
                String url = sysOssVo.getUrl();
                if (FileUtil.isImage(sysOssVo.getFileName())) {
                    imageUrlJoiner.add(url);
                } else {
                    fileUrlJoiner.add(url);
                }
            }
        }
        Boolean save = bizTaskLogService.saveToBizTaskLog(xiaFaBo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.XIAFA.getCode(), BizTaskLogTypeEnum.XIAFA.getDesc(), imageUrlJoiner.toString(), fileUrlJoiner.toString());
        LambdaUpdateWrapper<BizTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BizTask::getTaskNo, xiaFaBo.getTaskNo())
                .set(BizTask::getUpdateTime, new Date())
                .set(BizTask::getStatus, WflowContants.BIZ_TASK_STATUS_TO_DEPT_FENPEI);
        int update = bizTaskMapper.update(null, updateWrapper);
        // 任务下发同步创建群聊并邀请相关人员进群
        try {
            createGroupChatAndInviteFriends(xiaFaBo);
        } catch (Exception e) {
            log.error("创建群聊失败", e);
        }
        // 同步推送消息给代办人
        for (Long userId : userIds) {
            notifyService.pushMessage("您有新的任务待处理",StrUtil.builder("您有新的任务待处理【", bizTask.getTitle(), "】").toString(), userId);
        }
        return (successCount == depts.size()) && save && update > 0;
    }

    /**
     * 中心签收、认可反馈单
     *
     * @return
     */
    @Override
    public boolean qianshouFeedBack(BizTaskWorkBo bizTaskWorkBo) {
        int update = bizTaskWorkMapper.update(null, new LambdaUpdateWrapper<BizTaskWork>()
                .eq(BizTaskWork::getId, bizTaskWorkBo.getId())
                .set(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_CENTER_ALREADY_QIANSHOU));
        //
        Boolean logSaved = bizTaskLogService.saveToBizTaskLog(bizTaskWorkBo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.QIANSHOU.getCode(), BizTaskLogTypeEnum.QIANSHOU.getDesc(), null, null);

        LambdaQueryWrapper<BizTaskWork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizTaskWork::getTaskNo, bizTaskWorkBo.getTaskNo());
        queryWrapper.and(wq -> wq.ne(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_CENTER_ALREADY_QIANSHOU));
        Long count = bizTaskWorkMapper.selectCount(queryWrapper);
        if (count == 0) {
            Boolean aBoolean = bizTaskService.updateStatus(bizTaskWorkBo.getTaskNo(), WflowContants.BIZ_TASK_STATUS_CENTER_SP_PASS);
        }

        return update > 0 && logSaved;
    }

    /**
     * 中心签收、驳回反馈单
     *
     * @return
     */
    @Override
    public boolean refuseFeedBack(BizTaskWorkBo bizTaskWorkBo) {
        int update = bizTaskWorkMapper.update(null, new LambdaUpdateWrapper<BizTaskWork>()
                .eq(BizTaskWork::getId, bizTaskWorkBo.getId())
                .set(BizTaskWork::getSpContent, bizTaskWorkBo.getSpContent())
                .set(BizTaskWork::getSpTime, new Date())
                .set(BizTaskWork::getStatus, WflowContants.BIZ_TASK_WORK_STATUS_CENTER_ALREADY_REFUSED));
        //
        Boolean logSaved = bizTaskLogService.saveToBizTaskLog(bizTaskWorkBo.getTaskNo(), LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.APPROVAL.getCode(), BizTaskLogTypeEnum.APPROVAL.getDesc() + "，中心退回，" + bizTaskWorkBo.getSpContent(), null, null);
        return update > 0 && logSaved;
    }

    @Override
    public boolean allDone(String taskNo) {
//        Boolean bizTaskUpdated = bizTaskService.updateStatus(taskNo, WflowContants.BIZ_TASK_STATUS_CENTER_ALL_DWON);
        LambdaUpdateWrapper<BizTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BizTask::getTaskNo, taskNo);
        updateWrapper.set(BizTask::getStatus, WflowContants.BIZ_TASK_STATUS_CENTER_ALL_DWON);
        updateWrapper.set(BizTask::getFinishTime, new Date());
        updateWrapper.set(BizTask::getUpdateTime, new Date());
        int bizTaskUpdated = bizTaskMapper.update(null, updateWrapper);
        Boolean logSaved = bizTaskLogService.saveToBizTaskLog(taskNo, LoginHelper.getUserId().toString(), BizTaskLogTypeEnum.COMPLETE.getCode(), BizTaskLogTypeEnum.COMPLETE.getDesc(), null, null);

        return bizTaskUpdated > 0 && logSaved;
    }

    /**
     * 创建群聊
     *
     * @param xiaFaBo
     */
    private void createGroupChatAndInviteFriends(RuansiTaskXiaFaBo xiaFaBo) {
        // 办事民警id集合
        List<Long> list1 = new ArrayList<>();
        List<RuansiTaskXiaFaBo.CapacityAndPoliceNo> depts = xiaFaBo.getDepts();
        if (depts != null) {
            list1 = depts.stream().map(RuansiTaskXiaFaBo.CapacityAndPoliceNo::getUserId).toList();
        }
        List<Long> userIds = new ArrayList<>();
        if (xiaFaBo.getUserIds() != null) {
            userIds = xiaFaBo.getUserIds();
        }
        List<Long> mergedList = Stream.concat(list1.stream(), userIds.stream())
                .distinct()
                .collect(Collectors.toList());

        LambdaQueryWrapper<ActHiTaskinst> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActHiTaskinst::getProcInstId, xiaFaBo.getTaskNo());
        List<ActHiTaskinst> actHiTaskinsts = actHiTaskinstMapper.selectList(queryWrapper);
        List<String> list2 = actHiTaskinsts.stream().map(ActHiTaskinst::getAssignee).toList();
        // 发起人和审批人id集合
        List<Long> list3 = list2.stream().map(Long::parseLong).toList();
        // 当前用户id
        Long userId = LoginHelper.getUserId();
        // 需邀请进群成员id集合
        List<Long> list4 = new ArrayList<>(Stream.concat(mergedList.stream(), list3.stream()).toList());
        list4.add(userId);
        // 去重
        List<Long> inviteUserIds = list4.stream().distinct().toList();

        LambdaQueryWrapper<BizTask> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(BizTask::getTaskNo, xiaFaBo.getTaskNo());
        BizTask bizTask = bizTaskMapper.selectOne(queryWrapper1);
        // 群聊名称
        String name = bizTask.getTitle();
        // 创建群聊
        ImGroup imGroup = new ImGroup();
        imGroup.setTaskNo(xiaFaBo.getTaskNo());
        imGroup.setName(name);
        imGroup.setOwnerId(5L); // 群主固定为system
        Long groupId = createGroup(imGroup);
        if (groupId != null) {
            log.info("群聊创建成功！");
            inviteFriends(groupId, inviteUserIds);
        } else {
            log.error("群聊创建失败！");
        }
    }

    private boolean sendRequestToImServer(String suffixUrl, String requestBody) {
        HttpRequest createRequest = HttpUtil.createPost(imServerProperties.getServerUrl() + suffixUrl);
        createRequest.header("accessToken", Objects.requireNonNull(redisTemplate.opsForValue().get("im-accessToken")).toString());
        createRequest.header("Clientid", PC_CLIENT_ID);
        createRequest.body(requestBody);
        String body = createRequest.execute().body();
        JSONObject bodyJson = JSONUtil.parseObj(body);

        int code = (int) bodyJson.get("code");
        if (code == 200) {
            log.info("群调用成功！");
            return true;
        } else {
            log.error("群成员邀请失败！code={},msg={}", code, bodyJson.get("msg"));
            return true;
        }
    }

    private Long createGroup(ImGroup imGroup) {
        HttpRequest createRequest = HttpUtil.createPost(imServerProperties.getServerUrl() + "/group/create");
        createRequest.header("accessToken", Objects.requireNonNull(redisTemplate.opsForValue().get("im-accessToken")).toString());
        createRequest.header("Clientid", PC_CLIENT_ID);
        createRequest.body(JSONUtil.toJsonStr(imGroup));
        String body = createRequest.execute().body();
        JSONObject bodyJson = JSONUtil.parseObj(body);
        JSONObject data = (JSONObject) bodyJson.get("data");
        ImGroup newGroup = JSONUtil.toBean(data, ImGroup.class);
        if (newGroup != null) {
            return newGroup.getId();
        } else {
            return null;
        }
    }

    private void inviteFriends(Long groupId, List<Long> inviteUserIds) {
        List<Long> inviteUserIdList = new ArrayList<>();
        // 筛选出未在群中的用户
        for (Long inviteUserId : inviteUserIds) {
            int i = imGroupMemberMapper.checkInGroup(groupId, inviteUserId);
            if (i == 0) {
                inviteUserIdList.add(inviteUserId);
            }
        }
        if (!inviteUserIdList.isEmpty()) {
            GroupInviteDTO groupInviteDTO = new GroupInviteDTO();
            groupInviteDTO.setGroupId(groupId);
            groupInviteDTO.setFriendIds(inviteUserIdList);
            HttpRequest inviteRequest = HttpUtil.createPost(imServerProperties.getServerUrl() + "/group/invite2");
            inviteRequest.header("accessToken", Objects.requireNonNull(redisTemplate.opsForValue().get("im-accessToken")).toString());
            inviteRequest.header("Clientid", PC_CLIENT_ID);
            inviteRequest.body(JSONUtil.toJsonStr(groupInviteDTO));
            String inviteBody = inviteRequest.execute().body();
            JSONObject inviteBodyJson = JSONUtil.parseObj(inviteBody);
            int code = (int) inviteBodyJson.get("code");
            if (code == 200) {
                log.info("群成员邀请成功！");
            } else {
                log.error("群成员邀请失败！code={},msg={}", code, inviteBodyJson.get("msg"));
            }
        }
    }
}
