package com.zd.laboratory.service.impl;

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

import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.SaveUtil;

import com.zd.laboratory.domain.*;
import com.zd.laboratory.domain.vo.LabCheckRecordVO;
import com.zd.laboratory.domain.vo.LabSecurityApplyVO;
import com.zd.laboratory.domain.vo.LabSubjectVO;
import com.zd.laboratory.mapper.*;
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.ILabCheckMachineMsgService;
import com.zd.laboratory.service.ILabCheckRecordReleaseService;
import com.zd.laboratory.service.ILabMessageContentService;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.laboratory.domain.LabMessageContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.laboratory.service.ILabCheckRecordService;
import org.springframework.transaction.annotation.Transactional;
import com.zd.system.api.laboratory.RemoteLaboratoryService;

/**
 * 安全检查Service业务层处理
 *
 * @author zd
 * @date 2021-12-30
 */
@Service
public class LabCheckRecordServiceImpl implements ILabCheckRecordService
{
    private Logger logger = LoggerFactory.getLogger(LabCheckRecordServiceImpl.class);
    @Autowired
    private LabCheckRecordMapper labCheckRecordMapper;
    @Autowired
    private CommonSend commonSend;
    @Autowired
    private LabCheckRecordDetailsMapper labCheckRecordDetailsMapper;
    @Autowired
    private LabCheckMachineMsgMapper labCheckMachineMsgMapper;
    @Autowired
    private RemoteLaboratoryService remoteLaboratoryService;
    @Autowired
    private LabCheckRecordReleaseMapper labCheckRecordReleaseMapper;
    @Autowired
    private ILabCheckRecordReleaseService iLabCheckRecordReleaseService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private LabCheckRecordDetailslogMapper labCheckRecordDetailslogMapper;
    @Autowired
    private LabSecurityApplyMapper LabSecurityApplyMapper;
    @Autowired
    private ILabMessageContentService labMessageContentService;

    /**
     * 查询安全检查
     *
     * @param id 安全检查主键
     * @return 安全检查
     */
    @Override
    public LabCheckRecord selectLabCheckRecordById(Long id)
    {
        return labCheckRecordMapper.selectLabCheckRecordById(id);
    }

    /**
     * 查询安全检查列表
     *
     * @param labCheckRecordVo 安全检查
     * @return 安全检查
     */
    @Override
    @DataScope(deptAlias = "d" , userAlias = "t" , permi = PerPrefix.LABORATORY_CHECKRECORD)
    public List<LabCheckRecord> selectLabCheckRecordList(LabCheckRecordVO labCheckRecordVo)
    {
        return labCheckRecordMapper.selectLabCheckRecordList(labCheckRecordVo);
    }

    /**
     * 新增安全检查
     *
     * @param labCheckRecordVo 安全检查
     * @return 结果
     */
    @Override
    public int insertLabCheckRecord(LabCheckRecordVO labCheckRecordVo)
    {
        //设置其他公共字段
        SaveUtil.setCommonAttr(labCheckRecordVo);
        return labCheckRecordMapper.insertLabCheckRecord(labCheckRecordVo);
    }

