/*
 * Copyright ©2023 CJB-CNIT Team. All rights reserved
 */
package com.openhis.yb.service;

import static com.alibaba.fastjson2.JSON.parseObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import com.openhis.yb.domain.InpatientDischarge;
import com.openhis.yb.domain.InpatientReg;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.core.common.exception.ServiceException;
import com.core.common.utils.SecurityUtils;
import com.core.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.openhis.financial.domain.Contract;
import com.openhis.financial.service.IContractService;
import com.openhis.financial.service.impl.ContractServiceImpl;
import com.openhis.yb.domain.ClinicReg;
import com.openhis.yb.dto.*;
import com.openhis.yb.model.Clinic2207OrderModel;
import com.openhis.yb.model.Clinic2207OrderParam;
import com.openhis.yb.util.YbParamBuilderUtil;

/**
 * http请求接口
 *
 * @author SunJQ
 * @date 2025-04-11
 */
@Service
public class YbHttpUtils {

    @Autowired
    YbParamBuilderUtil ybParamBuilderUtil;
    @Autowired
    IContractService iContractService;

    Logger logger = LoggerFactory.getLogger(YbHttpUtils.class);
    @Autowired
    private ContractServiceImpl contractServiceImpl;

    public Info1101Output getPerInfo(Info1101ReadcardParam readcard) {
        // 声明参数
        Result result = null;
        Info1101Output perinfo = null;
        // 发送请求
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/getPatinfo", readcard, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(resultString));
        logger.info("【1101】返回参数:" + resultString);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(resultString, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            perinfo = parseObject(JSON.toJSONString(result.getResult()), Info1101Output.class);
        } else {
            throw new ServiceException(result.getMessage());
        }

        return perinfo;
    }

