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.domian.ThemeCheckDo;
import com.rongwe.scentity.domian.ThemeCheckItemDo;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.JSCommonUtils;
import com.rongwei.sfcommon.sys.dao.DangerousDao;
import com.rongwei.sfcommon.sys.service.SafeCheckSendNotifyService;
import com.rongwei.sfcommon.sys.service.ThemeCheckItemService;
import com.rongwei.sfcommon.sys.service.ThemeCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static com.rongwei.safecommon.utils.SaveConstans.DEFAULT_SEPARATOR;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.*;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.*;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.*;

/**
 * SafeCheckSendNotifyServiceImpl class
 *
 * @author XH
 * @since 2023/12/19
 */
@Service
@Slf4j
public class SafeCheckSendNotifyServiceImpl implements SafeCheckSendNotifyService {
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String VERIFICATION_SYSTEM_CONTENT = "【%s】 整改确认未通过，请您重新验证";
    /**
     * 隐患跟踪任务验证重新整改内容
     */
    public static final String RECTIFICATE_MAIL_CONTENT = "总编号：【%s】 \n 发现时间：【%tF】 \n 发现人：【%s】 \n 发现项：【%s】 \n 限整改期：【%tF】 \n 整改验证未通过，请您重新整改 ";

    public static final String VERIFICATION_REMIND_TEMP = "总编号:【%s】 【%s】\n";
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String VERIFICATION_REMIND_MAIL_CONTENT = "【%s】 已整改完成，请您验证关闭";
    /**
     * 隐患跟踪任务验证完成提醒内容
     */
    public static final String AFFIRM_REMIND_MAIL_CONTENT = "【%s】 已验证完成，请您确认关闭";
    @Autowired
    private DangerousDao dangerousDao;
    @Autowired
    private ThemeCheckService themeCheckService;
    @Autowired
    private ThemeCheckItemService themeCheckItemService;
    @Autowired
    private HiddenDangerTrackServiceImpl hiddenDangerTrackService;

    @Override
    public void inspectionTasks() {
        // 获取所有待检查的检查任务
        List<ThemeCheckItemDo> prepare = themeCheckItemService.list(new LambdaQueryWrapper<ThemeCheckItemDo>()
                .eq(BaseDo::getDeleted, "0").eq(ThemeCheckItemDo::getCheckstatus, "prepare"));
        if (prepare.isEmpty()) {
            log.debug("暂无待检测的任务");
            return;
        }
        // 获取检查计划id
        List<String> themeCheckId = prepare.stream().map(ThemeCheckItemDo::getThemecheckid).collect(Collectors.toList());
        Collection<ThemeCheckDo> themeCheckDos = themeCheckService.listByIds(themeCheckId);
        // 发送提醒的map
        Map<String, String> sendNotifyMap = new HashMap<>();
        prepare.forEach(themeCheckItemDo -> {
            ThemeCheckDo themeCheckDo = themeCheckDos.stream().filter(info -> info.getId().equals(themeCheckItemDo.getThemecheckid())).findFirst().orElse(null);
            if (themeCheckDo == null) {
                return;
            }
            // 任务名称  计划检查时间 区域
            sendNotifyMap.put(String.format(INSPECTION_TASKS_CONTENT, themeCheckDo.getCheckname(), themeCheckDo.getPlanstarttime(),
                            themeCheckDo.getPlanstarttime(), themeCheckItemDo.getCheckworkspart(), themeCheckItemDo.getId()),
                    themeCheckItemDo.getCheckerid());
        });
        sendInspectionTasksNotify(sendNotifyMap);
    }

    /**
     * 危险作业每日处罚提醒
     */
    public void dangerousDailyNotify() {
        List<Map<String, Object>> dangerous = dangerousDao.getDangerousDailyNotify();
        if (dangerous != null) {
            for (Map<String, Object> item : dangerous) {
                String punishPersonnelId = (String) item.get("PUNISHPERSONNELID");
                List<String> personnelIdList = new ArrayList<>();
                personnelIdList.add(punishPersonnelId);
                String jobType = item.get("JOBTYPE") == null ? "" : item.get("JOBTYPE").toString();
                String assignmentTimeStart = item.get("ASSIGNMENTTIMESTART") == null ? "" : item.get("ASSIGNMENTTIMESTART").toString();
                String assignmentTimeEnd = item.get("ASSIGNMENTTIMEEND") == null ? "" : item.get("ASSIGNMENTTIMEEND").toString();
                String penaltyAmount = item.get("PENALTYAMOUNT") == null ? "" : item.get("PENALTYAMOUNT").toString();
                String modifyDate = item.get("MODIFYDATE") == null ? "" : item.get("MODIFYDATE").toString();
                JSCommonUtils.sendNotify(DANGEROUS_TITLE, String.format(DANGEROUS_CONTENT,
                                jobType, assignmentTimeStart, assignmentTimeEnd, penaltyAmount, modifyDate),
                        "", personnelIdList, (String) item.get("ID"), DANGEROUS);
            }
        }
    }

