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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.system.SystemUtil;
import com.rongwe.scentity.domian.CheckItemsDo;
import com.rongwe.scentity.domian.CheckItemsPartsDo;
import com.rongwe.scentity.domian.HiddenDangerTrackDo;
import com.rongwei.commonservice.serial.service.SysSerialNumberService;
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.utils.SecurityUtil;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import com.rongwei.sfcommon.sys.dao.CheckItemsPartsDao;
import com.rongwei.sfcommon.sys.service.CheckItemsPartsService;
import com.rongwei.sfcommon.sys.service.CheckItemsService;
import com.rongwei.sfcommon.sys.service.HiddenDangerTrackService;
import com.rongwei.sfcommon.utils.MlConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

@Service("checkItemsPartsService")
public class CheckItemsPartsServiceImpl extends ServiceImpl<CheckItemsPartsDao, CheckItemsPartsDo> implements CheckItemsPartsService {

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

    @Autowired
    private HiddenDangerTrackService hiddenDangerTrackService;
    @Autowired
    private CheckItemsService checkItemsService;
    @Autowired
    private SysConfigFeignService sysConfigFeignService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysSerialNumberService sysSerialNumberService;

    /**
     * 定时检查设备配件是否过期
     * 如过期则发送邮件提醒以及生成隐患跟踪任务
     * @return
     */
    public void partExpireWarn(){
        List<CheckItemsPartsDo> checkItemsPartss = this.list();
        List<CheckItemsPartsDo> waitWarns = new ArrayList<>();
        // 邮件接收人
        Map<String,MailDo> reciveMails = new HashMap<>();

        if(checkItemsPartss != null && checkItemsPartss.size()>0){
            for(CheckItemsPartsDo checkItemsParts:checkItemsPartss){
                try{
                    // 设备信息
                    CheckItemsDo checkItemsDo = checkItemsService.getById(checkItemsParts.getCheckitemid());

                    int eWarnDays = checkItemsParts.getEarlywarningdays();
                    if(checkItemsParts.getYearlyinspectiondate() == null){
                        logger.info("设备配件ID："+checkItemsParts.getId()+";没有年检日期");
                        continue;
                    }
                    long betweenDay = DateUtil.between(new Date(),checkItemsParts.getYearlyinspectiondate(), DateUnit.DAY,false);
                    // 小于等于提前预警天数,并且未过期 发送邮件并生成跟踪任务
                    if(betweenDay <= eWarnDays && betweenDay >= 0){
                        // 判断是否已存在此跟踪任务
                        Map<String,Object> queryMap = new HashMap<>();
                        // 根据任务来源、关联ID、隐患内容确定是否存在此次年检跟踪任务
                        queryMap.put("DANGERSOURCE", MlConstants.DANGER_SOURCE_YEARCHECK);
                        queryMap.put("RELATIONID",checkItemsParts.getId());
                        if(checkItemsDo == null){
                            continue;
                        }
                        String hiddendangercontent = checkItemsDo.getCheckitemname()+checkItemsParts.getPartname()+DateUtil.format(checkItemsParts.getYearlyinspectiondate(),"yyyy-MM-dd");
                        queryMap.put("HIDDENDANGERCONTENT",hiddendangercontent);
                        List<HiddenDangerTrackDo> hiddenDangerTracks = (List<HiddenDangerTrackDo>)hiddenDangerTrackService.listByMap(queryMap);
                        // 没有此次年检跟踪任务，则生成新的跟踪任务
                        if(hiddenDangerTracks == null || hiddenDangerTracks.size() == 0){
                            HiddenDangerTrackDo hiddenDangerTrack = new HiddenDangerTrackDo();
                            hiddenDangerTrack.setId(SecurityUtil.getUUID());
                            hiddenDangerTrack.setFindtime(new Date());
                            // 总编号
                            SysSerialVo sysSerialVo = new SysSerialVo();
                            sysSerialVo.setRuleTemplateStr("@{date:yyyyMMdd}@{serialNumber:#000000}");
                            sysSerialVo.setModulecode("asp_hidden_danger_track_CODE");
                            hiddenDangerTrack.setCode(sysSerialNumberService.getCodeByTemplate(sysSerialVo));
                            // 限整改日期
                            hiddenDangerTrack.setRectificationdate(DateUtil.offsetDay(new Date(),7));
                            hiddenDangerTrack.setTrackuserid(checkItemsParts.getRecipientids());
                            hiddenDangerTrack.setTrackusername(checkItemsParts.getRecipientnames());
                            // 设置最初指派跟踪人
                            hiddenDangerTrack.setFirsttrackuserid(checkItemsParts.getRecipientids());
                            hiddenDangerTrack.setFirsttrackusername(checkItemsParts.getRecipientnames());
                            // 设置归属工段
                            if(StringUtils.isNotEmpty(checkItemsDo.getChargeorgid())){
//                                String[] orgids = checkItemsDo.getChargeorgid().split("/");
                                hiddenDangerTrack.setDangerworkpark(checkItemsDo.getChargeorgid());
                            }
                            if(StringUtils.isNotEmpty(checkItemsDo.getChargeorgname())){
//                                String[] orgnames = checkItemsDo.getChargeorgname().split("/");
                                hiddenDangerTrack.setDangerworkparkname(checkItemsDo.getChargeorgname());
                            }
                            hiddenDangerTrack.setHiddendangercontent(hiddendangercontent);
                            hiddenDangerTrack.setRelationid(checkItemsParts.getId());
                            // 设置任务来源
                            hiddenDangerTrack.setDangersource(MlConstants.DANGER_SOURCE_YEARCHECK);
                            hiddenDangerTrack.setStatus(MlConstants.HIDDEN_DANGER_STATUS_NOTCLOSE);
                            // 隐患类型默认为一般
                            hiddenDangerTrack.setHiddendangertype(MlConstants.HIDDEN_DANGER_TYPE_NORMAL);
                            // 生成新的跟踪任务
                            hiddenDangerTrackService.save(hiddenDangerTrack);
                            // 发送邮件
                            // 接收人查询
                            if(StringUtils.isNotEmpty(checkItemsParts.getRecipientids())){
                                List<SysUserDo> users = (List<SysUserDo>)sysUserService.listByIds(Arrays.asList(checkItemsParts.getRecipientids().split(",")));
                                if(users != null && users.size()>0){
                                    users.forEach(v->{
                                        if(com.rongwei.rwcommon.utils.StringUtils.isNotEmpty(v.getEmail())){
                                            if(reciveMails.get(v.getEmail()) != null){
                                                String contents = "设备编号："+checkItemsDo.getCheckitemcode()+"，设备名称："
                                                        +checkItemsDo.getCheckitemname()+"，配件名称："+checkItemsParts.getPartname()
                                                        +"，年检日期："+DateUtil.format(checkItemsParts.getYearlyinspectiondate(),"yyyy年MM月dd日")+"\n";
                                                reciveMails.get(v.getEmail()).setContent(reciveMails.get(v.getEmail()).getContent()+contents);
                                            }else{
                                                MailDo mail = new MailDo();
                                                String[] ri = {v.getEmail()};
                                                mail.setReceiveEmail(ri);
                                                mail.setSubject("设备年检提醒");
                                                StringBuilder sb = new StringBuilder();
                                                sb.append("您好，有如下设备即将年检到期，请及时处理。\n")
                                                        .append("设备编号：").append(checkItemsDo.getCheckitemcode()).append("，设备名称：")
                                                        .append(checkItemsDo.getCheckitemname()).append("，配件名称：").append(checkItemsParts.getPartname()).append("，年检日期：")
                                                        .append(DateUtil.format(checkItemsParts.getYearlyinspectiondate(),"yyyy年MM月dd日")).append("\n");
                                                mail.setContent(sb.toString());
                                                reciveMails.put(v.getEmail(),mail);
                                            }
                                        }
                                    });
                                }
                            }
                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    continue;
                }
            }
        }
        // 邮件发送
        if(reciveMails != null && reciveMails.size()>0){
            reciveMails.forEach((k,v)->{
                v.setContent(v.getContent()+"详见智能安全监控平台：http://192.168.0.205:8000");
                // 邮件发送服务调用
                sysConfigFeignService.sendTextMail(v);
            });
        }
    }


}
