package com.rongwei.sfcommon.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rongwe.scentity.domian.HiddenDangerTrackDo;
import com.rongwe.scentity.vo.UserMailOrgVo;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwadmincommon.system.service.SysConfigFeignService;
import com.rongwei.rwadmincommon.system.service.SysUserService;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.sfcommon.sys.dao.SaveCheckCommonDao;
import com.rongwei.sfcommon.sys.service.HiddenDangerTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static com.rongwei.sfcommon.utils.MlConstants.SECTION_SUPERVISOR_CODE;

/**
 * HiddenDangerTaskServiceImpl class
 *
 * @author XH
 * @date 2023/10/20
 */
@Service
public class HiddenDangerTaskServiceImpl implements HiddenDangerTaskService {
    /**
     * 隐患跟踪任务整改提现标题
     */
    public static final String RECTIFICATION_MAIL_TITLE = "隐患跟踪任务整改提醒";
    /**
     * 隐患跟踪任务验证提醒标题
     */
    public static final String VERIFICATION_MAIL_TITLE = "隐患跟踪任务验证提醒";
    /**
     * 隐患跟踪任务确认提醒标题
     */
    public static final String AFFIRM_MAIL_TITLE = "隐患跟踪任务确认提醒";
    /**
     * 隐患跟踪任务整改提醒内容
     */
    public static final String RECTIFICATION_MAIL_CONTENT = "总编号：【%s】\n 发现时间：【%tF】\n 发现人：【%s】\n 发现项：【%s】\n限整改期：【%tF】 ";
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String VERIFICATION_REMIND_MAIL_CONTENT = "【%s】 已整改完成，请您验证关闭 ";
    public static final String VERIFICATION_REMIND_TEMP = "总编号:【%s】 【%s】\n";
    /**
     * 隐患跟踪任务验证重新整改内容
     */
    public static final String RECTIFICATE_MAIL_CONTENT = "总编号：【%s】 \n 发现时间：【%tF】 \n 发现人：【%s】 \n 发现项：【%s】 \n 限整改期：【%tF】 \n 整改验证未通过，请您重新整改  ";
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String VERIFICATION_SYSTEM_CONTENT = "【%s】 整改确认未通过，请您重新验证 ";
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String AFFIRM_REMIND_MAIL_CONTENT = "【%s】 已验证完成，请您确认关闭 ";
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private HiddenDangerTrackServiceImpl hiddenDangerTrackService;
    @Autowired
    private SysConfigFeignService sysConfigFeignService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SaveCheckCommonDao saveCheckCommonDao;

