package com.docus.server.gzzxyjh.job;

import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.gzzxyjh.AssortConfig;
import com.docus.server.gzzxyjh.FileDto;
import com.docus.server.rpc.DownPlatformService;
import com.docus.server.rpc.TaskDistributeService;
import com.docus.server.rpc.dto.*;
import com.docus.server.util.JaxWsDynamicClientUtil;
import com.docus.server.util.TableJsonRead;
import com.docus.server.util.XmlUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author YongBin Wen
 * @date 2024/8/16 14:45
 */
@Component
@Slf4j
public class GzZxyJhPMRSCollectJob {

    @Autowired
    private DownPlatformService downPlatformService;
    @Autowired
    private TaskDistributeService taskDistributeService;


    @XxlJob("GzZxyJhPMRSCollectJob")
    public void pmrsCollectJob() {
        // 1.获取任务和患者信息 2.查询接口文件 3.上报下载
        List<AssortConfig.Config> assortConfig = AssortConfig.getConfig();

        String configPath = "data-config";
        String configName = "gzzxyjh-ws-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pmrsConfig = configOjb.getJSONObject("pmrs");
        String collectorId = pmrsConfig.getString("collectorId");
        String url = pmrsConfig.getString("url");
        String namespaceUri = pmrsConfig.getString("namespaceUri");
        String operationName = pmrsConfig.getString("operationName");
        String param1 = pmrsConfig.getString("param");

        CommonResult<ReportDownTwoDto> commonResult = taskDistributeService.getNoViewTaskByCollectorId(collectorId);
        if (ResultCode.SUCCESS.getCode().equals(commonResult.getCode())
                && commonResult.getData() != null) {
            ReportDownTwoDto downTwoDto = commonResult.getData();
            ReportTaskTwoDto task = downTwoDto.getTasks().get(0);
            log.info(">>>>>>>>>>>>>>>>>>>>>> 广州中西医结合pmrs采集任务，获取了任务：{}", Func.toJson(task));

            ReportHospitalTwoDto hospitalTwoDto = downTwoDto.getHospitals().get(0);
            ReportPatientTwoDto reportPatientTwoDto = downTwoDto.getPatient();
            String jzh = downTwoDto.getJzh();
            jzh = jzh.split("_")[0];

            String param2 = "<MESSAGE><BODY><ROWS><ROW><VISIT_NO>" + jzh + "</VISIT_NO></ROW></ROWS></BODY></MESSAGE>";
            String[] params = {param1, param2};
            Object resultObj = JaxWsDynamicClientUtil.send(url, namespaceUri, operationName, params);
            String result = String.valueOf(resultObj);
            List<FileDto> fileDtos = parseFileDtos(result);

            int size = fileDtos.size();
            log.info("住院号：{}，住院次数：{},记账号：{} 采集pmrs数据：{} 条！数据：{}", reportPatientTwoDto.getInpatientNo(), hospitalTwoDto.getAdmissTimes(), jzh, size, Func.toJson(fileDtos));
            if (size <= 0) {
                return;
            }

            ReportDownPatientDto patient = new ReportDownPatientDto();
            patient.setPatientid(downTwoDto.getPatientId());

            ReportDownDto reportDownDto = new ReportDownDto();
            reportDownDto.setCollectorid(collectorId);
            reportDownDto.setIp("java-pmrs-job");
            reportDownDto.setPatient(patient);

            int sort = 0;
            for (FileDto fileDto : fileDtos) {
                ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
                reportDownScanFileDto.setDownurl(fileDto.getPMR_URL());
                reportDownScanFileDto.setFiletitle(fileDto.getPMR_NAME());
                reportDownScanFileDto.setSerialnum(fileDto.getPMR_ID());
                reportDownScanFileDto.setFilesource(1);
                reportDownScanFileDto.setFiletype(1);
                reportDownScanFileDto.setFilestoragetype(1);
                reportDownScanFileDto.setTaskid(task.getTaskId());
                reportDownScanFileDto.setSort(++sort);
                List<ReportDownScanFileDto> scanFiles = Collections.singletonList(reportDownScanFileDto);

                String emrTypeCode = fileDto.getEMR_TYPE_CODE();
                String assortId = getAssortId(emrTypeCode, assortConfig);
                reportDownDto.setAssortid(assortId);
                reportDownDto.setScanfiles(scanFiles);
                downPlatformService.report(reportDownDto);
            }


        }
    }

