package com.foreverwin.mesnac.anomaly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalBillMapper;
import com.foreverwin.mesnac.anomaly.model.AbnormalBill;
import com.foreverwin.mesnac.anomaly.service.AbnormalBillService;
import com.foreverwin.mesnac.anomaly.service.AnomalyJobService;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.mapper.MessageMapper;
import com.foreverwin.mesnac.common.model.Message;
import com.foreverwin.mesnac.common.service.MessageService;
import com.foreverwin.mesnac.common.util.ActiveMQUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.listener.mapper.UsrMapper;
import com.foreverwin.mesnac.meapi.mapper.MessageTypeMapper;
import com.foreverwin.mesnac.meapi.mapper.UserGroupMapper;
import com.foreverwin.mesnac.meapi.model.MessageType;
import com.foreverwin.mesnac.meapi.model.NwaUser;
import com.foreverwin.mesnac.meapi.service.NwaUserService;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.modular.core.util.CommonMethods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description TODO
 * @Author zhaojiawei
 * @Since 2021-07-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AnomalyJobServiceImpl implements AnomalyJobService {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private AbnormalBillMapper abnormalBillMapper;

    @Autowired
    private AbnormalBillService abnormalBillService;

    @Autowired
    private ActiveMQUtil activeMQUtil;

    @Autowired
    private NwaUserService nwaUserService;

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private UsrMapper usrMapper;
    
    @Autowired
    private MessageTypeMapper messageTypeMapper; 

    private static Logger logger = LoggerFactory.getLogger(AnomalyJobServiceImpl.class);

    @Override
    public void anomalyJobProcess(String site) {
        LocalDateTime now = LocalDateTime.now();
        String user = CommonMethods.getUser();
        //找到状态为N，并且升级时间大于当前时间
        QueryWrapper<Message> abnormalMessageQueryWrapper = new QueryWrapper<>();
        abnormalMessageQueryWrapper.eq("STATUS","N");
        abnormalMessageQueryWrapper.lt("UP_DATE_TIME",now);
//        AbnormalBill abnormalBill = new AbnormalBill();
        List<Message> abnormalMessages = messageMapper.selectList(abnormalMessageQueryWrapper);
        for(Message _abnormalMessage : abnormalMessages){
            String uuid = UUID.randomUUID().toString();
            Message abnormalMessage = new Message();
            //设置abnormalMessage的handle
            abnormalMessage.setHandle(uuid);
            //设置abnormalMessage的site
            abnormalMessage.setSite(site);
            //设置abnormalMessage的异常单Bo
            abnormalMessage.setObjectBo(_abnormalMessage.getObjectBo());
            //设置abnormalMessage的type
            abnormalMessage.setType(_abnormalMessage.getType());
            //设置abnormalMessage的message_type
            abnormalMessage.setMessageType(_abnormalMessage.getUpMessageType());
            //设置发送用户组和升级用户组
            if(!StringUtil.isBlank(_abnormalMessage.getUpUserGroup())){
                //当前发送用户组就等于升级用户组，升级用户组就等于空
                abnormalMessage.setSendUserGroup(_abnormalMessage.getUpUserGroup());
                abnormalMessage.setUpUserGroup(null);
            }

            //设置发送用户和升级用户
            if(!StringUtil.isBlank(_abnormalMessage.getUpUser())){
                //当前发送用户就等于升级用户，升级用户就等于空
                abnormalMessage.setSendUser(_abnormalMessage.getUpUser());
                abnormalMessage.setUpUser(null);
            }

            AbnormalBill abnormalBill = abnormalBillMapper.selectById(abnormalMessage.getObjectBo());

            //设置UP_DATE_TIME、UP_MESSAGE_TYPE、GRADE、RESPONSE_DATE_TIME、ABNORMAL_NODE、STATUS
            abnormalMessage.setUpMessageType(null);
            abnormalMessage.setUpDateTime(null);

            abnormalMessage.setGrade(_abnormalMessage.getGrade() + 1);
            abnormalMessage.setResponseDateTime(now);
            abnormalMessage.setNode(_abnormalMessage.getNode());
            abnormalMessage.setStatus("Y");
            _abnormalMessage.setStatus("Y");
            //格式化消息
            String message = this.formatMessageJob(abnormalBill,abnormalMessage,site);
            abnormalMessage.setContent(message);

            //设置时间
            abnormalMessage.setCreatedUser(user);
            abnormalMessage.setCreatedDateTime(now);
            abnormalMessage.setModifiedUser(user);
            abnormalMessage.setModifiedDateTime(now);

            List<NwaUser> nwaUsers = null;
            //发送消息
            try{
                nwaUsers = nwaUserService.checkUserGroup(site,abnormalMessage.getSendUserGroup());
                if(nwaUsers == null){
                    logger.info("异常单:"+abnormalBill.getAbnormalNo()+"消息发送失败，错误信息：找不到发送的用户组\n");
                }
            }catch(Exception e){
                logger.info("异常单:"+abnormalBill.getAbnormalNo()+"消息发送失败，错误信息：找不到发送的用户组\n");
            }
            if(nwaUsers != null && nwaUsers.size() <= 0){
                logger.info("异常单:"+abnormalBill.getAbnormalNo()+"消息发送失败，错误信息：发送的用户组下面没有用户\n") ;
            }else{
                List<String> customFieldByUserId = usrMapper.findCustomFieldByUserId(site, nwaUsers);
                if(customFieldByUserId != null && customFieldByUserId.size() <= 0){
                    logger.info("异常单:"+abnormalBill.getAbnormalNo()+"消息发送失败，错误信息：发送的用户组下面的用户的自定义数据没有维护\n");
                }else {
                    StringBuilder sendUsers = new StringBuilder();
                    for (int i = 0; i < Objects.requireNonNull(customFieldByUserId).size(); i++) {
                        if(i == (customFieldByUserId.size() - 1)){
                            sendUsers.append(customFieldByUserId.get(i));
                        }else{
                            sendUsers.append(customFieldByUserId.get(i)).append("|");
                        }
                    }
                    activeMQUtil.wechatSendMessage(sendUsers.toString(),abnormalMessage.getContent());
                }
            }
            //保存升级的消息类型
            messageService.saveOrUpdate(abnormalMessage);
            //保存原先的消息类型，让原先的消息类型的stauts改为Y
            messageService.saveOrUpdate(_abnormalMessage);
        }
    }

    @Override
    public String formatMessageJob(AbnormalBill abnormalBill, Message message, String site) {
        //找到消息内容
        MessageType messageTypeEntity = new MessageType();
        messageTypeEntity.setSite(site);
        messageTypeEntity.setMessageType(message.getMessageType());
        QueryWrapper<MessageType> messageTypeQueryWrapper = new QueryWrapper<MessageType>();
        messageTypeQueryWrapper.setEntity(messageTypeEntity);
        MessageType sendMessageType = messageTypeMapper.selectOne(messageTypeQueryWrapper);
        if(sendMessageType == null){
           // return "消息类型:"+message.getMessageType()+"找不到，异常单为:"+abnormalBill.getAbnormalNo()+",状态为:"+abnormalBill.getStatus();
            return "找不到消息类型!!!";
        }
        //找到要替换的消息
        Map<String, String> replaceMessage = abnormalBillMapper.findReplaceMessageByAbnormal(abnormalBill);
        //找到用户组下的所有用户
        List<NwaUser> nwaUsers = nwaUserService.checkUserGroup(site, message.getSendUserGroup());
        String user = "";
        for (int i = 0; i < nwaUsers.size(); i++) {
            if(i == (nwaUsers.size() - 1)){
                user += nwaUsers.get(i).getFullName()+",";
            }else {
                user += nwaUsers.get(i).getFullName()+"、";
            }
        }
        //根据异常消息的节点来判断所处的状态
        if(Constants.ABNORMAL_MESSAGE_REPORT.equals(message.getNode())){
            user += "现已超时未响应。";
        }else if(Constants.ABNORMAL_MESSAGE_RESPONSE_DUTY.equals(message.getNode())){
            //走判责提交
            user += "现已判责提交（责任划分）超时。";
        }else if(Constants.ABNORMAL_MESSAGE_RESPONSE_RESOLVE.equals(message.getNode())){
            //走解决方案
            user += "现已方案确认超时。";
        }
        replaceMessage.put("USER",user);
        String messageBody = sendMessageType.getBody();
        //格式化之后的消息
        return StringUtils.format(messageBody, replaceMessage);
    }
}
