package com.zd.laboratory.service.impl;

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

import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.laboratory.domain.LabApprovalDetail;
import com.zd.laboratory.domain.LabSecurityGroup;
import com.zd.laboratory.domain.dto.LabApprovalAndDetailDTO;
import com.zd.laboratory.domain.vo.LabApprovalVO;
import com.zd.laboratory.domain.vo.LabSecurityGroupVO;
import com.zd.laboratory.mapper.LabApprovalDetailMapper;
import com.zd.laboratory.mapper.LabSecurityGroupMapper;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.exam.RemoteExamService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.zd.laboratory.mapper.LabApprovalMapper;
import com.zd.laboratory.domain.LabApproval;
import com.zd.laboratory.service.ILabApprovalService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 安全准入审批记录Service业务层处理
 *
 * @author zd
 * @date 2021-08-31
 */
@Service
public class LabApprovalServiceImpl implements ILabApprovalService {
    @Autowired
    private LabApprovalMapper labApprovalMapper;
    @Autowired
    private LabSecurityGroupMapper labSecurityGroupMapper;
    @Autowired
    private LabApprovalDetailMapper labApprovalDetailMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemoteExamService remoteExamService;

    /**
     * 查询安全准入审批记录
     *
     * @param id 安全准入审批记录主键
     * @return 安全准入审批记录
     */
    @Override
    public LabApprovalAndDetailDTO selectLabApprovalById(Long id) {
        return labApprovalMapper.selectLabApprovalById(id);
    }

    /**
     * 查询安全准入审批记录列表
     *
     * @param labApproval 安全准入审批记录
     * @return 安全准入审批记录
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<LabApprovalVO> selectLabApprovalList(LabApproval labApproval) {
        return labApprovalMapper.selectLabApprovalList(labApproval);
    }

    /**
     * 新增安全准入审批记录
     *
     * @param labApproval 安全准入审批记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertLabApproval(LabApprovalAndDetailDTO labApproval) {

        List<LabApprovalDetail> approvalDetails = labApproval.getApprovalDetails();
        if (CollectionUtils.isEmpty(approvalDetails)) {
            throw new ServiceException("请上传安全准入的资料！");
        }

        SysUser user = tokenService.getLoginUser().getSysUser();
        // 提交默认待审核
        labApproval.setRecordContent(2);
        labApproval.setJoinUserId(user.getUserId());
        labApproval.setUserId(user.getUserId());
        labApproval.setCreateBy(user.getNickName());
        labApproval.setCreateTime(DateUtils.getNowDate());

        int num = 0;
        try {
            num = labApprovalMapper.insertLabApproval(labApproval);
        } catch (DuplicateKeyException e) {
            throw new ServiceException("同一个实验室只能办理一次！");
        }

        for (LabApprovalDetail approvalDetail : approvalDetails) {
            approvalDetail.setApprovalId(labApproval.getId());
            approvalDetail.setCreateTime(DateUtils.getNowDate());
        }

        // 报错准入提交的资料
        labApprovalDetailMapper.insertBatch(approvalDetails);
        return num;
    }

    /**
     * 修改安全准入审批记录
     *
     * @param labApproval 安全准入审批记录
     * @return 结果
     */
    @Override
    @Transactional
    public int updateLabApproval(LabApprovalAndDetailDTO labApproval) {
        if (labApproval.getRecordContent() == null) {
            throw new ServiceException("状态不能为空");
        }
        List<LabApprovalDetail> approvalDetails = labApproval.getApprovalDetails();
        if (CollectionUtils.isEmpty(approvalDetails)) {
            throw new ServiceException("请上传安全准入的资料！");
        }

        LabApprovalAndDetailDTO labApprovalOld = labApprovalMapper.selectLabApprovalById(labApproval.getId());
        if (labApprovalOld == null) {
            throw new ServiceException("参数异常！");
        }
        // 0=未通过,1=已办理,2=待审核,3=即将过期,4=已过期
        if (labApprovalOld.getRecordContent() != null && labApprovalOld.getRecordOther() != null) {
            if (labApprovalOld.getRecordContent() == 0 || labApprovalOld.getRecordOther() == 4) {
                // 未通过或已过期时 需重新提交 传值 2
                if (labApproval.getRecordContent() != 2) {
                    throw new ServiceException("重新提交状态异常！");
                }
            } else if (labApprovalOld.getRecordOther() == 3) {
                // 即将过期，立即续约 传值 2
                if (labApproval.getRecordContent() != 2) {
                    throw new ServiceException("立即续约状态异常！");
                }
            } else if (labApprovalOld.getRecordContent() == 1 && labApproval.getRecordContent() == 2) {
                // 清除过期日期
                labApproval.setExpirationDate(null);
                labApprovalMapper.updateExpirationDate(labApproval.getId());
            }
        } else {
            // 默认待审核
            labApprovalOld.setRecordContent(2);
        }
        labApproval.setUpdateTime(DateUtils.getNowDate());
        int num = labApprovalMapper.updateLabApproval(labApproval);

        // 先删除之前的数据
        labApprovalDetailMapper.deleteLabApprovalDetailByApprovalId(labApproval.getId());
        for (LabApprovalDetail approvalDetail : approvalDetails) {
            approvalDetail.setApprovalId(labApproval.getId());
            approvalDetail.setCreateTime(DateUtils.getNowDate());
        }
        // 再保存提交资料
        labApprovalDetailMapper.insertBatch(approvalDetails);
        return num;
    }

