package com.cm.central.control.service.socket.offline.impl;

import com.alibaba.druid.util.StringUtils;
import com.cm.central.control.config.properties.SocketServerProperties;
import com.cm.central.control.manager.SocketServerManager;
import com.cm.central.control.pojo.bos.ClientOffLineNoticeBO;
import com.cm.central.control.pojo.bos.SocketClientBO;
import com.cm.central.control.pojo.dtos.projectleader.ClientProjectLeaderDTO;
import com.cm.central.control.service.BaseService;
import com.cm.central.control.service.client.IClientService;
import com.cm.central.control.service.projectleader.IProjectLeaderService;
import com.cm.central.control.service.socket.offline.IOffLineService;
import com.cm.common.constants.ISystemConstant;
import com.cm.manager.sms.pojo.vos.email.EmailVO;
import com.cm.manager.sms.service.IEmailService;
import com.cm.manager.sms.service.ISmsService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: OffLineServiceImpl
 * @Description: 离线业务
 * @Author: WangGeng
 * @Date: 2020/7/31 8:51 下午
 * @Version: 1.0
 **/
@Service
public class OffLineServiceImpl extends BaseService implements IOffLineService {

    @Autowired
    private SocketServerProperties socketServerProperties;
    @Autowired
    private IClientService clientService;
    @Autowired
    private IProjectLeaderService projectLeaderService;
    @Autowired
    private IEmailService emailService;
    @Autowired
    private ISmsService smsService;

    @Override
    public void checkOfflineClientAndSendEmail() throws Exception {
        // 获取当前离线的客户端
        List<SocketClientBO> socketClientBOs = SocketServerManager.getInstance().listOffLineClient();
        if (socketClientBOs.isEmpty()) {
            LOG.debug("当前无离线客户端");
            return;
        }
        boolean canNotice = StringUtils.equalsIgnoreCase(NOTICE_TYPE_EMAIL, socketServerProperties.getOfflineNoticeType());
        if (!canNotice) {
            LOG.debug("通知类型设置错误，目前只支持email");
            return;
        }
        Map<String, List<String>> noticeMap = new HashMap<>(16);
        // 构建通知通知内容
        for (SocketClientBO socketClientBO : socketClientBOs) {
            int emailNoticeCount = socketClientBO.getEmailNoticeCount();
            if (emailNoticeCount >= socketServerProperties.getOfflineNoticeCount()) {
                // 超过通知次数的不再通知
                continue;
            }
            if (System.currentTimeMillis() - socketClientBO.getLastTime() <= socketServerProperties.getOfflineNoticeMinute() * 60000) {
                // 没有超过提醒时间的不通知
                continue;
            }
            // 查询客户端负责人
            ClientProjectLeaderDTO clientProjectLeaderDTO = projectLeaderService.getProjectLeaderByClientId(socketClientBO.getClientId());
            if (clientProjectLeaderDTO == null) {
                LOG.debug("ClientId: {}，没有设置项目负责人", socketClientBO.getClientId());
                continue;
            }
            String emailKey = clientProjectLeaderDTO.getLeaderEmail();
            StringBuilder noticeContentSB = new StringBuilder();
            noticeContentSB.append("<tr><td>").append(clientProjectLeaderDTO.getClientName()).append("</td><td>")
                    .append(clientProjectLeaderDTO.getCustomerName()).append("</td><td>").append(clientProjectLeaderDTO.getServerIp())
                    .append("</td><td>").append(new DateTime(socketClientBO.getLastTime()).toString(ISystemConstant.DATE_FORMATTER_YYYY_MM_DD_HH_MM_SS))
                    .append("</td></tr>");
            List<String> noticeList = noticeMap.get(emailKey);
            if (noticeList == null) {
                noticeList = new ArrayList<>();
                // 列表的第一个是项目经理
                noticeList.add(clientProjectLeaderDTO.getLeaderName());
                noticeMap.put(emailKey, noticeList);
            }
            noticeList.add(noticeContentSB.toString());
            socketClientBO.setEmailNoticeCount(emailNoticeCount + 1);
        }
        sendNoticeEmail(noticeMap);
    }

    /**
     * 发送邮件
     *
     * @param noticeMap
     * @throws Exception
     */
    private void sendNoticeEmail(Map<String, List<String>> noticeMap) throws Exception {
        if (noticeMap.isEmpty()) {
            LOG.debug("无离线通知邮件发送");
            return;
        }
        for (Map.Entry<String, List<String>> notice : noticeMap.entrySet()) {
            String receiverEmail = notice.getKey();
            StringBuilder noticeContentTable = new StringBuilder();
            noticeContentTable.append("<div>").append(notice.getValue().get(0)).append("，您好").append("</div>");
            noticeContentTable.append("<div>").append("您所负责的项目出现异常离线情况，请及时处理，如果是主动离线请忽略</div><br/>");
            noticeContentTable.append("<div>详细情况见下表：</div><br/>");
            noticeContentTable.append("<table border=\"1\" cellspacing=\"0\">");
            noticeContentTable.append("<thead><tr><th>系统</th><th>所属客户</th><th>访问地址</th><th>离线时间</th></thread>");
            noticeContentTable.append("<tbody>");
            notice.getValue().remove(0);
            for (String tbodyTr : notice.getValue()) {
                noticeContentTable.append(tbodyTr);
            }
            noticeContentTable.append("</tbody>");
            noticeContentTable.append("</table>");
            EmailVO emailVO = new EmailVO();
            emailVO.setEmailReceiver(receiverEmail);
            emailVO.setEmailSubject("项目离线通知");
            emailVO.setEmailContent(noticeContentTable.toString());
            emailVO.setEmailType("2");
            emailService.saveAndSendSystemEmail(emailVO);
        }
    }

}
