package thyyxxk.webserver.service.medicalinsurance;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtflys.forest.http.ForestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.MedinsurConfig;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.constants.sidicts.SiFunction;
import thyyxxk.webserver.dao.his.medicalinsurance.SiDownloadDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.medicalinsurance.download.DldDictList;
import thyyxxk.webserver.entity.medicalinsurance.download.*;
import thyyxxk.webserver.service.externalhttp.SiExecSrvc;
import thyyxxk.webserver.utils.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @description: 医保目录下载服务
 * @author: DingJie
 * @create: 2021-06-23 15:17:03
 **/
@Service
@Slf4j
public class SiDownloadService {
    private static final String RESULT_CODE = "infcode";
    private static final String ERROR_MESSAGE = "err_msg";
    private static final String OUTPUT = "output";
    private static final String BEGIN_VERSION = "000000";
    private final ExecService exec;
    private final SiDownloadDao dnlddao;
    private final SiExecSrvc execSrvc;
    private final MedinsurConfig cfg;

    @Autowired
    public SiDownloadService(ExecService exec, SiDownloadDao dnlddao, SiExecSrvc execSrvc, MedinsurConfig cfg) {
        this.exec = exec;
        this.dnlddao = dnlddao;
        this.execSrvc = execSrvc;
        this.cfg = cfg;
    }