    private List<FileDto> parseFileDtos(String str) {

        XmlUtil xml = XmlUtil.of(str);
        //请求结果状态
        String status = "0";
        Node statusNode = xml.getNode("/MESSAGE/HEADER/STATUS");
        if (Func.isNotEmpty(statusNode)) {
            status = statusNode.getTextContent();
        }
        if ("0".equals(status)) {
            return new ArrayList<>();
        }
        List<FileDto> list = new ArrayList<FileDto>();
        NodeList rows = xml.getNodeList("/MESSAGE/BODY/ROWS/ROW");
        for (int i = 1; i <= rows.getLength(); i++) {
            Node PMR_ID_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/PMR_ID");
            String PMR_ID = null;
            if (Func.isNotEmpty(PMR_ID_NODE)) {
                PMR_ID = PMR_ID_NODE.getTextContent();
            }
            Node PMR_NAME_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/PMR_NAME");
            String PMR_NAME = null;
            if (Func.isNotEmpty(PMR_NAME_NODE)) {
                PMR_NAME = PMR_NAME_NODE.getTextContent();
            }
            Node PMR_NAME_NO_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/PMR_NAME_NO");
            String PMR_NAME_NO = null;
            if (Func.isNotEmpty(PMR_NAME_NO_NODE)) {
                PMR_NAME_NO = PMR_NAME_NO_NODE.getTextContent();
            }
            Node PMR_URL_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/PMR_URL");
            String PMR_URL = null;
            if (Func.isNotEmpty(PMR_URL_NODE)) {
                PMR_URL = PMR_URL_NODE.getTextContent();
            }
            Node RCD_TYPE_CODE_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/RCD_TYPE_CODE");
            String RCD_TYPE_CODE = null;
            if (Func.isNotEmpty(RCD_TYPE_CODE_NODE)) {
                RCD_TYPE_CODE = RCD_TYPE_CODE_NODE.getTextContent();
            }
            Node RCD_TYPE_NAME_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/RCD_TYPE_NAME");
            String RCD_TYPE_NAME = null;
            if (Func.isNotEmpty(RCD_TYPE_NAME_NODE)) {
                RCD_TYPE_NAME = RCD_TYPE_NAME_NODE.getTextContent();
            }
            Node EMR_TYPE_CODE_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/EMR_TYPE_CODE");
            String EMR_TYPE_CODE = null;
            if (Func.isNotEmpty(EMR_TYPE_CODE_NODE)) {
                EMR_TYPE_CODE = EMR_TYPE_CODE_NODE.getTextContent();
            }
            Node EMR_TYPE_NAME_NODE = xml.getNode("/MESSAGE/BODY/ROWS/ROW[" + i + "]/EMR_TYPE_NAME");
            String EMR_TYPE_NAME = null;
            if (Func.isNotEmpty(EMR_TYPE_NAME_NODE)) {
                EMR_TYPE_NAME = EMR_TYPE_NAME_NODE.getTextContent();
            }
            if (Func.isEmpty(PMR_URL)) {
                throw new BaseException("第" + i + "条文件数据文件地址为空");
            }
            FileDto dto = new FileDto();
            dto.setPMR_ID(PMR_ID);
            dto.setPMR_NAME(PMR_NAME);
            dto.setPMR_NAME_NO(PMR_NAME_NO);
            dto.setPMR_URL(PMR_URL);
            dto.setRCD_TYPE_CODE(RCD_TYPE_CODE);
            dto.setRCD_TYPE_NAME(RCD_TYPE_NAME);
            dto.setEMR_TYPE_CODE(EMR_TYPE_CODE);
            dto.setEMR_TYPE_NAME(EMR_TYPE_NAME);
            list.add(dto);
        }
        return list;

    }

    private String getAssortId(String emrTypeCode, List<AssortConfig.Config> assortConfig) {
        String defaut = "";
        for (AssortConfig.Config config : assortConfig) {
            if (emrTypeCode.equals(config.getEmrTypeCode())) {
                return config.getAssortId();
            }
            if ("defaut".equals(config.getEmrTypeCode())) {
                defaut = config.getAssortId();
            }
        }
        return defaut;
    }

    public static void main(String[] args) {
        System.out.println(AssortConfig.getConfig());
        String jzh = "10086_1";
        jzh = jzh.split("_")[0];
        System.out.println(jzh);
        String configPath = "data-config";
        String configName = "gzzxyjh-ws-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pmrsConfig = configOjb.getJSONObject("pmrs");
        System.out.println(pmrsConfig);
    }
}