    public ClinicReg2201Output reg(ClinicReg reg, Contract contract) {
        // 声名参数
        Result result = null;
        ClinicReg2201Output clinicReg2201Output = new ClinicReg2201Output();
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/reg", reg, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【2201】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinicReg2201Output = parseObject(JSON.toJSONString(result.getResult()), ClinicReg2201Output.class);
        } else {
            throw new ServiceException(result.getMessage());
        }
        return clinicReg2201Output;
    }

    public ClinicReg2201Output cancelReg(ClinicReg reg, Contract contract) {
        // 声名参数
        Result result = null;
        ClinicReg2201Output clinicReg2201Output = new ClinicReg2201Output();
        // 发送请求
        String s =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/cancelReg", reg, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【2202】返回参数:" + JSON.toJSONString(s));
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinicReg2201Output = parseObject(JSON.toJSONString(result.getResult()), ClinicReg2201Output.class);
        } else {
            throw new ServiceException(result.getMessage());
        }
        return clinicReg2201Output;
    }

    public Clinic2204OrderResult upload2204Record(Clinic2204OrderParam clinic2204OrderParam, Contract contract) {
        Clinic2204OrderResult clinicFeedetail2204Result = new Clinic2204OrderResult();
        // 声名参数
        Result result = null;
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/upload2204-record",
            clinic2204OrderParam, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【2204】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinicFeedetail2204Result = parseObject(JSON.toJSONString(result.getResult()), Clinic2204OrderResult.class);
        } else {
            throw new ServiceException(result.getMessage());
        }

        return clinicFeedetail2204Result;

    }

    public Clinic2206OrderOutput upload2206Record(Clinic2206OrderParam clinic2206OrderParam, Contract contract) {

        Clinic2206OrderOutput clinic2206OrderResult = new Clinic2206OrderOutput();
        // 声名参数
        Result result = null;
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/preSetl",
            clinic2206OrderParam, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2206】返回参数:" + JSON.toJSONString(s));
        logger.info(s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinic2206OrderResult = parseObject(JSON.toJSONString(result.getResult()), Clinic2206OrderOutput.class);
        } else {
            throw new ServiceException(result.getMessage());
        }

        return clinic2206OrderResult;
    }

    public Clinic2207OrderModel settle(Clinic2207OrderParam clinicOrder2207, Contract contract) {

        Clinic2207OrderModel clinic2206OrderResult = new Clinic2207OrderModel();
        // 声名参数
        Result result = null;
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/setl", clinicOrder2207,
            contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【2207】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinic2206OrderResult = parseObject(JSON.toJSONString(result.getResult()), Clinic2207OrderModel.class);
        } else {
            throw new ServiceException(result.getMessage());
        }

        return clinic2206OrderResult;
    }

    public Sign9001Result sign(Sign signParam, Contract contract) {
        Sign9001Result sign = null;
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/signIn", signParam, contract);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(resultString));
        logger.info("【9001】返回参数:" + resultString);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            sign = parseObject(JSON.toJSONString(result.getResult()), Sign9001Result.class);
        } else {
            throw new ServiceException(result.getMessage());
        }

        return sign;
    }

    public void unPreSettle(Clinic2205OrderParam clinic2205OrderParam, Contract contract) {

        // 声名参数
        Result result = null;
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/unPreSettle",
            clinic2205OrderParam, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info(s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            return;
        } else {
            throw new ServiceException(result.getMessage());
        }
    }

    public Clinic2208UnSetlInfoOutput unSettle(Clinic2208UnSetlInfoParam clinicOrder2208, Contract contract) {

        Clinic2208UnSetlInfoOutput clinicOrder2206Result = new Clinic2208UnSetlInfoOutput();
        // 声名参数
        Result result = null;
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/cancelSetl",
            clinicOrder2208, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【2208】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            clinicOrder2206Result =
                parseObject(JSON.toJSONString(result.getResult()), Clinic2208UnSetlInfoOutput.class);
        } else {
            throw new ServiceException(result.getMessage());
        }
        return clinicOrder2206Result;
    }

    public Result directoryCheck(MedicalDirectory3301ListParam medicalDirectory3301ListParam) {

        Clinic2208UnSetlInfoResult clinicOrder2206Result = new Clinic2208UnSetlInfoResult();
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/directoryCheck",
            medicalDirectory3301ListParam, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【3301】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result directoryUnCheck(MedicalDirectory3302Param medicalDirectory3302Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/directoryUnCheck",
            medicalDirectory3302Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info("【3302】返回参数:" + s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result reconcileGeneralLedger(Financial3201Param financial3201Param) {

        // 此处先查询到合同并回填给入参对象
        Contract contract = iContractService.getContract(financial3201Param.getSetlOptins());
        if (contract == null) {
            throw new ServiceException("未查询到合同信息");
        }
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/reconcile",
            financial3201Param, contract);

        // 赋值（上述回填的两个参数医保不要，为了避免麻烦，在发送http后进行回填）
        financial3201Param.setFixmedinsCode(contract.getFixmedinsCode());
        financial3201Param.setFixmedinsName(contract.getFixmedinsName());

        // 医保回参逻辑处理
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info(s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public FinancialSettlement3202Result reconcileGeneralLedgerDetail(FinancialSettlement3202Param financial3202Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/reconcile-detail",
            financial3202Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info(s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        FinancialSettlement3202Result result = null;
        try {
            result = mapper.readValue(s, FinancialSettlement3202Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public List<FinancialSettlement3209AResult>
        threePartSearch(FinancialSettlement3209AParam financialSettlement3209AParam) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/three-part-search-err",
            financialSettlement3209AParam, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println(JSON.toJSONString(s));
        logger.info(s);
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        List<FinancialSettlement3209AResult> result = null;
        try {
            result = mapper.readValue(s, List.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public String applyFinancialClearing(Financial3203AParam financial3203AParam) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/apply-clearing",
            financial3203AParam, iContractService.getContract(financial3203AParam.getClrOptins()));
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        return s;
    }

    public Result cancelFinancialClearing(Financial3204Param financial3204Param) {

        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/cancel-clearing",
            financial3204Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Clearing3205AResult getFinancialClearingStatus(Clearing3205AParma clearing3205AParma) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/get-clearing-status",
            clearing3205AParma, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Clearing3205AResult result = null;
        try {
            result = mapper.readValue(s, Clearing3205AResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result uploadInventoryCount(MedicalInventory3501Param medicalInventory3501Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/upload-inventory-count",
            medicalInventory3501Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result updateInventoryCount(MedicalInventory3502Param medicalInventory3502Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/update-inventory",
            medicalInventory3502Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result procurement(Medical3503Param medical3503Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/procurement",
            medical3503Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result cancelProcurement(MedicalPurchase3504Param medicalPurchase3504Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/procurement-cancel",
            medicalPurchase3504Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result merchandise(Medical3505Param medical3505Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/merchandise",
            medical3505Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result cancelMerchandise(Medical3506Param medical3506Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/cancel-merchandise",
            medical3506Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result deleteGoodsInfo(Medical3507Param medical3507Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/del-goods",
            medical3507Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public MedicalInventory3511Output querySalesInfo(MedicalInventory3511Param medicalInventory3511Param) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/query-3511-info",
            medicalInventory3511Param, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 转业务参数
        MedicalInventory3511Output medicalInventory3511Output = null;
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 401) {
            System.out.println(JSON.toJSONString(result.getResult()));
            medicalInventory3511Output =
                parseObject(JSON.toJSONString(result.getResult()), MedicalInventory3511Output.class);
        } else {
            throw new ServiceException(result.getMessage());
        }
        return medicalInventory3511Output;
    }

    public Result getClrOptins(Clearing3206AParam clearing3206AParam) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/getclroptins",
            clearing3206AParam, null);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Result upload2203Record(Clinic2203MedicalParam medical2203Param, Contract contract) {
        // 发送请求
        String s = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/upload2203-record",
            medical2203Param, contract);
        if (StringUtils.isEmpty(s)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(s, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送http请求（2025/05/02经测试，若以自带的工具类发送请求失败，故使用原peis系统中成功调用的写法重新封装）
     *
     * @param url 路径
     * @param o 参数
     * @return
     */
    private String httpPost(String url, Object o, Contract contract) {
        String resultString = "";
        // 拼参数
        BaseParam baseParam = new BaseParam();
        baseParam.setBaseInfo(ybParamBuilderUtil.getBaseInfo(parseObject(JSON.toJSONString(o)), contract)).setData(o);
        logger.info("【请求路径】:" + url + ";【入参】: " + JSON.toJSONString(baseParam));
        // 创建Http请求
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000)
            .setSocketTimeout(30000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse response = null;
        // 发送请求
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(baseParam), ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response == null) {
                throw new ServiceException("Http请求异常，未接受返回参数");
            }
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("Http请求异常，请稍后再试。");
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("关闭响应异常", e);
                    throw new ServiceException("未关闭系统资源：" + e.getStackTrace());
                }
            }
        }
        return resultString;
    }

    public List<Catalogue1312Output> queryYbCatalogue(Catalogue1312QueryParam catalogue1312QueryParam) {
        List<Catalogue1312Output> outputList = new ArrayList<>();
        try {

            String resultString =
                httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/queryYbCatalogue",
                    catalogue1312QueryParam, null);
            // System.out.println("--------1312resultString-------------" + resultString);
            // 1. 解析外层 JSON
            ObjectMapper mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); // 启用 Snake Case 自动映射
            JsonNode rootNode = mapper.readTree(resultString);
            String resultStr = rootNode.get("result").asText();

            // 2. 解析 result 中的 JSON 数组
            outputList = mapper.readValue(resultStr, new TypeReference<List<Catalogue1312Output>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return outputList;
    }

    public ResponseEntity<String> upload9101(MultipartFile file, String filename) {

        // File9101Param file9101Param = new File9101Param();
        // file9101Param.setFile(file);
        // file9101Param.setFilename(filename);
        List<Contract> contractListByYb = iContractService.getContractListByYb();
        if (contractListByYb.isEmpty()) {
            throw new ServiceException("未配置医保合同");
        }
        // file9101Param.setFixmedinsCode(contractListByYb.get(0).getFixmedinsCode());
        // FileResult fileResult = null;
        ResponseEntity<String> response = null;
        // 参数处理
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            // 1. 保存到临时文件
            Path tempFile = Files.createTempFile("upload-", file.getOriginalFilename());
            file.transferTo(tempFile);

            // 2. 构建转发请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new FileSystemResource(tempFile.toFile()));
            body.add("fixmedinsCode", contractListByYb.get(0).getFixmedinsCode());
            body.add("userId", SecurityUtils.getUserId());
            body.add("admvs", contractListByYb.get(0).getAdmVs());

            // 3. 转发并删除临时文件
            RestTemplate restTemplate = new RestTemplate();
            response = restTemplate.postForEntity(
                SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/file-up2",
                new HttpEntity<>(body, headers), String.class);
            System.out.println(JSON.toJSONString(response));
            // 清理临时文件
            // Files.deleteIfExists(tempFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;

        // 2. 构建 Multipart 请求体
        // HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //
        // MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        // body.add("file", new ByteArrayResource(file.getBytes()) {
        // @Override
        // public String getFilename() {
        // return filename; // 保持原文件名
        // }
        // });
        //
        //// 3. 发送请求到目标服务
        // RestTemplate restTemplate = new RestTemplate();
        // HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        // ResponseEntity<String> response =
        // restTemplate.postForEntity(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/file-up2",
        // requestEntity, String.class);

        // try {
        // String resultString = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/file-up2",
        // file9101Param,null);
        // // System.out.println("--------1312resultString-------------" + resultString);
        // // 1. 解析外层 JSON
        // ObjectMapper mapper = new ObjectMapper();
        // mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); // 启用 Snake Case 自动映射
        // Result result = null;
        // try {
        // result = mapper.readValue(resultString, Result.class);
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        //
        // if (result == null) {
        // throw new ServiceException("未接收到医保返回参数");
        // } else if (result.getCode() == 200) {
        // System.out.println(JSON.toJSONString(result.getResult()));
        // fileResult = JSON.parseObject(JSON.toJSONString(result.getResult()), FileResult.class);
        // } else {
        // throw new ServiceException(result.getMessage());
        // }
        // return fileResult;
        // }catch (Exception e){
        // e.printStackTrace();
        // }
        // return fileResult;
    }

    /**
     * 【3101】明细审核事前事中分析服务
     *
     * @param data 规则分析信息
     * @return 违规信息
     */
    public Yb3101OutputResult yb3101PreMidAnalysis(Yb3101InputData data) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/pre-mid-analysis", data, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【3101】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【3101】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
            return parseObject(JSON.toJSONString(result.getResult()), Yb3101OutputResult.class);
        } else {
            throw new ServiceException(result.getMessage());
        }
    }

    /**
     * 【3103】事前事中服务反馈服务
     *
     * @param data 输入
     */
    public void yb3103PreMidFeedback(Yb3103InputData data) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/pre-mid-feedback", data, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【3103】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【3103】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            System.out.println(JSON.toJSONString(result.getResult()));
        } else {
            throw new ServiceException(result.getMessage());
        }
    }

    public List<Yb2301OutputResult> upload2301FeeDetail(Yb2301InputFeeDetailModel yb2301InputFeeDetailModel) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/upload-2301-fee-detail",
                yb2301InputFeeDetailModel, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2301】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2301】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (result == null) {
            throw new ServiceException("未接收到医保返回参数");
        } else if (result.getCode() == 200) {
            List<Yb2301OutputResult> yb2301OutputResults = new ArrayList<>();
            JSONObject jsonObject = parseObject(String.valueOf(result.getResult()));
            System.out.println(JSON.toJSONString(result.getResult()));
            JSONArray jsonArray = jsonObject.getJSONArray("result");
            for (Object o : jsonArray) {
                yb2301OutputResults.add(JSON.parseObject(String.valueOf(o), Yb2301OutputResult.class));
            }
            return yb2301OutputResults;
        } else {
            throw new ServiceException(result.getMessage());
        }
    }

    public Yb2303OutputSetInfo inpatientPreSettle(Yb2303InputInpatient yb2303InputInpatient) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/inpa-pre-setl",
                yb2303InputInpatient, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2303】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2303】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                return mapper.readValue(String.valueOf(result.getResult()), Yb2303OutputSetInfo.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public Yb2304OutputSetlInfo inpatientSettle(Contract contract, Yb2304InputInpatient yb2304InpatientParam) {
        String resultString = httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/inpa-setl",
            yb2304InpatientParam, contract);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2304】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2304】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                return mapper.readValue(String.valueOf(result.getResult()), Yb2304OutputSetlInfo.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 【取消住院结算】
     * 
     * @param contract 合同
     * @param yb2305InpatientParam 2305参数
     * @return 医保结果
     */
    public Yb2305OutputSetlInfo inpatientUnSettle(Contract contract, Yb2305InputInpatient yb2305InpatientParam) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/inpa-un-setl",
                yb2305InpatientParam, contract);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2305】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2305】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                return mapper.readValue(String.valueOf(result.getResult()), Yb2305OutputSetlInfo.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 【5205】人员慢特病用药记录查询
     * 
     * @param yb5205InputSpecialDisease
     * @return
     */
    public List<Yb5205OutputSpecialDisease>
        yb5205SpecialDiseaseDrugRecordSearch(Yb5205InputSpecialDisease yb5205InputSpecialDisease) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/spe-disease-record-search",
                yb5205InputSpecialDisease, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【5205】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【5205】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return JSON.parseArray(result.getResult().toString(), Yb5205OutputSpecialDisease.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 【目录下载】
     *
     * @param catalogFileInput
     * @return
     */
    public FileResult queryCatalog(CatalogFileInput catalogFileInput) {
        String resultString = httpPost(
            SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/query-catalog", catalogFileInput, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【" + catalogFileInput.getAddress() + "】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【" + catalogFileInput.getAddress() + "】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return JSON.parseObject(JSON.toJSONString(result.getResult()), FileResult.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 【文件下载】
     *
     * @param fileResult
     * @return
     */
    public FileResult downLoadFile(FileResult fileResult) {
        String resultString =
            httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/download", fileResult, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【9102】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【9102】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return JSON.parseObject(JSON.toJSONString(result.getResult()), FileResult.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 【2401】住院办理
     *
     * @param yb2401InputInpatientMdtrtInfo 入參
     * @return 結果
     */
    public InpatientReg inpatientReg(Yb2401InputInpatientMdtrtInfo yb2401InputInpatientMdtrtInfo) {
        String resultString =
                httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/inpatient-reg",
                        yb2401InputInpatientMdtrtInfo, contractServiceImpl.getContract(yb2401InputInpatientMdtrtInfo.getMdtrtareaAdmvs()));
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2401】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2401】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return JSON.parseObject(result.getResult().toString(), InpatientReg.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public InpatientDischarge inpatientCheckOut(Contract contract,Yb2402InputParam yb2402InputInpatientDscgInfo) {
        String resultString =
                httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/discharge-patient",
                        yb2402InputInpatientDscgInfo, contract);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2402】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2402】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return JSON.parseObject(result.getResult().toString(), InpatientDischarge.class);
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public void updateInpatientInfo(Yb2403InputParam yb2405InputInpatient) {
        String resultString =
                httpPost(SecurityUtils.getLoginUser().getOptionJson().getString("ybUrl") + "/change-inpatient-info",
                        yb2405InputInpatient, null);
        if (StringUtils.isEmpty(resultString)) {
            throw new ServiceException("未接收到医保返回参数");
        }
        System.out.println("【2405】返回参数:" + JSON.toJSONString(resultString));
        logger.info("【2405】返回参数:" + resultString);
        ObjectMapper mapper = new ObjectMapper();
        Result result = null;
        try {
            result = mapper.readValue(resultString, Result.class);
            if (result == null) {
                throw new ServiceException("未接收到医保返回参数");
            } else if (result.getCode() == 200) {
                System.out.println(result.getResult().toString());
                return;
            } else {
                throw new ServiceException(result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
