package com.zd.laboratory.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zd.common.core.constant.SecurityConstants;
import com.zd.common.core.domain.R;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.security.utils.SaveUtil;
import com.zd.laboratory.domain.LabCheckConfig;
import com.zd.laboratory.domain.LabCheckMachineMsg;
import com.zd.laboratory.domain.LabCheckRecord;
import com.zd.laboratory.domain.LabCheckRecordDetails;
import com.zd.laboratory.domain.vo.LabCheckMachineMsgVo;
import com.zd.laboratory.mapper.LabCheckMachineMsgMapper;
import com.zd.laboratory.mqtt.constants.MqttConstants;
import com.zd.laboratory.mqtt.entiy.MessageBody;
import com.zd.laboratory.mqtt.enums.SendMode;
import com.zd.laboratory.mqtt.service.impl.CommonSend;
import com.zd.laboratory.service.*;
import com.zd.system.api.RemoteUserService;
import com.zd.system.api.alarm.domain.AlarmEntrty;
import com.zd.system.api.alarm.domain.Routes;
import com.zd.system.api.alarm.domain.SendTypes;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.laboratory.domain.LabMessageContent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 一体机安全检查通知消息Service业务层处理
 *
 * @author liubo
 * @date 2022-01-04
 */
@Service
public class LabCheckMachineMsgServiceImpl implements ILabCheckMachineMsgService {
    private static Logger logger = LoggerFactory.getLogger(LabCheckMachineMsgServiceImpl.class);

    @Autowired
    private LabCheckMachineMsgMapper labCheckMachineMsgMapper;
    @Autowired
    private ILabCheckConfigService labCheckConfigService;
    @Autowired
    private ILabCheckRecordService labCheckRecordService;
    @Autowired
    private ILabMessageContentService labMessageContentService;
    @Autowired
    private CommonSend commonSend;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private ILabCheckRecordDetailsService labCheckRecordDetailsService;