    /**
     * 发送隐患跟踪任务整改提醒
     *
     * @param map
     * @return
     */
    @Override
    public R rectificationMail(Map<String, String> map) {
        String id = map.getOrDefault("id", "");
        if (StringUtils.isBlank(id)) {
            log.error("任务ID为空");
            return R.ok();
        }
        HiddenDangerTrackDo hiddenDangerTrackDo = hiddenDangerTrackService.getById(id);
        if (null == hiddenDangerTrackDo) {
            log.error("无法通过id:{}获取到任务列表", id);
            return R.ok();
        }
        // 总编号
        String code = hiddenDangerTrackDo.getCode();
        // 发现时间
        Date findtime = hiddenDangerTrackDo.getFindtime();
        // 指派跟踪人
        String trackuserid = hiddenDangerTrackDo.getTrackuserid();
        if (StringUtils.isBlank(trackuserid)) {
            log.debug("指派跟踪人为空");
            return R.error("维护指派跟踪人!");
        }
        // 指派跟踪人
        SysUserDo userDo = sysUserService.getById(trackuserid);
        if (userDo == null) {
            log.debug("无法通过：{}获取到指派跟踪人", trackuserid);
            return R.error("请维护指派跟踪人!");
        }
        // 发现人
        String findusername = hiddenDangerTrackDo.getFindusername();
        // 隐患内容
        String hiddendangercontent = hiddenDangerTrackDo.getHiddendangercontent();
        // 整改期限
        Date rectificationdate = hiddenDangerTrackDo.getRectificationdate();
        // 组织邮件内容
        String mailContent = String.format(RECTIFICATION_MAIL_CONTENT, code, findtime, findusername, hiddendangercontent, rectificationdate);
        MailDo mail = new MailDo();
        mail.setSubject(RECTIFICATION_MAIL_TITLE);
        mail.setReceiveEmail(new String[]{userDo.getEmail()});
        mail.setNeedTransReceive(false);
        mail.setContent(mailContent);
        try {
            log.info("发送隐患跟踪任务整改提醒邮件!");
            // 邮件发送服务调用
            sysConfigFeignService.sendTextMail(mail);
        } catch (Exception e) {
            log.error("隐患跟踪任务整改提醒邮件发送失败！原因为:{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 隐患跟踪任务验证提醒
     */
    @Override
    public void verifyMail() {
        // 获取所有待验证的任务信息
        List<HiddenDangerTrackDo> hiddenDangerTrackDos = hiddenDangerTrackService.list(new LambdaQueryWrapper<HiddenDangerTrackDo>()
                .eq(BaseDo::getDeleted, "0")
                .eq(HiddenDangerTrackDo::getStatus, "30")
                .isNotNull(HiddenDangerTrackDo::getSafetypromoterid));
        // 用户ID
        List<String> userIds = hiddenDangerTrackDos.stream().map(info -> info.getSafetypromoterid().split(","))
                .flatMap(Arrays::stream).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        // 获取用户信息
        List<SysUserDo> sysUserDos = sysUserService.list(new LambdaQueryWrapper<SysUserDo>().in(SysUserDo::getId, userIds));
        // 防止不同用户拥有相同的邮件 对用户信息按照 邮件进行分组
        Map<String, List<SysUserDo>> userGroupByEmail = sysUserDos.stream()
                .filter(info -> StringUtils.isNotBlank(info.getEmail()))
                .collect(Collectors.groupingBy(SysUserDo::getEmail));
        // 循环邮箱信息
        userGroupByEmail.forEach((k, v) -> {
            // 用户ID
            List<String> userId = v.stream().map(SysUserDo::getId).collect(Collectors.toList());
            // 邮件内容
            StringBuffer mailContentList = new StringBuffer();
            // 找到  该邮箱所属用户和安全促进员中又该用户的 任务信息
            List<HiddenDangerTrackDo> hiddenDangerTrackDoList = hiddenDangerTrackDos.stream()
                    .filter(info -> {
                        List<String> safetyPromoterIds = Arrays.asList(info.getSafetypromoterid().split(","));
                        return userId.stream().filter(safetyPromoterIds::contains).count() != 0;
                    }).collect(Collectors.toList());
            // 生成邮件内容
            hiddenDangerTrackDoList.forEach(data -> {
                mailContentList.append(String.format(VERIFICATION_REMIND_TEMP, data.getCode(), data.getHiddendangercontent()));
            });
            // 发送邮件信息
            MailDo mail = new MailDo();
            mail.setSubject(VERIFICATION_MAIL_TITLE);
            mail.setReceiveEmail(new String[]{k});
            mail.setNeedTransReceive(false);
            mail.setContent(String.format(VERIFICATION_REMIND_MAIL_CONTENT, mailContentList));
            try {
                log.info("发送隐患跟踪任务验证提醒邮件!");
                // 邮件发送服务调用
                sysConfigFeignService.sendTextMail(mail);
            } catch (Exception e) {
                log.error("隐患跟踪任务验证提醒邮件发送失败！原因为:{}", e.getMessage());
                e.printStackTrace();
            }
        });
    }

    @Override
    public R sendBackMail(Map<String, String> map) {
        String id = map.getOrDefault("id", "");
        if (StringUtils.isBlank(id)) {
            log.error("任务ID为空");
            return R.ok();
        }
        HiddenDangerTrackDo hiddenDangerTrackDo = hiddenDangerTrackService.getById(id);
        if (null == hiddenDangerTrackDo) {
            log.error("无法通过id:{}获取到任务列表", id);
            return R.ok();
        }
        Set<String> userEmails = new HashSet<>();
        // 指派跟踪人ID
        String trackuserid = hiddenDangerTrackDo.getTrackuserid();
        if (StringUtils.isNotBlank(trackuserid)) {
            SysUserDo sysUserDo = sysUserService.getById(trackuserid);
            if (sysUserDo != null) {
                userEmails.add(sysUserDo.getEmail());
            }
        }
        String dangerworkpark = hiddenDangerTrackDo.getDangerworkpark();
        // 获取工段信息
        dangerworkpark = StringUtils.isBlank(dangerworkpark) ? "" :
                dangerworkpark.contains("/") ? hiddenDangerTrackDo.getDangerworkpark().split("/")[1] : dangerworkpark;

        // 获取工段主管
        List<UserMailOrgVo> sectionUserList = saveCheckCommonDao.getUserInfoByOrgIdAndRoleCode(Arrays.asList(dangerworkpark), SECTION_SUPERVISOR_CODE);
        if (!sectionUserList.isEmpty()) {
            userEmails.addAll(sectionUserList.stream().map(UserMailOrgVo::getEmail).collect(Collectors.toSet()));
        }
        userEmails = userEmails.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        String[] receiveEmail = userEmails.toArray(new String[userEmails.size()]);
        if (receiveEmail.length == 0) {
            log.error("无法找到收件人邮件信息");
        }
        MailDo mail = new MailDo();
        mail.setSubject(RECTIFICATION_MAIL_TITLE);
        mail.setReceiveEmail(receiveEmail);
        mail.setNeedTransReceive(false);
        mail.setContent(String.format(RECTIFICATE_MAIL_CONTENT, hiddenDangerTrackDo.getCode(),
                hiddenDangerTrackDo.getFindtime(), hiddenDangerTrackDo.getFindusername(),
                hiddenDangerTrackDo.getHiddendangercontent(), hiddenDangerTrackDo.getRectificationdate()));
        try {
            log.info("发送隐患跟踪任务验证提醒邮件!");
            // 邮件发送服务调用
            sysConfigFeignService.sendTextMail(mail);
        } catch (Exception e) {
            log.error("隐患跟踪任务验证提醒邮件发送失败！原因为:{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}
