package com.docus.server.report.job;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.redis.service.RedisOps;
import com.docus.server.common.entity.SdryPacsPrintExcept;
import com.docus.server.common.service.SdryPacsPrintExceptService;
import com.docus.server.common.util.FileUtil;
import com.docus.server.report.api.dto.ReportDto;
import com.docus.server.report.service.ReportService;
import com.docus.server.report.util.XmlUtil;
import com.docus.server.report.webservice.WebserviceMessageType;
import com.docus.server.report.webservice.impl.HIP1008InspectionReportAdditionHandler;
import com.docus.server.report.webservice.impl.HIP1009InspectionReportUpdatesHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * pacs获取base64报告相关xxl-Job
 *
 * @author jiashi
 */
@Component
@Slf4j
public class FetchPacsBase64Job {
    /**
     * 从pacs获取pdf报告base64内容时间过长，异步使用队列，采用job获取
     */
    public final static String FETCH_PACS_BASE64_QUEUE_HIP1008 = "docus:sdry:pacsbase64:" + WebserviceMessageType.HIP1008;
    public final static String FETCH_PACS_BASE64_QUEUE_HIP1009 = "docus:sdry:pacsbase64:" + WebserviceMessageType.HIP1009;

    @Resource
    private ReportService reportService;
    @Resource
    private RedisOps redisOps;
    @Resource
    private HIP1008InspectionReportAdditionHandler hip1008;
    @Resource
    private HIP1009InspectionReportUpdatesHandler hip1009;
    @Resource
    private SdryPacsPrintExceptService sdryPacsPrintExceptService;
    @Resource
    private IdService idService;

    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now().plusMonths(-3);
        String beginDateTime = localDate.toString() + " 00:00:00";
        System.out.println(beginDateTime);
    }


    @XxlJob("compensateFetchBase64ReportJob")
    public void compensateFetchBase64ReportJob() {
        LocalDate localDate = LocalDate.now().plusMonths(-3);
        String beginDateTime = localDate.toString() + " 00:00:00";
        List<Long> compensateIds = sdryPacsPrintExceptService.getCompensateIds(beginDateTime);
        log.info("补偿失败的pacs获取base64文件数据JOB开始，本次补偿 {} 条数据！", compensateIds.size());
        if (Func.isNotEmpty(compensateIds)) {
            for (Long id : compensateIds) {
                try {
                    compensateFetchBase64Report(id);
                } catch (Exception ex) {
                    log.error("补偿失败的pacs，补偿id：" + id + " 补偿失败了。", ex);
                }
            }
        }
        log.info("补偿失败的pacs获取base64文件数据JOB结束！");
    }

    /**
     * 检查报告1008新增需要获取base64报告的job
     */
    @XxlJob("fetchBase64ReportHip1008Job")
    public void fetchBase64ReportHip1008Job() {
        String xml = redisOps.rPop(FETCH_PACS_BASE64_QUEUE_HIP1008);
        ReportDto reportDto = parse(WebserviceMessageType.HIP1008, xml);
        if (reportDto != null) {
            reportService.report(reportDto);
            return;
        }
        String filePath = FileUtil.currentPath() + File.separator + "fetch-base64-xml"
                + File.separator + WebserviceMessageType.HIP1008
                + File.separator + Func.formatDate(LocalDate.now())
                + File.separator + idService.getDateSeq();
        FileUtil.saveStrData(xml, new File(filePath));
        ReportDto reportDto2 = hip1008.getReportDtoByInspectionInsert(XmlUtil.of(xml));
        SdryPacsPrintExcept pacsPrintExcept = new SdryPacsPrintExcept();
        pacsPrintExcept.setInpatientNo(reportDto2.getInpatientNo());
        pacsPrintExcept.setAdmissTimes(reportDto2.getAdmisstimes());
        pacsPrintExcept.setJzh(reportDto2.getJzh());
        pacsPrintExcept.setReportMessagePath(filePath);
        pacsPrintExcept.setServiceFlag(WebserviceMessageType.HIP1008);
        pacsPrintExcept.setState(0);
        pacsPrintExcept.setCreateTime(new Date());
        pacsPrintExcept.setExamReportSn(reportDto2.getReportSn());
        sdryPacsPrintExceptService.insert(pacsPrintExcept);
    }

    /**
     * 检查报告1009更新需要获取base64报告的job
     */
    @XxlJob("fetchBase64ReportHip1009Job")
    public void fetchBase64ReportHip1009Job() {
        String xml = redisOps.rPop(FETCH_PACS_BASE64_QUEUE_HIP1009);
        ReportDto reportDto = parse(WebserviceMessageType.HIP1009, xml);
        if (reportDto != null) {
            reportService.report(reportDto);
            return;
        }
        String filePath = FileUtil.currentPath() + File.separator + "fetch-base64-xml"
                + File.separator + WebserviceMessageType.HIP1009
                + File.separator + Func.formatDate(LocalDate.now())
                + File.separator + idService.getDateSeq();
        FileUtil.saveStrData(xml, new File(filePath));
        ReportDto reportDto2 = hip1009.getReportDtoByInspectionUpdate(XmlUtil.of(xml));
        SdryPacsPrintExcept pacsPrintExcept = new SdryPacsPrintExcept();
        pacsPrintExcept.setInpatientNo(reportDto2.getInpatientNo());
        pacsPrintExcept.setAdmissTimes(reportDto2.getAdmisstimes());
        pacsPrintExcept.setJzh(reportDto2.getJzh());
        pacsPrintExcept.setReportMessagePath(filePath);
        pacsPrintExcept.setServiceFlag(WebserviceMessageType.HIP1009);
        pacsPrintExcept.setState(0);
        pacsPrintExcept.setExamReportSn(reportDto2.getReportSn());
        pacsPrintExcept.setCreateTime(new Date());
        sdryPacsPrintExceptService.insert(pacsPrintExcept);
    }

    public void compensateFetchBase64Report(Long id) {
        // base64的和job的检查报告统一处理逻辑，不然会出现重复
        SdryPacsPrintExcept except = sdryPacsPrintExceptService.getById(id);
        if(Objects.isNull(except)){
            log.error("未找到id为：{} 的获取pacs异常的数据！",id);
            return;
        }
        String messagePath = except.getReportMessagePath();
        String xml = FileUtil.readStr(new File(messagePath));
        if (Objects.isNull(xml)) {
            log.error("文件：{},获取xml内容为空！", messagePath);
            return;
        }
        ReportDto reportDto = parse(except.getServiceFlag(), xml);
        if (reportDto != null) {
            reportService.report(reportDto);
            sdryPacsPrintExceptService.compensateSuccuss(id);
        }
    }

    private ReportDto parse(String serviceFlag, String xml) {
        XmlUtil xmlUtil = XmlUtil.of(xml);
        if (serviceFlag.equals(WebserviceMessageType.HIP1008)) {
            return hip1008.fetchBase64Parse(xmlUtil);
        }
        if (serviceFlag.equals(WebserviceMessageType.HIP1009)) {
            return hip1009.fetchBase64Parse(xmlUtil);
        }
        return null;
    }

}
