package com.casic.missiles.service.listeners.processor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.casic.missiles.dto.flowable.NotifyEventStatusDTO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.business.MeasureTypeEnum;
import com.casic.missiles.enums.notifyevent.ActionStatusBeanEnum;
import com.casic.missiles.enums.sample.SampleStatusEnum;
import com.casic.missiles.enums.system.ApprovalStatusEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessOrderMapper;
import com.casic.missiles.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.model.business.BusinessOrder;
import com.casic.missiles.service.listeners.NotifyEventPostProcessor;
import com.casic.missiles.mapper.business.BusinessCertificatePrintMapper;
import com.casic.missiles.mapper.business.BusinessCertificateReportMapper;
import com.casic.missiles.mapper.customer.CustomerSampleMapper;
import com.casic.missiles.model.business.BusinessCertificatePrint;
import com.casic.missiles.model.business.BusinessCertificateReport;
import com.casic.missiles.model.customer.CustomerSampleInfo;
import com.casic.missiles.service.listeners.register.PrintFileRegister;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author zt
 * <p>
 * 证书报告审批通过状态回填
 */
@Slf4j
@Service(ActionStatusBeanEnum.CERTIFICATE_REPORT_BEAN_NAME)
public class CertificateReportEventPostProcessor implements NotifyEventPostProcessor {

    @Override
    public void doHandleNotifyEvent(NotifyEventStatusDTO notifyEventStatusDTO) {
        Long id = Long.valueOf(notifyEventStatusDTO.getId());
        Assert.isFalse(Objects.isNull(id), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        BusinessCertificateReportMapper certificateReportMapper = SpringContextUtil.getBean(BusinessCertificateReportMapper.class);
        CustomerSampleMapper sampleMapper = SpringContextUtil.getBean(CustomerSampleMapper.class);
        BusinessOrderMapper orderMapper = SpringContextUtil.getBean(BusinessOrderMapper.class);
        BusinessOrderSampleRelationMapper orderSampleRelationMapper = SpringContextUtil.getBean(BusinessOrderSampleRelationMapper.class);

        BusinessCertificateReport certificateReport = new BusinessCertificateReport();
        certificateReport.setId(id);
        //设置审批状态为通过
        certificateReport.setApprovalStatus(ApprovalStatusEnum.PASSED);
        certificateReport.setUpdateTime(DateUtil.formatDateTime(new Date()));
        int row = certificateReportMapper.updateById(certificateReport);
        //更新样品有效期和待归还状态
        BusinessCertificateReport certificateReport1 = certificateReportMapper.selectById(id);
        if (certificateReport1.getSampleId() != null&&certificateReport1.getOrderId()!= null) {
            CustomerSampleInfo sampleInfo = sampleMapper.selectById(certificateReport1.getSampleId());
            BusinessOrder businessOrder = orderMapper.selectById(certificateReport1.getOrderId());
            if (sampleInfo != null) {
                //比较哪个时间更早
                String endTime = sampleInfo.getValidDeadline();
                if (StringUtils.isNotEmpty(endTime)) {
                    endTime = DateUtil.compare(DateUtil.parseDateTime(endTime), DateUtil.parseDateTime(certificateReport1.getExpirationDate())) < 0 ?
                            endTime : certificateReport1.getExpirationDate();
                }
                sampleInfo.setValidDeadline(StringUtils.isNotEmpty(endTime) ? endTime : certificateReport1.getExpirationDate());
                int rs = sampleMapper.updateById(sampleInfo);
                if (row < 1 || rs < 1) throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
                //若样品是自检或现场检查方式、已全部检定完成更新样品待归还状态
                if (MeasureTypeEnum.INSIDE_MEASURE.equals(sampleInfo.getMeasureType())&&businessOrder!=null) {
                    //获取样品已取得的证书不小于应出具的总数时更新样品待归还状态
                    if(certificateReportMapper.selectSampleCertifications(sampleInfo.getId(), businessOrder.getId())>=
                            certificateReportMapper.selectSampleCertificationAlls(sampleInfo.getId(), businessOrder.getId())) {
                        orderSampleRelationMapper.updateByOrderIdAndSampleId(businessOrder.getId(),sampleInfo.getId(), SampleStatusEnum.TO_GIVE_BACK);
                    }
                }
            }
        }

        //获取证书报告信息
        certificateReport = certificateReportMapper.selectById(id);
        //进行证书报告生成，并在远程注册服务器注册
        PrintFileRegister printFileRegister = SpringContextUtil.getBean(PrintFileRegister.class);
        try {
            DictCodeUtils.convertDictCodeToName(certificateReport);
            String  printFileName = printFileRegister.registerPrintFile(certificateReport, certificateReport.getCertificateReportTypeName());
            //生成证书打印信息
            CertificatePrintBuilder(certificateReport, printFileName);
        } catch (Exception ex) {
            log.error("打印异常，证书报告信息为{},异常信息为{}", JSONObject.toJSON(certificateReport), ex);
        }

    }

    /**
     * 通过审批的证书报告，产生证书打印
     */
    private void CertificatePrintBuilder(BusinessCertificateReport certificateReport, String printFileName) {
        BusinessCertificatePrintMapper certificatePrintMapper = SpringContextUtil.getBean(BusinessCertificatePrintMapper.class);
        BusinessCertificatePrint certificatePrint = getCertificatePrintByReport(certificateReport, printFileName);
        int row = certificatePrintMapper.insert(certificatePrint);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        }
    }


    /**
     * 审批通过的证书报告，生成相应的证书打印信息
     *
     * @param certificateReport
     * @return
     */
    private BusinessCertificatePrint getCertificatePrintByReport(BusinessCertificateReport certificateReport, String printFileName) {
        BusinessCertificatePrint certificatePrint = BusinessCertificatePrint.builder()
                .certificateReportCode(certificateReport.getCertificateReportCode())
                .certificateReportFile(certificateReport.getCertificateReportFile())
                .certificateReportType(certificateReport.getCertificateReportType())
                .certificateReportCategory(certificateReport.getCertificateReportCategory())
                .certificateReportName(certificateReport.getCertificateReportName())
                .measureDeptId(certificateReport.getMeasureDeptId())
                .measurePersonId(certificateReport.getMeasurePersonId())
                .originalRecordId(certificateReport.getOriginalRecordId())
                .remark(certificateReport.getRemark())
                .sampleId(certificateReport.getSampleId())
                .orderId(certificateReport.getOrderId())
                .templateId(certificateReport.getTemplateId())
                .signId(certificateReport.getSignId())
                .printFileName(printFileName)
                .printNum(0)
                .printStatus("1")
                .createUser(certificateReport.getCreateUser())
                .build();
        return certificatePrint;
    }

}