    /**
     * 新增安全检查
     *
     * @param labCheckRecordVo 安全检查
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLabCheckRecordCg(LabCheckRecordVO labCheckRecordVo)
    {
        int id =0;
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        /*R<Object> r = remoteLaboratoryService.selectUserInfoById(labCheckRecordVo.getUserId());
        SysUser sysUser =  (SysUser) r.getData();*/
        if(sysUser==null){
            throw new ServiceException("没有查询到用户相关信息");
        }else if(sysUser.getIsCheck()==0){
            throw new ServiceException("该用户非检查人员，无权限保存");
        }else if(sysUser.getIsCheck()==1){
            //设置其他公共字段
            SaveUtil.setCommonAttr(labCheckRecordVo);

            //非草稿
            labCheckRecordVo.setIsCg(1);
            labCheckRecordVo.setCheckNum( "JC"+String.valueOf(new Date().getTime()));
            labCheckRecordVo.setCreateUserId(sysUser.getUserId());
            labCheckRecordVo.setJcRyxm(sysUser.getNickName());
            labCheckRecordVo.setCreateTime(new Date());
            labCheckRecordVo.setIsFabu(0);//默认未发布

            //检查项录入
            id = labCheckRecordMapper.insertLabCheckRecord(labCheckRecordVo);
            //检查隐患录入
            List<LabCheckRecordDetails> listlcrd = labCheckRecordVo.getDetailsList();
            for (LabCheckRecordDetails lcrd: listlcrd) {
                lcrd.setJcxNum("YHX"+String.valueOf(new Date().getTime()));
                lcrd.setCheckId(labCheckRecordVo.getId());
                lcrd.setCreateTime(new Date());
                lcrd.setSpStatus(0);
                labCheckRecordDetailsMapper.insertLabCheckRecordDetails(lcrd);
            }
        }
        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLabCheckRecordTj(LabCheckRecordVO labCheckRecordVo) {
        int id =0;
        int id2 = 0;
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        /*R<Object> r = remoteLaboratoryService.selectUserInfoById(labCheckRecordVo.getUserId());
        SysUser sysUser =  (SysUser) r.getData();*/
        if(sysUser==null){
            throw new ServiceException("没有查询到用户相关信息");
        }else if(sysUser.getIsCheck()==0){
            throw new ServiceException("该用户非检查人员，无权限保存");
        }else if(sysUser.getIsCheck()==1) {
            //设置其他公共字段
            SaveUtil.setCommonAttr(labCheckRecordVo);

            //非草稿
            labCheckRecordVo.setIsCg(0);
            labCheckRecordVo.setCheckNum( "JC"+String.valueOf(new Date().getTime()));
            labCheckRecordVo.setCreateUserId(sysUser.getUserId());
            labCheckRecordVo.setJcRyxm(sysUser.getNickName());
            labCheckRecordVo.setCreateTime(new Date());
            labCheckRecordVo.setIsFabu(1);//默认发布

            //检查项录入
            id = labCheckRecordMapper.insertLabCheckRecord(labCheckRecordVo);
            //检查隐患录入
            List<LabCheckRecordDetails> listlcrd = labCheckRecordVo.getDetailsList();
            for (LabCheckRecordDetails lcrd : listlcrd) {
                lcrd.setJcxNum( "YHX"+String.valueOf(new Date().getTime()));
                lcrd.setCheckId(labCheckRecordVo.getId());
                lcrd.setCreateTime(new Date());
                lcrd.setSpStatus(0);
                id2 = labCheckRecordDetailsMapper.insertLabCheckRecordDetails(lcrd);

               //检查日志表数据录入
                /*LabCheckRecordDetailslog detailslog = new LabCheckRecordDetailslog();
                detailslog.setCheckId(labCheckRecordVo.getId());
                detailslog.setCheckDetailsId(lcrd.getId());
                detailslog.setApplyYhImg(lcrd.getYhImg());
                detailslog.setApplyUserId(labCheckRecordVo.getCreateUserId());
                detailslog.setApplyUserName(labCheckRecordVo.getJcRyxm());
                detailslog.setApplyTime(labCheckRecordVo.getCreateTime());
                detailslog.setCreateTime(new Date());//创建时间
                detailslog.setSpStatus(0L);
                labCheckRecordDetailslogMapper.insertLabCheckRecordDetailslog(detailslog);*/
            }

            //发布检查关系表数据录入
            LabCheckRecordRelease lcrr = new LabCheckRecordRelease();
            lcrr.setCheckId(String.valueOf(labCheckRecordVo.getId()));
            lcrr.setReleaseDescribe(labCheckRecordVo.getCheckName());
            lcrr.setCreateTime(new Date());
            lcrr.setUserId(sysUser.getUserId());
            lcrr.setCreateBy(sysUser.getNickName());
            lcrr.setDeptId(sysUser.getDept().getDeptId());
            lcrr.setDeptName(sysUser.getDept().getDeptName());
            iLabCheckRecordReleaseService.insertLabCheckRecordRelease(lcrr);

        }

        if(id>0 && id2>0){
            return id;
        }else{
            return 0;
        }
    }

