package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.utils.PubFun;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.date.DateUtil;
import com.fs.qw.domain.QwGroupChat;
import com.fs.qw.service.IQwGroupChatService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.ChatSopRuleTimeVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.sop.domain.QwSop;
import com.fs.sop.domain.QwSopTemp;
import com.fs.sop.domain.SopUserLogs;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.QwSopTempMapper;
import com.fs.sop.mapper.SopUserLogsMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class AsyncChatSopService {

    private final QwSopMapper qwSopMapper;
    private final QwSopTempMapper qwSopTempMapper;
    private final SopUserLogsMapper sopUserLogsMapper;
    private final IQwUserService qwUserService;
    private final IQwGroupChatService qwGroupChatService;

    /**
     * 立即执行SOP任务
     */
    @Async("scheduledExecutorService")
    public void executeChatSopByIds(String[] ids) {
        try {
            List<ChatSopRuleTimeVO> ruleTimeVOList = qwSopMapper.executeSopChatByIds(ids);
            List<QwSopTemp> tempList = qwSopTempMapper.selectListByIds(PubFun.listToNewList(ruleTimeVOList, ChatSopRuleTimeVO::getTempId));
            Map<String, QwSopTemp> tempMap = PubFun.listToMapByGroupObject(tempList, QwSopTemp::getId);
            ruleTimeVOList = ruleTimeVOList.stream().filter(e -> tempMap.containsKey(e.getTempId())).collect(Collectors.toList());
            List<QwUserVO> qwUserVOList = qwUserService.selectQwUserVOByIds(ruleTimeVOList.stream().flatMap(e -> Arrays.stream(e.getQwUserIds().split(",")).map(Long::parseLong)).toArray(Long[]::new));
            Map<String, QwUserVO> qwUserMap = PubFun.listToMapByGroupObject(qwUserVOList, QwUserVO::getQwUserId);
            List<QwGroupChat> qwGroupChatList = qwGroupChatService.selectQwGroupChatByChatIds(ruleTimeVOList.stream().flatMap(e -> Arrays.stream(e.getChatId().split(","))).toArray(String[]::new));
            Map<String, QwGroupChat> groupChatMap = PubFun.listToMapByGroupObject(qwGroupChatList, QwGroupChat::getChatId);
            ruleTimeVOList.forEach(ruleTimeVO -> {
                QwSopTemp qwSopTemp = tempMap.get(ruleTimeVO.getTempId());
                if (!qwSopTemp.getStatus().equals("0")) {
                    processInternal(ruleTimeVO, qwSopTemp, qwUserMap, groupChatMap);
                }
                QwSop qwSop = new QwSop();
                qwSop.setStatus(3L);
            });
            qwSopMapper.updateStatusQwSopById2(PubFun.listToNewList(ruleTimeVOList, ChatSopRuleTimeVO::getId));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("立即执行执行失败", e);
        }
    }

    private void processInternal(ChatSopRuleTimeVO timeVO, QwSopTemp temp, Map<String, QwUserVO> qwUserMap, Map<String, QwGroupChat> groupChatMap) {
        if(StringUtils.isNotEmpty(timeVO.getChatId())){
            List<SopUserLogs> list = Arrays.stream(timeVO.getChatId().split(",")).map(e -> {
                SopUserLogs sopUserLogs = new SopUserLogs();
                sopUserLogs.setSopId(timeVO.getId());
                sopUserLogs.setSopTempId(temp.getId());
                QwGroupChat groupChat = groupChatMap.get(e);
                sopUserLogs.setQwUserId(groupChat.getOwner());
                sopUserLogs.setChatId(e);
                sopUserLogs.setCorpId(timeVO.getCorpId());
                sopUserLogs.setStartTime(DateUtil.formatLocalDate(timeVO.getStartTime()));
                sopUserLogs.setStatus(1);
                QwUserVO qwUserVO = qwUserMap.get(groupChat.getOwner());
                if(qwUserVO != null){
                    sopUserLogs.setUserId(qwUserVO.getId() + "|" + qwUserVO.getCompanyUserId() + "|" + qwUserVO.getCompanyId());
                }
                return sopUserLogs;
            }).collect(Collectors.toList());
            sopUserLogsMapper.batchInsertSopUserLogs(list);
        }
    }

}
