package com.docus.server.report.listener;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.collection.entity.TBasic;
import com.docus.server.collection.service.ITBasicService;
import com.docus.server.report.api.DownPlatformService;
import com.docus.server.report.api.dto.ReportDownDto;
import com.docus.server.report.api.dto.ReportDownPatientDto;
import com.docus.server.report.api.dto.ReportDownScanFileDto;
import com.docus.server.report.api.dto.ReportDto;
import com.docus.server.report.entity.AfReportRecord;
import com.docus.server.report.event.TaskConsumptionReportDownEvent;
import com.docus.server.report.event.ThreePartyPushReportDownEvent;
import com.docus.server.report.mapper.AfReportRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * 上报下载监听
 *
 * @author wyb
 */
@Component
@Slf4j
public class ReportDownListener {
    @Resource
    private DownPlatformService downPlatformService;

    @Resource
    private AfReportRecordMapper afReportRecordMapper;

    @Resource
    private ITBasicService itBasicService;

    @EventListener
    @Async("threadPoolExecutor")
    public void threePartyPushReportDown(ThreePartyPushReportDownEvent threePartyPushReportDownEvent) {
        // 根据任务id获取上报记录信息
        AfReportRecord afReportRecord = afReportRecordMapper.getReportRecordInfoByTaskId(threePartyPushReportDownEvent.getTaskId());

        // 病案是否是婴儿
        boolean isBaby = itBasicService.getIsBabyBasic(afReportRecord.getPatientId());
        if (isBaby) {
            // 如果是婴儿查找母亲的信息
            TBasic parentPatientInfo = itBasicService.getSdRyParentPatientInfo(afReportRecord.getPatientId());
            if (Objects.isNull(parentPatientInfo)) {
                log.warn("住院号：{}，住院次数：{}，病案主键：{} 是婴儿病案，未关联查询到母亲信息，不进行下载！", afReportRecord.getInpatientNo(), afReportRecord.getAdmissTimes(), afReportRecord.getPatientId());
                return;
            }
            // 婴儿的报告要推给母亲，修改为母亲信息
            afReportRecord.setPatientId(parentPatientInfo.getPatientId());
            afReportRecord.setInpatientNo(parentPatientInfo.getInpatientNo());
            afReportRecord.setAdmissTimes(parentPatientInfo.getAdmissTimes());
            afReportRecord.setJzh(parentPatientInfo.getJzh());
        }

        // 组织基础信息数据
        ReportDownPatientDto reportDownPatientDto = new ReportDownPatientDto(afReportRecord);

        // 组织文件数据
        List<ReportDownScanFileDto> reportDownScanFileDtos = new ArrayList<>(5);
        ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto(afReportRecord);
        reportDownScanFileDtos.add(reportDownScanFileDto);

        // 组织下载数据，基础信息和文件数据
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setAssortid(afReportRecord.getZdAssortId());
        reportDownDto.setCollectorid(afReportRecord.getSysflag());
        reportDownDto.setScanusercode("admin");
        reportDownDto.setScanusername("admin");
        reportDownDto.setPatient(reportDownPatientDto);
        reportDownDto.setScanfiles(reportDownScanFileDtos);

        // 下面是调用下载服务
        CommonResult result = downPlatformService.report(reportDownDto);
        if (ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            // 下载返回了成功更新状态
            afReportRecordMapper.updateStateByTaskId(threePartyPushReportDownEvent.getTaskId());
        }
    }


    @EventListener
    @Async("threadPoolExecutor")
    public void taskConsumptionReporDown(TaskConsumptionReportDownEvent taskConsumptionReportDownEvent) {
        ReportDto reportDto = taskConsumptionReportDownEvent.getReportDto();
        // 组织基础信息数据
        ReportDownPatientDto reportDownPatientDto = new ReportDownPatientDto(reportDto);

        // 组织文件数据
        List<ReportDownScanFileDto> reportDownScanFileDtos = new ArrayList<>(5);
        ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto(reportDto);
        reportDownScanFileDtos.add(reportDownScanFileDto);

        // 组织下载数据，基础信息和文件数据
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setAssortid(reportDto.getAssortId());
        reportDownDto.setCollectorid(reportDto.getSysFlag());
        reportDownDto.setScanusercode("admin");
        reportDownDto.setScanusername("admin");
        reportDownDto.setPatient(reportDownPatientDto);
        reportDownDto.setScanfiles(reportDownScanFileDtos);

        // 下面是调用下载服务
        downPlatformService.report(reportDownDto);
    }


    public static void main(String[] args) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();


        String url = "http://192.168.161.102:9291/api/downplatform/scansionReportBatch";
//        String url="http://127.0.0.1:9291/api/downplatform/scansionReportBatch";
        Map<String, Object> bodyMap = new HashMap<>();
        Map<String, Object> patientMap = new HashMap<>();
        patientMap.put("patientid", "8099350542");
        List<Map<String, Object>> scanfiles = new ArrayList<>();


//        FileInputStream inputStream = new FileInputStream("d://wyb.png");
//        System.out.println(inputStream.available());
//        byte[] bytes = new byte[inputStream.available()];
//        inputStream.read(bytes,0,inputStream.available());
//        inputStream.close();
//        String base641 = encoder.encode(bytes);
//        Map<String, Object> scanfile1Map=new HashMap<>();
//        scanfile1Map.put("assortid","docustestAssortID");
//        scanfile1Map.put("downurl",base641);
//        scanfile1Map.put("filestoragetype",1);
//        scanfile1Map.put("filetitle","嘉时测试图片1");
//        scanfile1Map.put("filetype","2");
//        scanfile1Map.put("serialnum","嘉时测试图片1");


        FileInputStream inputStream2 = new FileInputStream("d://jianli_02.jpg");
        System.out.println(inputStream2.available());
        byte[] bytes2 = new byte[inputStream2.available()];
        inputStream2.read(bytes2, 0, inputStream2.available());
        inputStream2.close();
        String base642 = encoder.encode(bytes2);
        Map<String, Object> scanfile2Map = new HashMap<>();
        scanfile2Map.put("assortid", "docustestAssortID");
        scanfile2Map.put("downurl", base642);
        scanfile2Map.put("filestoragetype", 1);
        scanfile2Map.put("filetitle", "嘉时测试图片2");
        scanfile2Map.put("filetype", "2");
        scanfile2Map.put("serialnum", "嘉时测试图片2");


//
//        scanfiles.add(scanfile1Map);
        scanfiles.add(scanfile2Map);
        bodyMap.put("patient", patientMap);
        bodyMap.put("ip", "wybtest");
        bodyMap.put("collectorid", "docus测试扫描");
        bodyMap.put("scanfiles", scanfiles);
        bodyMap.put("scanusercode", "docus测试");
        bodyMap.put("scanusername", "docus测试");
        HttpRequest post = HttpUtil.createPost(url);
        post.timeout(5 * 1000);
        post.header("Content-Type", "application/json; charset=utf-8");
        post.body(JSON.toJSONString(bodyMap));
        HttpResponse response = post.execute();
    }
}