    /**
     * 修改安全检查
     *
     * @param labCheckRecordVo 安全检查
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLabCheckRecord(LabCheckRecordVO  labCheckRecordVo)
    {
        boolean senMsg = false;
        //获取当前登录用户
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        //如果为整改确认或者整改中时 添加整改确认时间
        if(1==labCheckRecordVo.getZgStatus()){
            labCheckRecordVo.setZgqrTime(new Date());
            if(!sysUser.getUserId().equals(labCheckRecordVo.getFzrId())){
                throw new ServiceException("不是负责人，无权提交");
            }
            //提交时 记录日志
        }

        //审核驳回时 添加驳回时间
        if(2==labCheckRecordVo.getZgStatus() ){
            labCheckRecordVo.setZgbhTime(new Date());
            if(!sysUser.getUserId().equals(labCheckRecordVo.getCreateUserId())){
                throw new ServiceException("不是创建人，无权审核");
            }
        }

        if(3==labCheckRecordVo.getZgStatus()){
            labCheckRecordVo.setZgqrTime(new Date());
            if(!sysUser.getUserId().equals(labCheckRecordVo.getFzrId())){
                throw new ServiceException("不是创建人，无权提交");
            }
        }

        //整改完成时 添加整改整改完成时间
        if(4==labCheckRecordVo.getZgStatus() ){
            labCheckRecordVo.setZgWcsj(new Date());
            if(!sysUser.getUserId().equals(labCheckRecordVo.getCreateUserId())){
                throw new ServiceException("不是创建人，无权审核");
            }
            senMsg = true;
        }

        labCheckRecordVo.setUpdateTime(new Date());

        if(1==labCheckRecordVo.getIsFabu()){
            //发布检查关系表数据录入
            LabCheckRecordRelease lcrr = new LabCheckRecordRelease();
            lcrr.setCheckId(String.valueOf(labCheckRecordVo.getId()));
            lcrr.setReleaseDescribe(labCheckRecordVo.getCheckName());
            lcrr.setUserId(sysUser.getUserId());
            lcrr.setCreateBy(sysUser.getNickName());
            lcrr.setCreateTime(new Date());
            iLabCheckRecordReleaseService.insertLabCheckRecordRelease(lcrr);
        }

        //安全检查项修改
        int id= labCheckRecordMapper.updateLabCheckRecord(labCheckRecordVo);

        //安全检查隐患修改
        List<LabCheckRecordDetails> listlcrd = labCheckRecordVo.getDetailsList();
        if(listlcrd!=null){
            for (LabCheckRecordDetails lcrd : listlcrd) {
                LabCheckRecordDetails ds =labCheckRecordDetailsMapper.selectLabCheckRecordDetailsById(lcrd.getId());
                //隐患不存在添加 否则修改
                if(ds==null){
                    lcrd.setCheckId(labCheckRecordVo.getId());
                    lcrd.setCreateTime(new Date());
                    labCheckRecordDetailsMapper.insertLabCheckRecordDetails(lcrd);
                }else{
                    lcrd.setUpdateTime(new Date());
                    labCheckRecordDetailsMapper.updateLabCheckRecordDetails(lcrd);
                }

            }
        }

        if(senMsg){
            // 需要将一体机消息通知作废掉
            labCheckMachineMsgMapper.updateByCheckRecordId(labCheckRecordVo.getId());

            MessageBody messageBody = new MessageBody();
            messageBody.setData(null);
            // 不确定前端传值是否有实验室ID 故重新查询保证
            LabCheckRecord checkRecord = labCheckRecordMapper.selectLabCheckRecordById(labCheckRecordVo.getId());
            //仅发送一次
            commonSend.send(MqttConstants.LAB_CHECK + checkRecord.getLaboratoryId(), messageBody, SendMode.ONCE);
        }

        return id;
    }

    /**
     * 批量删除安全检查
     *
     * @param ids 需要删除的安全检查主键
     * @return 结果
     */
    @Override
    public int deleteLabCheckRecordByIds(Long[] ids)
    {
        return labCheckRecordMapper.deleteLabCheckRecordByIds(ids);
    }

    /**
     * 删除安全检查信息
     *
     * @param id 安全检查主键
     * @return 结果
     */
    @Override
    public int deleteLabCheckRecordById(Long id)
    {
        return labCheckRecordMapper.deleteLabCheckRecordById(id);
    }

    /***
     * 根据房间号查询实验室信息
     * @param map
     * @return
     */
    @Override
    //@DataScope(deptAlias = "d" , userAlias = "u" , permi = PerPrefix.LABORATORY_CHECKRECORD)
    public List<LabSubjectVO> selectInfoByRoom(Map<String, Object> map) {
        logger.error("根据房间号查询实验室信息: " + map.toString());
        return labCheckRecordMapper.selectInfoByRoom(map);
    }

    /**
     * 根据整改状态获取集合
     *
     * @return
     */
    @Override
   // @DataScope(deptAlias = "s" , userAlias = "s" , permi = PerPrefix.LABORATORY_CHECKRECORD)
    public List<Map<String, Object>> selectStatusList() {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        LabCheckRecordVO labCheckRecordVo =new LabCheckRecordVO();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecordVo.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            /*if(sysUser.getIsCheck() == 1){
                // 检查者只能查到自己创建的数据
                labCheckRecordVo.setFzrId(null);
                labCheckRecordVo.setCreateUserId(sysUser.getUserId());
            }else{
                labCheckRecordVo.setFzrId(sysUser.getUserId());
            }*/
            labCheckRecordVo.setFzrId(sysUser.getUserId());
        }