    /**
     * 危险作业处罚提醒
     */
    @Override
    public R sendDangerousTimelyNotify(String id) {
        Map<String, Object> dangerous = dangerousDao.getDangerousNotify(id);
        if (dangerous != null) {
            String punishPersonnelId = (String) dangerous.get("PUNISHPERSONNELID");
            List<String> personnelIdList = new ArrayList<>();
            personnelIdList.add(punishPersonnelId);
            String jobType = dangerous.get("JOBTYPE") == null ? "" : dangerous.get("JOBTYPE").toString();
            String assignmentTimeStart = dangerous.get("ASSIGNMENTTIMESTART") == null ? "" : dangerous.get("ASSIGNMENTTIMESTART").toString();
            String assignmentTimeEnd = dangerous.get("ASSIGNMENTTIMEEND") == null ? "" : dangerous.get("ASSIGNMENTTIMEEND").toString();
            String penaltyAmount = dangerous.get("PENALTYAMOUNT") == null ? "" : dangerous.get("PENALTYAMOUNT").toString();
            String modifyDate = dangerous.get("MODIFYDATE") == null ? "" : dangerous.get("MODIFYDATE").toString();
            JSCommonUtils.sendNotify(DANGEROUS_TITLE, String.format(DANGEROUS_CONTENT,
                            jobType, assignmentTimeStart, assignmentTimeEnd, penaltyAmount, modifyDate),
                    "", personnelIdList, (String) dangerous.get("ID"), DANGEROUS);
        }
        return R.ok();
    }

    /**
     * 检查任务提醒
     */
    public void sendInspectionTasksNotify(Map<String, String> sendNotifyMap) {
        sendNotifyMap.forEach((k, v) -> JSCommonUtils.sendNotify(INSPECTION_TASKS_TITLE, k.split(DEFAULT_SEPARATOR)[0], "",
                Arrays.asList(v), k.split(DEFAULT_SEPARATOR)[1], INSPECTIONTASKS));
    }

    /**
     * 隐患任务提醒
     */
    public void sendDangerTasksNotify(List<HiddenDangerTrackDo> hiddenDangerTrackDos) {
        hiddenDangerTrackDos.forEach((k) -> JSCommonUtils.sendNotify(DANGER_TASKS_TITLE,
                String.format(DANGER_TASKS_CONTENT, k.getWorkshop(), k.getRectificationdate())
                , "",
                new ArrayList<String>() {{
                    add(k.getTrackuserid());
                }}, k.getId(), DANGERTASKS));
    }

    @Override
    public R sendBackSystem(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();
        }
        //发送人
        List<String> userId = new ArrayList<>();
        //发送内容
        String context = null;
        //发送标题
        String title = null;
        String state = map.getOrDefault("state", "");
        if (StringUtils.isBlank(state)) {
            log.error("状态为空");
            return R.ok();
        }
        //判断发送验证还是整改
        if ("20".equals(state)) {
            userId = Arrays.asList(hiddenDangerTrackDo.getTrackuserid().split(","));
            context = String.format(RECTIFICATE_MAIL_CONTENT, hiddenDangerTrackDo.getCode(),
                    hiddenDangerTrackDo.getFindtime(), hiddenDangerTrackDo.getFindusername(),
                    hiddenDangerTrackDo.getHiddendangercontent(), hiddenDangerTrackDo.getRectificationdate());
            title = RECTIFICATION_MAIL_TITLE;

        } else if ("30".equals(state)) {
            userId = Arrays.asList(hiddenDangerTrackDo.getShopfacilitatorid().split(","));
            String verificationRemindTemp = String.format(VERIFICATION_REMIND_TEMP, hiddenDangerTrackDo.getCode(),
                    hiddenDangerTrackDo.getHiddendangercontent());
            context = String.format(VERIFICATION_SYSTEM_CONTENT, verificationRemindTemp);
            title = VERIFICATION_MAIL_TITLE;
        }
        if (userId.size() == 0) {
            log.error("无法找到接收人！");
        }
        JSCommonUtils.sendNotify(title,
                context, null, userId, hiddenDangerTrackDo.getId(), DANGERTASKS);
        return R.ok();
    }


    @Override
    public R submitSystem(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();
        }
        //发送人
        List<String> userId = new ArrayList<>();
        //发送内容
        String context = null;
        //发送标题
        String title = null;
        String state = map.getOrDefault("state", "");
        if (StringUtils.isBlank(state)) {
            log.error("状态为空");
            return R.ok();
        }
        if ("30".equals(state)) {
            userId = Arrays.asList(hiddenDangerTrackDo.getShopfacilitatorid().split(","));
            title = VERIFICATION_MAIL_TITLE;
            String format = String.format(VERIFICATION_REMIND_TEMP, hiddenDangerTrackDo.getCode(),
                    hiddenDangerTrackDo.getHiddendangercontent());
            context = String.format(VERIFICATION_REMIND_MAIL_CONTENT, format);
        } else if ("40".equals(state)) {
            userId = Arrays.asList(hiddenDangerTrackDo.getSafetypromoterid().split(","));
            title = AFFIRM_MAIL_TITLE;
            String format = String.format(VERIFICATION_REMIND_TEMP, hiddenDangerTrackDo.getCode(),
                    hiddenDangerTrackDo.getHiddendangercontent());
            context = String.format(AFFIRM_REMIND_MAIL_CONTENT, format);
        }
        if (userId.size() == 0) {
            log.error("无法找到接收人！");
        }
        JSCommonUtils.sendNotify(title,
                context, null, userId, hiddenDangerTrackDo.getId(), DANGERTASKS);
        return R.ok();
    }

}