    public ResultVo<Map<String, Object>> executeDownload(DwnldPrm prm) {
        String v = StringUtil.nullIf(prm.getVersion(), BEGIN_VERSION);
        switch (prm.getCode()) {
            case "1301":
                return downloadPatentAndWesternMedicineCatalogue(v);
            case "1302":
                return downloadChineseHerbalCatalogue(v);
            case "1303":
                return downloadHospitalDosage(v);
            case "1304":
                return downloadEthnicMedicine(prm);
            case "1305":
                return downloadMedicalServiceItemsCatalogue(v);
            case "1306":
                return downloadMedicalSuppliesCatalogue(v);
            case "1307":
                return downloadDiseasesAndDiagnosisCatalogue(v);
            case "1308":
                return downloadOperationCatalogue(v);
            case "1309":
                return downloadOutpatientSpecialChronicDiseasesCatalogue(v);
            case "1310":
                return downloadPayByDiseaseCatalogue(v);
            case "1311":
                return downloadDaytimeSurgeryDiseasesCatalogue(v);
            case "1312":
                return downloadMedicalInsuranceCatalogue(prm);
            case "1313":
                return downloadTumorMorphologyCatalogue(v);
            case "1314":
                return downloadTraditionalChineseDiseasesCatalogue(v);
            case "1315":
                return downloadTcmSyndromeCatalogue(v);
            case "1316":
                return downloadMedicalInsuranceMatchCatalogue(prm);
            case "1317":
                return downloadMedicalInstitutionMatchCatalogue(prm);
            case "1318":
                return downloadMedicalInsurancePriceLimitCatalogue(prm);
            case "1319":
                return downloadMedicalInsurancePayFirstCatalogue(prm);
            case "1319_save":
                return saveMedicalInsurancePayFirstCatalogue(prm);
            case "1901":
                return downloadDictionaryList(prm);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到此目录下载的功能号。");
    }

    public ResultVo<Map<String, Object>> queryFromHis(DwnldPrm prm) {
        Map<String, Object> map = new HashMap<>(Capacity.TWO);
        IPage iPage;
        switch (prm.getCode()) {
            case "1301":
                iPage = new Page<SiDlPtntWstnMdcn>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlPtntWstnMdcnPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1302":
                iPage = new Page<SiDlChnsHbl>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlChnsHblPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1303":
                iPage = new Page<SiDlInstPrptn>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlInstPrptnPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1305":
                iPage = new Page<SiDlMdcnSrvc>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlMdcnSrvcPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1306":
                iPage = new Page<SiDlMdcnSply>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlMdcnSplyPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1307":
                iPage = new Page<SiDlDssDns>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlDssDnsPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1308":
                iPage = new Page<SiDlOprtn>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlOprtnPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1309":
                iPage = new Page<SiDlSlwSpcChr>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlSlwSpcChrPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1310":
                iPage = new Page<SiDlPayByDss>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlPayByDssPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1311":
                iPage = new Page<SiDlDytmSrgyDss>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlDytmSrgyDssPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1313":
                iPage = new Page<SiDlTmrMrphlgy>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlTmrMrphlgyPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1314":
                iPage = new Page<SiDlTrdtnlChnsDss>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlTrdtnlChnsDssPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
            case "1315":
                iPage = new Page<SiDlTcmSyndr>(prm.getPageNum(), prm.getPageSize());
                iPage = dnlddao.selectSiDlTcmSyndrPage(iPage);
                map.put("totalSize", iPage.getTotal());
                map.put("list", iPage.getRecords());
                return ResultVoUtil.success(map);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到此目录下载的功能号。");
    }

    public ResultVo<Map<String, Object>> downloadPatentAndWesternMedicineCatalogue(String v) {
        ResultVo<String> dwnldrslt = dwnldPtntWstnMdcnCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = dwnldPtntWstnMdcnCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> dwnldPtntWstnMdcnCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_PATENT_AND_WESTERN_MEDICINE_CATALOGUE, version);
        log.info("【操作员：{}】，西药中成药目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncatePtntWstnMdcnTable();
            }
            List<SiDlPtntWstnMdcn> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlPtntWstnMdcn(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deletePtntWstnMdcnTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertPtntWstnMdcnBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertPtntWstnMdcnBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadChineseHerbalCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldChnsHrblCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldChnsHrblCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<Map<String, Object>> downloadHospitalDosage(String v) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_INSTITUTIONS_PREPARATIONS_CATALOGUE, v);
        log.info("【操作员：{}】，医院制剂目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), v, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Map<String, Object> obj = new HashMap<>();
            obj.put("message", "下载成功");
            obj.put("path", filePath);
            return ResultVoUtil.success(obj);
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<String> execDwnldChnsHrblCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_CHINESE_HERBAL_CATALOGUE, version);
        log.info("中药饮片目录下载：版本号：{}，结果：{}", version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                log.info("初始版本号 {}，删除全表。", version);
                dnlddao.truncateChnsHblTable();
            }
            String versionName = null;
            List<SiDlChnsHbl> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlChnsHbl(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteChnsHblTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    try {
                        dnlddao.insertChnsHblBatch(list);
                        list.clear();
                    } catch (Exception e) {
                        log.info("{}", JSONArray.toJSON(list));
                        throw e;
                    }
                }
            }
            if (!list.isEmpty()) {
                try {
                    dnlddao.insertChnsHblBatch(list);
                } catch (Exception e) {
                    log.info("{}", JSONArray.toJSON(list));
                    throw e;
                }
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadEthnicMedicine(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_ETHNIC_MEDICINE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_ETHNIC_MEDICINE);
        return getMapResultVo(result);
    }

    public ResultVo<Map<String, Object>> downloadMedicalServiceItemsCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldMdclSrvcItmsCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldMdclSrvcItmsCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldMdclSrvcItmsCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_MEDICAL_SERVICE_ITEMS_CATALOGUE, version);
        log.info("【操作员：{}】，医疗服务项目目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateMdcnSrvcTable();
            }
            List<SiDlMdcnSrvc> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlMdcnSrvc(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteMdcnSrvcTableByVersionId(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertMdcnSrvcBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertMdcnSrvcBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadMedicalSuppliesCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldMdclSpplsCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldMdclSpplsCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldMdclSpplsCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_MEDICAL_SUPPLIES_CATALOGUE, version);
        log.info("【操作员：{}】，医用耗材目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateMdcnSplyTable();
            }
            List<SiDlMdcnSply> list = new ArrayList<>();
            String versionName = null;
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlMdcnSply(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteMdcnSplyTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertMdcnSplyBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertMdcnSplyBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadDiseasesAndDiagnosisCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldDssDgnssCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldDssDgnssCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldDssDgnssCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_DISEASES_AND_DIAGNOSIS_CATALOGUE, version);
        log.info("【操作员：{}】，疾病与诊断目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateDssDnsTable();
            }
            List<SiDlDssDns> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlDssDns(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteDssDnsTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertDssDnsBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertDssDnsBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadOperationCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldOprtnCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldOprtnCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldOprtnCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_OPERATION_CATALOGUE, version);
        log.info("【操作员：{}】，手术操作目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateOprtnTable();
            }
            List<SiDlOprtn> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                String[] arr = tempstr.split("\t");
                if (StringUtil.isBlank(arr[10])) {
                    continue;
                }
                list.add(new SiDlOprtn(arr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteOprtnTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertOprtnBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertOprtnBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadOutpatientSpecialChronicDiseasesCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldOutptntSpclChrncDssCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldOutptntSpclChrncDssCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldOutptntSpclChrncDssCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_OUTPATIENT_SPECIAL_CHRONIC_DISEASES_CATALOGUE, version);
        log.info("【操作员：{}】，门诊慢特病种目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateSlwSpcChrTable();
            }
            List<SiDlSlwSpcChr> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlSlwSpcChr(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteSlwSpcChrTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertSlwSpcChrBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertSlwSpcChrBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadPayByDiseaseCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldPayByDssCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldPayByDssCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldPayByDssCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_PAY_BY_DISEASE_CATALOGUE, version);
        log.info("【操作员：{}】，按病种付费病种目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncatePayByDssTable();
            }
            List<SiDlPayByDss> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlPayByDss(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deletePayByDssTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertPayByDssBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertPayByDssBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadDaytimeSurgeryDiseasesCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldDytmSrgryDssCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldDytmSrgryDssCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldDytmSrgryDssCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_DAYTIME_SURGERY_DISEASES_CATALOGUE, version);
        log.info("【操作员：{}】，日间手术治疗病种目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateDytmSrgyDssTable();
            }
            List<SiDlDytmSrgyDss> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlDytmSrgyDss(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteDytmSrgyDssTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertDytmSrgyDssBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertDytmSrgyDssBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadMedicalInsuranceCatalogue(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_CATALOGUE);
        return getMapResultVo(result);
    }

    private ResultVo<Map<String, Object>> getMapResultVo(JSONObject result) {
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            Map<String, Object> map = new HashMap<>(Capacity.TWO);
            map.put("totalSize", output.getIntValue("recordCounts"));
            map.put("list", output.getJSONArray("data"));
            return ResultVoUtil.success(map);
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadTumorMorphologyCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldTmrMrphlgyCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldTmrMrphlgyCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldTmrMrphlgyCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_TUMOR_MORPHOLOGY_CATALOGUE, version);
        log.info("【操作员：{}】，肿瘤形态学目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateTmrMrphlgyTable();
            }
            List<SiDlTmrMrphlgy> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlTmrMrphlgy(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteTmrMrphlgyTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertTmrMrphlgyBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertTmrMrphlgyBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadTraditionalChineseDiseasesCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldTrdtnlChnDssCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldTrdtnlChnDssCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldTrdtnlChnDssCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_TRADITIONAL_CHINESE_DISEASES_CATALOGUE, version);
        log.info("【操作员：{}】，中医疾病目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateTrdtnlChnsDssTable();
            }
            List<SiDlTrdtnlChnsDss> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlTrdtnlChnsDss(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteTrdtnlChnsDssByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertTrdtnlChnsDssBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertTrdtnlChnsDssBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadTcmSyndromeCatalogue(String v) {
        ResultVo<String> dwnldrslt = execDwnldTcmSyndrmCtlg(v);
        while (Objects.equals(dwnldrslt.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            dwnldrslt = execDwnldTcmSyndrmCtlg(dwnldrslt.getData());
        }
        return ResultVoUtil.success();
    }

    public ResultVo<String> execDwnldTcmSyndrmCtlg(String version) {
        JSONObject result = getOrdinaryDownloadResult(SiFunction.DOWNLOAD_TCM_SYNDROME_CATALOGUE, version);
        log.info("【操作员：{}】，中医证候目录下载：版本号：{}，结果：{}", TokenUtil.getInstance().getTokenUserId(), version, result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        String versionName = null;
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            String filename = output.getString("filename");
            String filePath = downloadFile(fileQuryNo, filename);
            if (null == filePath) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "网络异常，下载失败！");
            }
            Queue<String> queue = SiUtil.readTxtFile(filePath);
            if (version.equals(BEGIN_VERSION)) {
                dnlddao.truncateTcmSyndrTable();
            }
            List<SiDlTcmSyndr> list = new ArrayList<>();
            while (!queue.isEmpty()) {
                String tempstr = queue.poll();
                list.add(new SiDlTcmSyndr(tempstr));
                if (null == versionName) {
                    versionName = list.get(0).getVersionName();
                    if (StringUtil.notBlank(versionName)) {
                        dnlddao.deleteTcmSyndrTableByVersion(versionName);
                    }
                }
                if (list.size() == 20) {
                    dnlddao.insertTcmSyndrBatch(list);
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                dnlddao.insertTcmSyndrBatch(list);
            }
            if (StringUtil.notBlank(versionName)) {
                return ResultVoUtil.success(versionName);
            }
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public ResultVo<Map<String, Object>> downloadMedicalInsuranceMatchCatalogue(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_MATCH_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_MATCH_CATALOGUE);
        return getMapResultVo(result);
    }

    public ResultVo<Map<String, Object>> downloadMedicalInstitutionMatchCatalogue(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSTITUTION_MATCH_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSTITUTION_MATCH_CATALOGUE);
        return getMapResultVo(result);
    }

    public ResultVo<Map<String, Object>> downloadMedicalInsurancePriceLimitCatalogue(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PRICE_LIMIT_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PRICE_LIMIT_CATALOGUE);
        return getMapResultVo(result);
    }

    public ResultVo<Map<String, Object>> downloadMedicalInsurancePayFirstCatalogue(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        JSONObject data = new JSONObject();
        if (StringUtil.notBlank(prm.getMedinsCode())) {
            data.put("hilist_code", prm.getMedinsCode());
        }
        if (StringUtil.notBlank(prm.getInsutype())) {
            data.put("selfpay_prop_psn_type", prm.getInsutype());
        }
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", prm.getPageNum());
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        return getMapResultVo(result);
    }

    public ResultVo<Map<String, Object>> saveMedicalInsurancePayFirstCatalogue(DwnldPrm prm) {
        int pageNum = prm.getPageNum();
        int recordPages = 0;
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("updt_time", DateUtil.formatDatetime(prm.getUpdtTime()));
        data.put("page_num", pageNum);
        data.put("page_size", prm.getPageSize());
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            recordPages = output.getInteger("pages");
            List<SelfPayFirstCatalogue> list = JSONArray.parseArray(output.getJSONArray("data").toJSONString(), SelfPayFirstCatalogue.class);
            List<SelfPayFirstCatalogue> tempList = new ArrayList<>();
            log.info("下载医保目录先自付比例信息并入库：第 {} 页，共 {} 页。", pageNum, recordPages);
            if (pageNum == 1) {
                dnlddao.truncateSelfPayCatalogue();
            }
            for (SelfPayFirstCatalogue item : list) {
                tempList.add(item);
                if (tempList.size() == 100) {
                    dnlddao.insertSelfPayCatalogue(tempList);
                    tempList.clear();
                }
            }
            if (!tempList.isEmpty()) {
                dnlddao.insertSelfPayCatalogue(tempList);
            }
        }
        while (pageNum < recordPages) {
            pageNum += 1;
            data.replace("page_num", pageNum);
            input.getJSONObject("input").replace("data", data);
            result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
            if (null == result) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
            }
            if (null == result.getInteger(RESULT_CODE)) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
            }
            if (result.getIntValue(RESULT_CODE) == 0) {
                JSONObject output = result.getJSONObject(OUTPUT);
                List<SelfPayFirstCatalogue> list = JSONArray.parseArray(output.getJSONArray("data").toJSONString(), SelfPayFirstCatalogue.class);
                List<SelfPayFirstCatalogue> tempList = new ArrayList<>();
                log.info("下载医保目录先自付比例信息并入库：第 {} 页，共 {} 页。", pageNum, recordPages);
                for (SelfPayFirstCatalogue item : list) {
                    tempList.add(item);
                    if (tempList.size() == 100) {
                        dnlddao.insertSelfPayCatalogue(tempList);
                        tempList.clear();
                    }
                }
                if (!tempList.isEmpty()) {
                    dnlddao.insertSelfPayCatalogue(tempList);
                }
            }
        }
        prm.setPageNum(1);
        prm.setPageSize(30);
        return downloadMedicalInsurancePayFirstCatalogue(prm);
    }

    public ResultVo<Map<String, Object>> downloadDictionaryList(DwnldPrm prm) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_DICTIONARY_LIST);
        DldDictList data = new DldDictList();
        data.setDate(DateUtil.formatDatetime(new Date(), "yyyy-MM-dd"));
        data.setAdmdvs(cfg.getHospArea());
        data.setParentValue(prm.getParentValue());
        data.setType(prm.getType());
        data.setValiFlag(prm.getValiFlag());
        input.getJSONObject("input").put("data", JSONObject.parseObject(JSONObject.toJSONString(data)));
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_DICTIONARY_LIST);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            JSONArray list = output.getJSONArray("list");
            Map<String, Object> map = new HashMap<>(Capacity.TWO);
            map.put("totalSize", list.size());
            map.put("list", list);
            return ResultVoUtil.success(map);
        }
        throw new BizException(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

    public String downloadFile(String fileQuryNo, String filename) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_FILE);
        JSONObject fsDownloadIn = new JSONObject();
        fsDownloadIn.put("file_qury_no", fileQuryNo);
        fsDownloadIn.put("filename", filename);
        fsDownloadIn.put("fixmedins_code", cfg.getHospId());
        input.getJSONObject("input").put("fsDownloadIn", fsDownloadIn);
        String targetPath = ZipUtil.DIRECTORY + filename;
        ForestResponse<byte[]> rsp = execSrvc.download(exec.getSiHeaderMap(SiFunction.DOWNLOAD_FILE), input);
        try {
            Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getByteArray(),
                    "未获取到下载文件"));
            String unZip = ZipUtil.unZip(targetPath);
            log.info("解压缩成功：{}", unZip);
            ZipUtil.deleteFile(targetPath);
            return unZip;
        } catch (Exception e) {
            log.error("从医保中心下载文件出错", e);
        }
        return null;
    }

    private JSONObject getOrdinaryDownloadResult(SiFunction function, String version) {
        JSONObject input = exec.makeTradeHeader(function);
        JSONObject data = new JSONObject();
        data.put("ver", version);
        input.getJSONObject("input").put("data", data);
        return exec.executeTrade(input, function);
    }

    public ResultVo<String> fillPsnPayProp() {
        int countYp = 0;
        List<String> ypList = dnlddao.selectHospitalItems("yp_zd_dict");
        for (String item : ypList) {
            countYp += queryPsnPayProp(item, "yp_zd_dict");
        }

        int countXm = 0;
        List<String> xmList = dnlddao.selectHospitalItems("zd_charge_item");
        for (String item : xmList) {
            countXm += queryPsnPayProp(item, "zd_charge_item");
        }
        String result = String.format("药品共 %d 项，补充 %d 项；项目共 %d 项，补充 %d 项。",
                                        ypList.size(), countYp, xmList.size(), countXm);
        log.info(result);
        return ResultVoUtil.success(result);
    }

    private int queryPsnPayProp(String hilistCode, String table) {
        JSONObject input = exec.makeTradeHeader(SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        JSONObject data = new JSONObject();
        data.put("hilist_code", hilistCode);
        data.put("selfpay_prop_psn_type", "310");
        data.put("updt_time", "2000-01-01 00:00:00");
        data.put("page_num", 1);
        data.put("page_size", 100);
        input.getJSONObject("input").put("data", data);
        JSONObject result = exec.executeTrade(input, SiFunction.DOWNLOAD_MEDICAL_INSURANCE_PAY_FIRST_CATALOGUE);
        if (null == result || null == result.getInteger(RESULT_CODE)) {
            return 0;
        }
        String psnPayProp = null;
        String nowdate = DateUtil.formatDatetime(new Date());
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            JSONArray array = output.getJSONArray("data");
            int recordCounts = output.getIntValue("recordCounts");
            if (recordCounts == 1) {
                JSONObject target = array.getJSONObject(0);
                psnPayProp = target.getString("selfpay_prop");
            } else {
                for (int i = 0; i < recordCounts; i++) {
                    JSONObject target = array.getJSONObject(i);
                    String enddate = target.getString("enddate");
                    if (DateUtil.shiJianDaXiao(nowdate, enddate, "<=")) {
                        nowdate = enddate;
                        psnPayProp = target.getString("selfpay_prop");
                    }
                }
            }
        }
        if (StringUtil.notBlank(psnPayProp)) {
            dnlddao.updatePsnpayProp(table, hilistCode, psnPayProp);
            log.info("补充自费比例：{}，{}", hilistCode, psnPayProp);
            return 1;
        }
        return 0;
    }

    public void importDown() throws IOException {
        File file = new File("D:\\his\\接口\\医保\\111.xlsx");
        List<List<String>> data = ExcelReaderUtil.readExcel(file);
        System.out.println("-------data-------");

        // 打印读取到的数据

        try {
            for (List<String> row : data) {
                List<SiDlMdcnSrvc> siDlMdcnSrvcList = new ArrayList<>();
                    if(StringUtil.isNotEmpty(row.get(2))) {
                        SiDlMdcnSrvc srvc = new SiDlMdcnSrvc();
                        srvc.setCode(row.get(2) + "-" + row.get(0));
                        srvc.setServiceName(row.get(3));
                        srvc.setChargeUnit(row.get(6));
                        srvc.setExcludeContent(row.get(5));
                        srvc.setConnotation(row.get(4));
                        siDlMdcnSrvcList.add(srvc);

//                        dnlddao.insertMdcnSrvc(srvc);

                        try {
                            dnlddao.insertMdcnSrvcBatch(siDlMdcnSrvcList);
                        } catch (Exception e) {
                            System.out.println(row);
                        }
                    }

            }

        } catch (Exception e) {
            //e.printStackTrace();

        }


    }

    public void updateDown() throws IOException {
        File file = new File("D:\\his\\接口\\医保\\111.xlsx");
        List<List<String>> data = ExcelReaderUtil.readExcel(file);
        System.out.println("-------data-------");

        // 打印读取到的数据

        try {
            for (List<String> row : data) {
                List<SiDlMdcnSrvc> siDlMdcnSrvcList = new ArrayList<>();
                if(StringUtil.isNotEmpty(row.get(2))) {
                    SiDlMdcnSrvc srvc = new SiDlMdcnSrvc();
                    srvc.setCode(row.get(2) + "-" + row.get(0));
                    srvc.setServiceName(row.get(3));
                    srvc.setChargeUnit(row.get(6));
                    srvc.setExcludeContent(row.get(5));
                    srvc.setConnotation(row.get(4));
                    siDlMdcnSrvcList.add(srvc);

//                        dnlddao.insertMdcnSrvc(srvc);

                    try {
                        dnlddao.insertMdcnSrvcBatch(siDlMdcnSrvcList);
                    } catch (Exception e) {
                        System.out.println(row);
                    }
                }

            }

        } catch (Exception e) {
            //e.printStackTrace();

        }


    }

}