        return labCheckRecordMapper.selectStatusList(labCheckRecordVo);
    }

    /**
     * 查询安全检查列表
     *
     * @param labCheckRecordVo 安全检查
     * @return 安全检查集合
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.LABORATORY_APPLY)
    public List<LabCheckRecordVO> selectLabCheckRecordZgshList(LabCheckRecordVO labCheckRecordVo) {

        return labCheckRecordMapper.selectLabCheckRecordZgshList(labCheckRecordVo);
    }

    /***
     * 根据部门id查询用户所属部门
     * @param
     * @return
     */
    @Override
    public List<Map<String, Object>> selectUserDept() {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        return labCheckRecordMapper.selectUserDept(sysUser.getDeptId());
    }

    /**
     * 更具登录用户部门id查询该部门下单位信息
     *
     * @param
     * @return
     */
    @Override
    public List<Map<String, Object>> selectDeptListUserDeptId() {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        return labCheckRecordMapper.selectDeptListUserDeptId(sysUser.getDeptId());
    }

    /**
     * 根据yyyy-mm-dd对检查项时间分组
     *
     * @return
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.LABORATORY_APPLY)
    public List<LabCheckRecordVO> selectLabCheckRecordListOrderBydate(LabCheckRecordVO labCheckRecordVo) {

        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        //LabCheckRecordVO labCheckRecordVo =new LabCheckRecordVO();
        if("00".equals(sysUser.getUserType())){ //系统用户
            if(sysUser.getDeptId()!=null ){
                labCheckRecordVo.setDeptId(sysUser.getDeptId());
            }
        }else if("11".equals(sysUser.getUserType())){ //教职工
            if(sysUser.getIsCheck() == 1){
                // 检查者只能查到自己创建的数据
                labCheckRecordVo.setFzrId(null);
                labCheckRecordVo.setCreateUserId(sysUser.getUserId());
            }else{
                labCheckRecordVo.setFzrId(sysUser.getUserId());
            }
        }
        return labCheckRecordMapper.selectLabCheckRecordListOrderBydate(labCheckRecordVo);
    }

    /***
     * 修改第一次查看时间
     * @param id
     * @return
     */
    @Override
    public int updateFirstTimeById(Long id) {
        return labCheckRecordMapper.updateFirstTimeById(id);
    }

    /***
     * 批量修改发布状态
     * @param ids
     * @return
     */
    @Override
    public int updateLabCheckRecordByIds(Long[] ids) {
        return labCheckRecordMapper.updateLabCheckRecordByIds(ids);
    }

    /***
     * 首页安全检查 发布详情跳转查询
     * @param labCheckRecordVo
     * @return
     */
    @Override
    public List<LabCheckRecordVO> selectLabCheckRecordIndexDetals(LabCheckRecordVO labCheckRecordVo) {
        /*if(labCheckRecordVo.getId()==null){
            throw new ServiceException("参数为空！");
        }*/
            List<LabCheckRecordVO> list =labCheckRecordMapper.selectLabCheckRecordIndexDetals(labCheckRecordVo);
        return list;
    }

    /**
     * 撤销发布
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLabCheckRecordBack(Long[] ids) {
        //修改 检查记录表数据
        labCheckRecordMapper.updateLabCheckRecordBack(ids);

        //最近一次发布记录
        LabCheckRecordRelease labCheckRecordRelease=labCheckRecordReleaseMapper.selectLabCheckRecordReleaseFirst();
        //String checkid="38,39,40,41";
        String[] ystr = labCheckRecordRelease.getCheckId().split(",");

        /*Long[] idscheck = new Long[2];
        idscheck[0]=38L;
        idscheck[1]=39L;*/

        Map<String,String> checkMap = new HashMap();
        for (int i=0;i<ystr.length;i++){
            checkMap.put(ystr[i],ystr[i]);
        }
        for (int k=0;k<ids.length;k++){
            checkMap.remove(ids[k]+"");
        }

        StringBuffer str1 = new StringBuffer();
        checkMap.forEach((key,value)->{
            str1.append(value);
            str1.append(",");
        });
        //System.out.println(str1);
        //System.out.println(str1.substring(0,str1.lastIndexOf(",")));

        //修改发布表数据
        String checkId=str1.substring(0,str1.lastIndexOf(","));
        labCheckRecordRelease.setCheckId(checkId);
        return labCheckRecordReleaseMapper.updateLabCheckRecordRelease(labCheckRecordRelease);
    }

    /***
     * 某个检查项在某个实验室下出现的次数
     * @param map
     * @return
     */
    @Override
    public List<LabCheckRecordVO> selectHiddenDangerCount(Map<String, Object> map) {
        return labCheckRecordMapper.selectHiddenDangerCount(map);
    }

    /**
     *  隐患项未整改逾期小程序消息发送
     * @param
     * @return
     */
    @Override
    public void checkSendMsgBeOverdue() {
        Map<String, Object> map = new HashMap<>();
        // 一天逾期消息发送
        map.put("timeLength",1);
        List<LabCheckRecordVO> list = labCheckRecordMapper.selectCheckBeoverdue(map);
        if(list.size()>0){
            //循环发送消息-即将预期未整改的隐患项
            for (int i=0;i<list.size();i++){
                //获取该实验室下准入资格未过期的学生申请集合
                LabSecurityApply apply=new LabSecurityApply();
                apply.setSubjectId(Long.valueOf(list.get(i).getLaboratoryId()) );
                List<LabSecurityApplyVO> listapply=  LabSecurityApplyMapper.selectApplyListEffective(new LabSecurityApply());
                String userIds="";//学生id集合
                if(listapply.size()>0){
                    for (int k=0;k<listapply.size();k++){
                        userIds+=listapply.get(k).getUserId()+",";
                    }
                }

                //小程序消息通知发送
                LabMessageContent labMessageContent = null;
                //1.实验室负责人 和 2.准入人员
                labMessageContent = new LabMessageContent();
                labMessageContent.setSendMode(2);
                labMessageContent.setSendRange(3);
                labMessageContent.setMessClass(1);
                labMessageContent.setMessType(16);//即将预期
                labMessageContent.setSubIds(String.valueOf(list.get(i).getLaboratoryId()));
                // 喷雾降尘实验室(103),隐患项即将整改过期,隐患项单号：JC1649410773849,隐患描述:AAA
                StringBuffer str = new StringBuffer();
                str.append(list.get(i).getLaboratoryName())
                        .append("，隐患项即将整改过期，隐患项单号:").append(list.get(i).getCheckNum())
                                .append("，隐患描述:").append(list.get(i).getYhMs());
                labMessageContent.setContent(str.toString());
                labMessageContent.setUserIds(list.get(i).getFzrId()+","+userIds);
                labMessageContentService.insertLabMessageContent(labMessageContent);
            }
        }

        //3天逾期消息发送
        map.put("timeLength",3);
        List<LabCheckRecordVO> list3 = labCheckRecordMapper.selectCheckBeoverdue(map);
        if(list3.size()>0){
            //循环发送消息-即将预期未整改的隐患项
            for (int i=0;i<list3.size();i++){
                //获取该实验室下准入资格未过期的学生申请集合
                LabSecurityApply apply=new LabSecurityApply();
                apply.setSubjectId(Long.valueOf(list3.get(i).getLaboratoryId()) );
                List<LabSecurityApplyVO> listapply=  LabSecurityApplyMapper.selectApplyListEffective(new LabSecurityApply());
                String userIds=""; //学生id集合
                if(listapply.size()>0){
                    for (int k=0;k<listapply.size();k++){
                        userIds+=listapply.get(k).getUserId()+",";
                    }
                }

                //小程序消息通知发送
                LabMessageContent labMessageContent = null;
                //1.实验室负责人 和 2.准入人员
                labMessageContent = new LabMessageContent();
                labMessageContent.setSendMode(2);
                labMessageContent.setSendRange(3);
                labMessageContent.setMessClass(1);
                labMessageContent.setMessType(16);//即将预期
                labMessageContent.setSubIds(String.valueOf(list.get(i).getLaboratoryId()));
                // 喷雾降尘实验室(103),隐患项即将整改过期,隐患项单号：JC1649410773849,隐患描述:AAA
                StringBuffer str = new StringBuffer();
                str.append(list3.get(i).getLaboratoryName())
                        .append("，隐患项即将整改过期,隐患项单号:").append(list3.get(i).getCheckNum())
                        .append("，隐患描述:").append(list3.get(i).getYhMs());
                labMessageContent.setContent(str.toString());
                labMessageContent.setUserIds(list3.get(i).getFzrId()+","+userIds);
                labMessageContentService.insertLabMessageContent(labMessageContent);
            }
        }
    }
}
