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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwe.scentity.domian.HiddenDangerTrackDo;
import com.rongwe.scentity.vo.HiddenDangerTrackVo;
import com.rongwei.rwadmincommon.system.domain.SysRoleDo;
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.QueryPar;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.sfcommon.sys.dao.HiddenDangerTrackDao;
import com.rongwei.sfcommon.sys.dao.ThemeCheckItemDao;
import com.rongwei.sfcommon.sys.service.HiddenDangerTrackService;
import com.rongwei.sfcommon.utils.MlConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

@Service("hiddenDangerTrackService")
public class HiddenDangerTrackServiceImpl extends ServiceImpl<HiddenDangerTrackDao, HiddenDangerTrackDo> implements HiddenDangerTrackService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysConfigFeignService sysConfigFeignService;
    @Autowired
    private HiddenDangerTrackDao hiddenDangerTrackDao;
    @Autowired
    private ThemeCheckItemDao themeCheckItemDao;
    // 邮件标题
    public static final String MAIL_TITLE = "隐患跟踪任务待处理";
    // 邮件内容
    public static final String MAIL_CONTENT = "您好,你有新的隐患跟踪任务待处理,限整改日期【%s】,请登录安全平台尽快处理;\n ";

    public static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 隐患跟踪任务列表
     * @param queryMap
     * @return
     */
    @Override
    public IPage<HiddenDangerTrackVo> checkTaskList(QueryPar<Map<String,Object>> queryMap){
        // userid:当前登录用户ID  status:任务状态（10：已关闭；20：未关闭）
        Map<String,Object> map = queryMap.getParameter();
        return hiddenDangerTrackDao.checkTaskList(queryMap.getPage(),map.get("userid").toString(), map.get("status").toString());
    }

    /**
     * 定时提醒限整改日期
     */
    public void limitedRectificationWarn(){
        // 任务查询
        Map<String,Object> parmap = new HashMap<>();
        parmap.put("STATUS", MlConstants.HIDDEN_DANGER_STATUS_NOTCLOSE);
        List<HiddenDangerTrackDo> hiddenDangerTracks = (List<HiddenDangerTrackDo>)this.listByMap(parmap);
        if(hiddenDangerTracks != null && hiddenDangerTracks.size()>0){
            // 提醒任务集合
            Map<String,Map<String,List<HiddenDangerTrackDo>>> warnMap = new HashMap<>();

            for(HiddenDangerTrackDo hiddenDangerTrack:hiddenDangerTracks){
                //限整改日期
                Date rectificationdate = hiddenDangerTrack.getRectificationdate();
                String trackuserid = hiddenDangerTrack.getTrackuserid();
                if(rectificationdate != null && StringUtils.isNotEmpty(trackuserid)){
                    Date bg = DateUtil.parseDate(DateUtil.format(new Date(),"yyyy-MM-dd"));
                    Date end = DateUtil.parseDate(DateUtil.format(rectificationdate,"yyyy-MM-dd"));
                    Long bday = DateUtil.between(bg,end, DateUnit.DAY,false);
                    // 预警提醒邮件发送
                    if(bday == 1){
                        constructWarnMap(warnMap,trackuserid,hiddenDangerTrack,"1");
                    }else if(bday == 3){
                        constructWarnMap(warnMap,trackuserid,hiddenDangerTrack,"3");
                    }else if(bday < 0){
                        constructWarnMap(warnMap,trackuserid,hiddenDangerTrack,"delay");
                    }
                    // 更新预警状态
                    if(bday > 1 && bday <= 3){
                        hiddenDangerTrack.setWarnstatus("3天");
                    }else if(bday <= 1 && bday >= 0){
                        hiddenDangerTrack.setWarnstatus("1天");
                    }else if(bday < 0){
                        hiddenDangerTrack.setWarnstatus("过期");
                    }
                    hiddenDangerTrack.setModifydate(new Date());
                    this.updateById(hiddenDangerTrack);

                }
            }

            // 邮件发送
            if(warnMap.size() > 0){
                warnMap.forEach((k,v)->{
                    if(v.size() > 0){
                        SysUserDo userDo = sysUserService.getById(k);
                        if(userDo != null && StringUtils.isNotEmpty(userDo.getEmail())){
                            MailDo mail = new MailDo();
                            String[] res = {userDo.getEmail()};
                            mail.setReceiveEmail(res);
                            mail.setSubject("隐患跟踪任务提醒");
                            // 邮件内容组装
                            StringBuilder sb = new StringBuilder("您好！\n");
                            if(v.containsKey("1")){
                                sb.append("距离限整改期剩余1天的隐患任务有").append(v.get("1").size()).append("条，\n");
                            }
                            if(v.containsKey("3")){
                                sb.append("距离限整改期剩余3天的隐患任务有").append(v.get("3").size()).append("条，\n");
                            }
                            if(v.containsKey("delay")){
                                sb.append("已延期的隐患任务有").append(v.get("delay").size()).append("条，\n");
                            }
                            sb.append("如已关闭，请尽快登陆系统进行处理! \n");
                            sb.append("详见智能安全监控平台：http://192.168.0.205:8000");
                            // 邮件内容
                            mail.setContent(sb.toString());
                            if(v.containsKey("1")||v.containsKey("3")||v.containsKey("delay")){
                                // 邮件发送
                                sysConfigFeignService.sendTextMail(mail);
                            }
                        }
                    }
                });
            }
        }

    }

    /**
     * 构造提醒人的不通提醒类型的数据
     * @param warnMap
     * @param trackuserid
     * @param hiddenDangerTrack
     * @param warnType 1:距离限整改期1天提醒；3:距离限整改期3天提醒；delay:距离限整改期3天提醒
     */
    private void constructWarnMap(Map<String,Map<String,List<HiddenDangerTrackDo>>> warnMap,String trackuserid,
                                  HiddenDangerTrackDo hiddenDangerTrack,String warnType){
        if(warnMap.containsKey(trackuserid)){
            if(warnMap.get(trackuserid).containsKey(warnType)){
                warnMap.get(trackuserid).get(warnType).add(hiddenDangerTrack);
            }else{
                List<HiddenDangerTrackDo> warns = new ArrayList<>();
                warns.add(hiddenDangerTrack);
                warnMap.get(trackuserid).put(warnType,warns);
            }
        }else{
            Map<String,List<HiddenDangerTrackDo>> warnUser = new HashMap<>();
            warnMap.put(trackuserid,warnUser);

            List<HiddenDangerTrackDo> warns = new ArrayList<>();
            warns.add(hiddenDangerTrack);
            warnMap.get(trackuserid).put("one",warns);
        }
    }

    /**
     * 任务关闭后如果指派跟踪人和原始人不一样则发送邮件
     * @param dataMap
     */
    public void sendMailAfterClose(Map<String,Object> dataMap){
        Object obj = dataMap.get("ID");
        if(obj != null){
            String id = (String)obj;
            HiddenDangerTrackDo hiddenDangerTrack = this.getById(id);
            // 判断是否为关闭、是否修改过指派跟踪人
            if(MlConstants.HIDDEN_DANGER_STATUS_HASCLOSE.equals(hiddenDangerTrack.getStatus()) &&
                    StringUtils.isNotEmpty(hiddenDangerTrack.getTrackuserid()) && StringUtils.isNotEmpty(hiddenDangerTrack.getFirsttrackuserid()) &&
                    !hiddenDangerTrack.getTrackuserid().equals(hiddenDangerTrack.getFirsttrackuserid())){
                // 邮件发送
                // 接收人邮箱地址查询
                String[] userids = hiddenDangerTrack.getFirsttrackuserid().split(",");
                List<SysUserDo> sysUsers = (List<SysUserDo>)sysUserService.listByIds(Arrays.asList(userids));
                List<String> res = new ArrayList<>();
                for(SysUserDo sysUser:sysUsers){
                    if(StringUtils.isNotEmpty(sysUser.getEmail())){
                        res.add(sysUser.getEmail());
                    }
                }
                if(res != null && res.size()>0){
                    MailDo mail = new MailDo();
                    mail.setReceiveEmail(res.toArray(new String[res.size()]));
                    mail.setSubject("跟踪任务关闭提醒");
                    // 邮件内容组装
                    StringBuilder sb = new StringBuilder("总编号 ");
                    sb.append(hiddenDangerTrack.getCode()).append("，隐患内容：").append(hiddenDangerTrack.getHiddendangercontent()).append("，请注意查收，谢谢！\n")
                            .append("详见智能安全监控平台：http://192.168.0.205:8000");
                    // 邮件内容
                    mail.setContent(sb.toString());
                    // 邮件发送
                    sysConfigFeignService.sendTextMail(mail);
                }
            }
        }
    }

    /**
     * 查询所有部门对应的部门主管和spa角色的人
     * @return
     */
    public List<Map<String,Object>> getAllDeptZGSPA(){
        List<Map<String,Object>> list = hiddenDangerTrackDao.getAllDeptZGSPA();
        List<Map<String,Object>> spas = themeCheckItemDao.getGdzgByUserId(null,"spa");

        // spa角色人
        List<SysUserDo> spaList = new ArrayList<>();
        if(spas != null && spas.size()>0){
            for(Map<String,Object> spa:spas){
                SysUserDo userDo = new SysUserDo();
                if(spa.get("USERID") != null){
                    userDo.setId(spa.get("USERID").toString());
                }
                if(spa.get("USERNAME") != null){
                    userDo.setName(spa.get("USERNAME").toString());
                }
                spaList.add(userDo);
            }
        }
        // 工段主管
        if(list != null && list.size()>0){
            for(Map<String,Object> map:list){
                List<SysUserDo> users = new ArrayList<>();
                String[] us = map.get("USERID").toString().split(",");
                String[] usn = map.get("USERNAME").toString().split(",");
                if(us != null && us.length>0){
                    for(int i=0;i<us.length;i++){
                        SysUserDo userDo = new SysUserDo();
                        userDo.setId(us[i]);
                        if(i<usn.length){
                            userDo.setName(usn[i]);
                        }
                        Stream<SysUserDo> tempUsers = users.stream().filter(row -> row.getId().equals(userDo.getId()));
                        if (tempUsers.count() == 0) {
                            users.add(userDo);
                        }

                    }
                }
                users.addAll(spaList);
                map.put("allUsers",users);
            }
        }
        return list;
    }

    /**
     * 根据指标跟踪人获取相应的角色
     *
     * @param ids
     * @return
     */
    @Override
    public Map<String, Object> getTrackUserRoles(List<String> ids) {
        Map<String, Object> map = new HashMap<>();
        if (ids != null && ids.size() > 0) {
            for (String id : ids) {
                List<SysRoleDo> sysRoleDos = hiddenDangerTrackDao.getTrackUserRoles(id);
                map.put(id, sysRoleDos);
            }
        }
        return map;
    }

    /**
     * 发送邮件给跟踪人
     *
     * @param dataMap
     * @return
     */
    @Override
    public R sendMailTostalker(Map<String, Object> dataMap) {
        String id = dataMap.getOrDefault("ID", "").toString();
        if (StringUtils.isBlank(id)) {
            log.error("任务id为空");
            return R.ok();
        }
        // 获取任务管理信息
        HiddenDangerTrackDo hiddenDangerTrackDo = this.getById(id);
        if (hiddenDangerTrackDo == null) {
            log.debug("无法根据Id:{}获取到任务信息", id);
            return R.ok();
        }
        // 获取跟踪人信息
        String trackuserid = hiddenDangerTrackDo.getTrackuserid();
        if (StringUtils.isBlank(trackuserid)) {
            log.debug("无法获取到跟踪人信息");
            return R.ok();
        }
        // 主键ID
        String relationId = hiddenDangerTrackDo.getRelationid();
        if (StringUtils.isBlank(relationId)) {
            log.debug("无法获取到跟踪人信息");
            return R.ok();
        }
        relationId = String.join("','", relationId.split("-"));
        // 校验是否需要发送邮件
        if (themeCheckItemDao.checkSendMail(relationId) == 0) {
            log.debug("不属于经理主管值班检查");
            return R.ok();
        }
        // 用户信息
        List<SysUserDo> sysUserDos = sysUserService.list(new LambdaQueryWrapper<SysUserDo>().in(SysUserDo::getId, trackuserid.split(",")));
        if(sysUserDos.isEmpty()){
            log.debug("无法获取到用户信息");
            return R.ok();
        }
        // 收件人地址
        MailDo mail = new MailDo();
        mail.setReceiveEmail(sysUserDos.stream().map(SysUserDo::getEmail).filter(StringUtils::isNotBlank).toArray(String[]::new));
        mail.setSubject(MAIL_TITLE);
        // 邮件内容
        mail.setContent(String.format(MAIL_CONTENT,DATE_FORMATTER.format(hiddenDangerTrackDo.getRectificationdate())));
        // 邮件发送
        sysConfigFeignService.sendTextMail(mail);
        return R.ok();
    }
}