    /**
     * 查询一体机安全检查通知消息
     *
     * @param id 一体机安全检查通知消息主键
     * @return 一体机安全检查通知消息
     */
    @Override
    public LabCheckMachineMsg selectLabCheckMachineMsgById(Long id) {
        LabCheckMachineMsg checkMachineMsg = labCheckMachineMsgMapper.selectLabCheckMachineMsgById(id);

        LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
        labCheckRecordDetails.setCheckId(checkMachineMsg.getCheckRecordId());
        checkMachineMsg.setDetails(labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails));
        return checkMachineMsg;
    }

    /**
     * 查询一体机安全检查通知消息列表
     *
     * @param labCheckMachineMsg 一体机安全检查通知消息
     * @return 一体机安全检查通知消息
     */
    @Override
    public List<LabCheckMachineMsg> selectLabCheckMachineMsgList(LabCheckMachineMsg labCheckMachineMsg) {
        // 需要根据实验室ID 来查询通知消息
        labCheckMachineMsg.setStatus(1);
        List<LabCheckMachineMsg> list = labCheckMachineMsgMapper.selectLabCheckMachineMsgList(labCheckMachineMsg);

        LabCheckRecord labCheckRecord;
        for (LabCheckMachineMsg checkMachineMsg : list) {
            LabCheckRecordDetails labCheckRecordDetails = new LabCheckRecordDetails();
            labCheckRecordDetails.setCheckId(checkMachineMsg.getCheckRecordId());
            checkMachineMsg.setDetails(labCheckRecordDetailsService.selectLabCheckRecordDetailsList(labCheckRecordDetails));

            labCheckRecord = labCheckRecordService.selectLabCheckRecordById(checkMachineMsg.getCheckRecordId());
            if(labCheckRecord != null){
                checkMachineMsg.setCheckRecord(labCheckRecord);

            }
            String checkDateStr = DateUtil.format(labCheckRecord.getCreateTime(), "yyyy年MM月dd日");

            String str = "  学院于check_date对你实验室实施了安全管理现场检查，共发现了count个整改项（见整改详情）。请逐一对照、分析原因、采取有效措施实施整改，并于check_date在系统里提交整改证明材料和整改报告。\n" +
                    "  请你实验室务必高度重视，积极采取有效措施，切实加强对实验室的安全管理。同时，要举一反三，对实验室定期开展安全自查与整改，不断提升实验室安全工作水平。";
            str = str.replaceAll("check_date", checkDateStr).replaceAll("count", checkMachineMsg.getDetails().size()+"");

            checkMachineMsg.setNotifyMsg(str);
            checkMachineMsg.setCheckDateStr(checkDateStr);

        }

        return list;
    }

    /**
     * 新增一体机安全检查通知消息
     * @param type 通知类型 1 一般整改，2 重大整改
     * @param checkRecordId 安全检查ID
     * @return 结果
     */
    @Override
    public void insertLabCheckMachineMsg(int type, long checkRecordId) {


        // 查询配置信息
        LabCheckConfig checkConfigInfo = labCheckConfigService.getCheckConfigInfo();
        if(checkConfigInfo != null){
            boolean senMsg = false;
            LabCheckRecord checkRecord = labCheckRecordService.selectLabCheckRecordById(checkRecordId);

            if(checkRecord == null){
                logger.error("发送消息通知失败，ID无效");
            }
            // 查询实验室负责人
            Long userId = checkRecord.getFzrId();

            LabCheckMachineMsg labCheckMachineMsg = null;
            LabMessageContent labMessageContent = null;
            if(type == 1){
                // 1.短信通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckSmsMsg())){
                    // 查询负责人手机号
//                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
//                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
//                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                    // 修改为 提交输入的手机号

                    if (StringUtils.isNotBlank(checkRecord.getFzrLxfs())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{checkRecord.getFzrLxfs()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }
                }
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAioMsg())){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getCheckAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    labMessageContent.setContent(checkConfigInfo.getCheckAppMsg());
                    labMessageContent.setUserIds(userId+"");

                }
            }else if(type == 2){
                // 1.短信通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifySmsMsg())){
                    // 查询负责人手机号
                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getRectifySmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }
                }
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAioMsg())){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getRectifyAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    labMessageContent.setContent(checkConfigInfo.getCheckAppMsg());
                    labMessageContent.setUserIds(userId+"");
                }
            }

            if(labCheckMachineMsg != null){
                labCheckMachineMsg.setStatus(1);
                labCheckMachineMsgMapper.insertLabCheckMachineMsg(labCheckMachineMsg);
            }
            if(labMessageContent != null){
                labMessageContentService.insertLabMessageContent(labMessageContent);
            }
            if(senMsg){
                MessageBody messageBody = new MessageBody();
                messageBody.setData(labCheckMachineMsg);
                //仅发送一次
                commonSend.send(MqttConstants.LAB_CHECK + checkRecord.getLaboratoryId(), messageBody, SendMode.ONCE);
            }
        }
    }

    /***
     * 新增一体机安全检查 检查者审核 通知消息
     * @param type
     * @param checkRecordId
     */
    @Override
    public void insertLabCheckMachineJcz(int type, long checkRecordId) {
        // 查询配置信息
        LabCheckConfig checkConfigInfo = labCheckConfigService.getCheckConfigInfo();
        if(checkConfigInfo != null){
            boolean senMsg = false;
            //String count="您有新的整改报告需要审批，请注意查看";//发送的内容

            LabCheckRecord checkRecord = labCheckRecordService.selectLabCheckRecordById(checkRecordId);

            if(checkRecord == null){
                logger.error("发送消息通知失败，ID无效");
            }
            // 查询实验室负责人
            Long userId = checkRecord.getCreateUserId();

            LabCheckMachineMsg labCheckMachineMsg = null;
            LabMessageContent labMessageContent = null;
            if(type == 1){
                // 1.短信通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckSmsMsg())){
                    // 查询负责人手机号
//                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
//                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
//                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                    // 修改为 提交输入的手机号

                   /* if (StringUtils.isNotBlank(checkRecord.getFzrLxfs())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{checkRecord.getFzrLxfs()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }*/
                }
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAioMsg())){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getCheckAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    labMessageContent.setContent(checkConfigInfo.getCheckAppMsg());
                    //labMessageContent.setContent(count);
                    labMessageContent.setUserIds(userId+"");

                }
            }else if(type == 2){
                // 1.短信通知
                /*if(StringUtils.isNotBlank(checkConfigInfo.getRectifySmsMsg())){
                    // 查询负责人手机号
                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getRectifySmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }
                }*/
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAioMsg())){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getRectifyAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    labMessageContent.setContent(checkConfigInfo.getRectifyAppMsg());
                    labMessageContent.setUserIds(userId+"");
                }
            }

            if(labCheckMachineMsg != null){
                //检查消息通知是否存在
                LabCheckMachineMsg lmm= new LabCheckMachineMsg();
                lmm.setCheckRecordId(checkRecordId);
                List<LabCheckMachineMsg> list = labCheckMachineMsgMapper.selectLabCheckMachineMsgList(lmm);
                if(list.size()==0){
                    senMsg = true;
                    labCheckMachineMsg.setStatus(1);
                    labCheckMachineMsgMapper.insertLabCheckMachineMsg(labCheckMachineMsg);
                }

            }
            if(labMessageContent != null){
                labMessageContentService.insertLabMessageContent(labMessageContent);
            }
            if(senMsg){
                MessageBody messageBody = new MessageBody();
                messageBody.setData(labCheckMachineMsg);
                //仅发送一次
                commonSend.send(MqttConstants.LAB_CHECK + checkRecord.getLaboratoryId(), messageBody, SendMode.ONCE);
            }
        }
    }

    /**
     * 新增一体机安全检查 提交者 通知消息
     *
     * @param type
     * @param checkRecordId
     * @param status
     * @return 结果
     */
    @Override
    public void insertLabCheckMachineTjz(int type, long checkRecordId, int status) {
        // 查询配置信息
        LabCheckConfig checkConfigInfo = labCheckConfigService.getCheckConfigInfo();
        if(checkConfigInfo != null){
            boolean senMsg = false;
            String count=null;//发送的内容
            if(status==1){//提交时

            }else if(status==2){
                count="您的整改报告未能通过审批，请注意查看";
            }else if(status==4){
                count="您的整改报告通过了审批，请注意查看";
            }
            LabCheckRecord checkRecord = labCheckRecordService.selectLabCheckRecordById(checkRecordId);

            if(checkRecord == null){
                logger.error("发送消息通知失败，ID无效");
            }
            // 查询实验室负责人
            Long userId = checkRecord.getFzrId();

            LabCheckMachineMsg labCheckMachineMsg = null;
            LabMessageContent labMessageContent = null;
            if(type == 1){
                // 1.短信通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckSmsMsg())){
                    // 查询负责人手机号
//                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
//                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
//                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                    // 修改为 提交输入的手机号

                   /* if (StringUtils.isNotBlank(checkRecord.getFzrLxfs())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{checkRecord.getFzrLxfs()}, SendTypes.SMS+"", checkConfigInfo.getCheckSmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }*/
                }
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAioMsg()) && status==1){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getCheckAioMsg());
                    //labCheckMachineMsg.setCheckMsg(count!=null?count:checkConfigInfo.getCheckAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getCheckAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    //labMessageContent.setContent(checkConfigInfo.getCheckAppMsg());
                    labMessageContent.setContent(count!=null?count:checkConfigInfo.getCheckAppMsg());
                    labMessageContent.setUserIds(userId+"");

                }
            }else if(type == 2){
                // 1.短信通知
                /*if(StringUtils.isNotBlank(checkConfigInfo.getRectifySmsMsg())){
                    // 查询负责人手机号
                    R<SysUser> user = remoteUserService.getUserInfoByUserId(userId, SecurityConstants.INNER);
                    if (user.getCode() == 200 && user.getData() != null && StringUtils.isNotBlank(user.getData().getPhonenumber())) {
                        AlarmEntrty alarmEntrty = new AlarmEntrty(Routes.NoticePush, new String[]{user.getData().getPhonenumber()}, SendTypes.SMS+"", checkConfigInfo.getRectifySmsMsg());
                        MessageBody messageBody = new MessageBody();
                        messageBody.setData(alarmEntrty);
                        commonSend.send("alarm/"+checkRecordId,messageBody, SendMode.DISTINCT);
                    }
                }*/
                // 2.一体机通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAioMsg()) && status==1){
                    labCheckMachineMsg = new LabCheckMachineMsg();
                    labCheckMachineMsg.setCheckRecordId(checkRecordId);
                    labCheckMachineMsg.setType(type);
                    labCheckMachineMsg.setCheckMsg(checkConfigInfo.getRectifyAioMsg());
                    //labCheckMachineMsg.setCheckMsg(count!=null?count:checkConfigInfo.getRectifyAioMsg());
                    SaveUtil.setCommonAttr(labCheckMachineMsg);

                    senMsg = true;
                }
                // 3.小程序消息通知
                if(StringUtils.isNotBlank(checkConfigInfo.getRectifyAppMsg())){
                    labMessageContent = new LabMessageContent();
                    labMessageContent.setSendMode(2);
                    labMessageContent.setSendRange(3);
                    labMessageContent.setMessClass(1);
                    //labMessageContent.setContent(checkConfigInfo.getCheckAppMsg());
                    labMessageContent.setContent(count!=null?count:checkConfigInfo.getRectifyAppMsg());
                    labMessageContent.setUserIds(userId+"");
                }
            }

            if(labCheckMachineMsg != null && status==1){
                //检查消息通知是否存在
                LabCheckMachineMsg lmm= new LabCheckMachineMsg();
                lmm.setCheckRecordId(checkRecordId);
                List<LabCheckMachineMsg> list = labCheckMachineMsgMapper.selectLabCheckMachineMsgList(lmm);
                if(list.size()==0){
                    senMsg = true;
                    labCheckMachineMsg.setStatus(1);
                    labCheckMachineMsgMapper.insertLabCheckMachineMsg(labCheckMachineMsg);
                }
            }
            if(labMessageContent != null){
                labMessageContentService.insertLabMessageContent(labMessageContent);
            }
            if(senMsg){
                MessageBody messageBody = new MessageBody();
                messageBody.setData(labCheckMachineMsg);
                //仅发送一次
                commonSend.send(MqttConstants.LAB_CHECK + checkRecord.getLaboratoryId(), messageBody, SendMode.ONCE);
            }
        }
    }

    /**
     * 修改一体机安全检查通知消息
     *
     * @param labCheckMachineMsg 一体机安全检查通知消息
     * @return 结果
     */
    @Override
    public int updateLabCheckMachineMsg(LabCheckMachineMsg labCheckMachineMsg) {
        labCheckMachineMsg.setUpdateTime(DateUtils.getNowDate());
        labCheckMachineMsg.setUpdateBy(SecurityUtils.getUsername());
        return labCheckMachineMsgMapper.updateLabCheckMachineMsg(labCheckMachineMsg);
    }

    /**
     * 批量删除一体机安全检查通知消息
     *
     * @param ids 需要删除的一体机安全检查通知消息主键
     * @return 结果
     */
    @Override
    public int deleteLabCheckMachineMsgByIds(Long[] ids) {
        return labCheckMachineMsgMapper.deleteLabCheckMachineMsgByIds(ids);
    }

    /**
     * 删除一体机安全检查通知消息信息
     *
     * @param id 一体机安全检查通知消息主键
     * @return 结果
     */
    @Override
    public int deleteLabCheckMachineMsgById(Long id) {
        return labCheckMachineMsgMapper.deleteLabCheckMachineMsgById(id);
    }

    @Override
    public List<LabCheckMachineMsgVo> selectCheckMsg(LabCheckMachineMsg labCheckMachineMsg) {

        labCheckMachineMsg.setStatus(1);
        List<LabCheckMachineMsgVo> list = labCheckMachineMsgMapper.selectCheckMsgBySubId(labCheckMachineMsg);

        for (LabCheckMachineMsgVo labCheckMachineMsgVo : list) {

            labCheckMachineMsgVo.setDetailList(labCheckRecordDetailsService.selectCheckMsgDetail(labCheckMachineMsgVo.getId()));

        }


        return list;
    }
}