    /**
     * 安全准入审批操作
     *
     * @param labApproval 安全准入审批操作
     * @return 结果
     */
    @Override
    @Transactional
    public int appOperation(LabApproval labApproval) {
        labApproval.setPassedDate(new Date());
        LabApprovalAndDetailDTO dto = labApprovalMapper.selectLabApprovalById(labApproval.getId());
        LabSecurityGroup security = labSecurityGroupMapper.selectLabSecurityGroupById(dto.getSecurityGroupId());

        GregorianCalendar now = new GregorianCalendar();
        SimpleDateFormat fmtrq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df = DateFormat.getDateInstance();
        System.out.println(fmtrq.format(now.getTime()));
        now.add(GregorianCalendar.MONTH, Integer.parseInt(security.getEffectiveTime() + ""));   //可以是天数或月数  数字自定 -6前6个月
        System.out.println(fmtrq.format(now.getTime()));

        Date date = now.getTime();
        labApproval.setExpirationDate(date);
        int num = labApprovalMapper.updateLabApproval(labApproval);

        LabApprovalAndDetailDTO labApprovalAndDetailDTO = labApprovalMapper.selectLabApprovalById(labApproval.getId());
        if(labApprovalAndDetailDTO!=null){
            //查询当前人员是否获取实验室安全证书
            List<LabApprovalVO> cardList = labApprovalMapper.selectLabCardByUserid(labApprovalAndDetailDTO.getJoinUserId());
            Integer gainSafeCert;
            if(cardList.size()>0){
                gainSafeCert = 1;
            }else{
                gainSafeCert = 0;
            }
            Map<String,Object> initMap = new HashMap<>();
            initMap.put("joinUserId",labApprovalAndDetailDTO.getJoinUserId());
            initMap.put("nickName",labApprovalAndDetailDTO.getNickName());
            initMap.put("userName",labApprovalAndDetailDTO.getUserName());
            initMap.put("gainSafeCert",gainSafeCert);
            initMap.put("gainSubSafeCert",1);
            initMap.put("reason","获取实验室安全准入资格");
            remoteExamService.initCreditPoints(initMap);
        }

        return num;
    }

    /**
     * 安全准入拒绝操作
     *
     * @param labApproval 安全准入拒绝操作
     * @return 结果
     */
    @Override
    @Transactional
    public int failedOperation(LabApproval labApproval) {
        labApproval.setFailedDate(new Date());
        int num = labApprovalMapper.updateLabApproval(labApproval);
        return num;
    }

    /**
     * 批量删除安全准入审批记录
     *
     * @param ids 需要删除的安全准入审批记录主键
     * @return 结果
     */
    @Override
    public int deleteLabApprovalByIds(Long[] ids) {
        return labApprovalMapper.deleteLabApprovalByIds(ids);
    }

    /**
     * 删除安全准入审批记录信息
     *
     * @param id 安全准入审批记录主键
     * @return 结果
     */
    @Override
    public int deleteLabApprovalById(Long id) {
        return labApprovalMapper.deleteLabApprovalById(id);
    }

    /**
     * 通过实验室 查询对应的安全准入规则 1V1
     */
    @Override
    public LabSecurityGroupVO querySecurityBySubjectId(Long subjectId) {
        return labSecurityGroupMapper.querySecurityBySubjectId(subjectId);
    }


    /**
     * 统计安全准入审批不同列表信息
     *
     * @param labApproval
     * @return 统计安全准入审批不同列表信息
     */
    @Override
    public LabApprovalVO getApprovalCount(LabApproval labApproval) {
        return labApprovalMapper.getApprovalCount(labApproval);
    }


    /**
     * 查询安全准入审批记录列表
     *
     * @param labApproval 安全准入审批记录
     * @return 安全准入审批记录
     */
    @Override
    public List<LabApprovalVO> getApprovalList(LabApproval labApproval) {
        return labApprovalMapper.getApprovalList(labApproval);
    }

    @Override
    public List<LabApprovalVO> selectApprovalListByUser(LabApproval labApproval) {
        return labApprovalMapper.selectApprovalListByUser(labApproval);
    }

    /**
     * 大屏 安全考试与安全准入统计
     */
    @Override
    public List<Map<String, Object>> statistics(LabApproval labApproval) {
        return labApprovalMapper.statistics(labApproval);
    }
}
