package com.yihu.wlyy.service.third.jw;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientReservation;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientReservationDao;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.service.third.ehr.EhrService;
import com.yihu.wlyy.service.third.guahao.GuahaoDoctor;
import com.yihu.wlyy.service.third.guahao.IGuahaoService;
import com.yihu.wlyy.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionContext;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by hzp on 2016/11/14.
 * 基卫健康市民健康服务
 */
@Service
public class JwSmjkService {

    //基卫服务地址
    private String jwUrl = SystemConf.getInstance().getJwUrl();

    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    EhrService ehrService;

    @Autowired
    SystemDictService systemDictService;


    /****************************************************************************************************************************/
    /**
     * 获取门/急诊记录 + 住院记录
     */
    public String getResidentEventListJson(String strSSID,String type,String page,String pageSize)
    {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return "";
        }
        else {
            String re = "";
            try {
                String url = jwUrl + "/third/smjk/ResidentEventList";

                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("strSSID", strSSID));
                if (!StringUtils.isEmpty(type)) {
                    params.add(new BasicNameValuePair("type", type));
                }
                params.add(new BasicNameValuePair("page", page));
                params.add(new BasicNameValuePair("pageSize", pageSize));

                String response = HttpClientUtil.post(url, params, "UTF-8");

                if (!StringUtils.isEmpty(response)) {
                    JSONObject responseObject = new JSONObject(response);
                    int status = responseObject.getInt("status");
                    if (status == 200) {
                        String data = responseObject.getString("data");
                        if (!StringUtils.isEmpty(data) && data.startsWith("error")) {
                            throw new Exception(data);
                        } else {
                            JSONObject jsonData = new JSONObject(data);
                            JSONArray jsonArray = jsonData.getJSONArray("EventList");
                            re = jsonArray.toString();
                        }
                    } else {
                        throw new Exception(responseObject.getString("msg"));
                    }
                } else {
                    throw new Exception("null response.");
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if(re.equals("[{}]"))
            {
                re = "";
            }

            return re;
        }
    }

    /**
     * 通过event获取档案类型列表
     */
    public String getEventCatalog(String strSSID,String strEvent)
    {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return "";
        }
        else {
            try {
                String url = jwUrl + "/third/smjk/EventCatalog";

                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("strSSID", strSSID));
                params.add(new BasicNameValuePair("strEvent", strEvent));

                String response = HttpClientUtil.post(url, params, "UTF-8");
                String result = "";
                if (!StringUtils.isEmpty(response)) {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if (status == 200) {
                        result = jsonObject.getString("data");
                    }
                    else {
                        throw new Exception(jsonObject.getString("msg"));
                    }
                }
                else {
                    throw new Exception("null response.");
                }

                return result;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return "";
            }
        }
    }

    /**
     * 获取健康档案信息详情
     */
    public String getHealthData(String strSSID, String strEvent, String strCatalog, String strSerial) {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getHealthData(strSSID,strEvent,strCatalog,strSerial);
        }
        else {
            try {
                String url = jwUrl + "/third/smjk/HealthData";

                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("strSSID", strSSID));
                params.add(new BasicNameValuePair("strEvent", strEvent));
                params.add(new BasicNameValuePair("strCatalog", strCatalog));
                params.add(new BasicNameValuePair("strSerial", strSerial));

                String response = HttpClientUtil.post(url, params, "UTF-8");
                String result = "";
                if (!StringUtils.isEmpty(response)) {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if (status == 200) {
                        result = jsonObject.getString("data");
                        result = result.replaceAll("<\\?xml version=\"1.0\" encoding=\"utf-8\"\\?>", "");
                        if (result.startsWith("error")) {
                            throw new Exception(result);
                        }
                    }
                    else {
                        throw new Exception(jsonObject.getString("msg"));
                    }
                }
                else {
                    throw new Exception("null response.");
                }

                return result;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return "";
            }
        }
    }


    /**
     * 获取检查检验列表
     */
    public String getExamAndLabReport(String strSSID,String page,String pageSize)
    {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return "";
        }
        else {
            try {
                String url = jwUrl + "/third/smjk/ExamAndLabReport";

                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("strSSID", strSSID));
                params.add(new BasicNameValuePair("page", page));
                params.add(new BasicNameValuePair("pageSize", pageSize));

                String response = HttpClientUtil.post(url, params, "UTF-8");
                String re = "";
                if (!StringUtils.isEmpty(response)) {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if (status == 200) {
                        String data = jsonObject.getString("data");
                        if (!StringUtils.isEmpty(data) && data.startsWith("error")) {
                            throw new Exception(data);
                        } else {
                            JSONObject jsonData = new JSONObject(data);
                            JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                            re = jsonArray.toString();
                        }
                    } else {
                        throw new Exception(jsonObject.getString("msg"));
                    }
                } else {
                    throw new Exception("null response.");
                }

                if(re.equals("[{}]"))
                {
                    re = "";
                }

                return re;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return "";
            }
        }
    }

    /**
     * 获取用药列表
     */
    public String getDrugsListPage(String strSSID,String page,String pageSize) throws Exception
    {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return "";
        }
        else {
            String url = jwUrl + "/third/smjk/DrugsListPage";

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            params.add(new BasicNameValuePair("page", page));
            params.add(new BasicNameValuePair("pageSize", pageSize));

            String response = HttpClientUtil.post(url, params, "UTF-8");
            String result = "";
            if (!StringUtils.isEmpty(response)) {
                JSONObject jsonObject = new JSONObject(response);
                int status = jsonObject.getInt("status");
                if (status == 200) {
                    result = jsonObject.getString("data");
                }
                else {
                    throw new Exception(jsonObject.getString("msg"));
                }
            }
            else {
                throw new Exception("null response.");
            }

            if(result.equals("[{}]"))
            {
                result = "";
            }
            return result;

        }
    }


    /****************************************************************************************************************************/
    /**
     * （内网）获取转诊预约医生号源信息
     */
    public String getRegDeptSpeDoctorSectionList(String OrgCode,String DeptCode,String strStart,String strEnd,String DocCode)  throws Exception
    {
        String re = "";
        String url = jwUrl + "/third/smjk/RegDeptSpeDoctorSectionList";

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("OrgCode", OrgCode));
        params.add(new BasicNameValuePair("DeptCode", DeptCode));
        params.add(new BasicNameValuePair("strStart", strStart));
        params.add(new BasicNameValuePair("strEnd", strEnd));
        params.add(new BasicNameValuePair("DocCode", DocCode));

        String response =  HttpClientUtil.post(url, params, "UTF-8");

        if (!StringUtils.isEmpty(response)) {
            JSONObject jsonObject = new JSONObject(response);
            int status = jsonObject.getInt("status");
            if (status == 200) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data) && (data.startsWith("error")||data.startsWith("System-Error"))) {
                    throw new Exception(data);
                } else {
                    re = data;
                }
            } else {
                throw new Exception(jsonObject.getString("msg"));
            }
        } else {
            throw new Exception("null response.");
        }

        return re;
    }

    /**
     * （内网）预约挂号接口
     */
    public String webRegisterByFamily(String idcard,String patientName,String ssid,String sectionType,String startTime,String orgCode,String deptCode,String deptName,String doctorCode,String doctorName)  throws Exception
    {
        String re = "";
        String url = jwUrl + "/third/smjk/WebRegisterByFamily";

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("idcard", idcard));
        params.add(new BasicNameValuePair("patientName", patientName));
        params.add(new BasicNameValuePair("ssid", ssid));
        params.add(new BasicNameValuePair("sectionType", sectionType));
        params.add(new BasicNameValuePair("startTime", startTime));
        params.add(new BasicNameValuePair("orgCode", orgCode));
        params.add(new BasicNameValuePair("deptCode", deptCode));
        params.add(new BasicNameValuePair("deptName", deptName));
        params.add(new BasicNameValuePair("doctorCode", doctorCode));
        params.add(new BasicNameValuePair("doctorName", doctorName));

        String response = HttpClientUtil.post(url, params, "UTF-8");

        if (!StringUtils.isEmpty(response)) {
            JSONObject jsonObject = new JSONObject(response);
            int status = jsonObject.getInt("status");
            if (status == 200) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data) && (data.startsWith("error")||data.startsWith("System-Error"))) {
                    throw new Exception(data);
                } else {
                    re = data;
                }
            } else {
                throw new Exception(jsonObject.getString("msg"));
            }
        } else {
            throw new Exception("null response.");
        }

        //返回挂号单
        return re;
    }












    /*************************************** 旧版本函数 *************************************************************************/
    /**
     * 获取住院记录(X)
     */
    public String getHospitalizationRecord(String strSSID, String startNum, String endNum) throws Exception {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getHospitalizationRecord(strSSID);
        }
        else {
            String startDate = "1900-01-01";
            String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
            String url = jwUrl + "/third/smjk/InpatientRecord";

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            params.add(new BasicNameValuePair("startDate", startDate));
            params.add(new BasicNameValuePair("endDate", endDate));
            params.add(new BasicNameValuePair("startNum", startNum));
            params.add(new BasicNameValuePair("endNum", endNum));

            String response = HttpClientUtil.post(url, params, "UTF-8");
            JSONArray resultArray = new JSONArray();
            List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
            Map<String, String> systemDictMap = new HashMap<>();
            for (SystemDict systemDict : systemDictList) {
                systemDictMap.put(systemDict.getCode(), systemDict.getValue());
            }

            if (!StringUtils.isEmpty(response)) {
                JSONObject responseObject = new JSONObject(response);
                int status = responseObject.getInt("status");
                if (status == 200) {
                    String data = responseObject.getString("data");
                    if (!StringUtils.isEmpty(data)) {
                        if (data.startsWith("error")) {
                            return data;
                        }
                        JSONObject jsonData = new JSONObject(data);
                        JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                        if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                            Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String patientId = jsonObject.getString("XMAN_ID");
                                String eventNo = jsonObject.getString("EVENT");
                                Integer orgId = jsonObject.getInt("ORG_ID");
                                String key = patientId + eventNo + orgId;
                                JSONObject catalogObject = new JSONObject();
                                String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                                String endTimeNew = jsonObject.get("END_TIME").toString();
                                String catalogValue = systemDictMap.get(catalogCode);
                                jsonObject.remove("CATALOG_CODE");
                                if (jsonObjectMap.containsKey(key)) {
                                    jsonObject = jsonObjectMap.get(key);
                                    String endTimeOld = jsonObject.get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) < 0) {
                                        endTimeNew = endTimeOld;
                                    }
                                    catalogObject = jsonObject.getJSONObject("CATALOG");
                                }
                                catalogObject.put(catalogCode, catalogValue);
                                jsonObject.put("CATALOG", catalogObject);
                                jsonObject.put("END_TIME", endTimeNew);
                                jsonObjectMap.put(key, jsonObject);
                            }

                            for (String key : jsonObjectMap.keySet()) {
                                resultArray.put(jsonObjectMap.get(key));
                            }

                            JSONObject temp;
                            for (int i = 0; i < resultArray.length(); i++) {
                                for (int j = i + 1; j < resultArray.length(); j++) {
                                    String endTimeNew = resultArray.getJSONObject(j).get("END_TIME").toString();
                                    String endTimeOld = resultArray.getJSONObject(i).get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) > 0) {
                                        temp = resultArray.getJSONObject(i);
                                        resultArray.put(i, resultArray.getJSONObject(j));
                                        resultArray.put(j, temp);  // 两个数交换位置
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return resultArray.toString();
        }
    }

    /**
     * 获取门/急诊记录(X)
     */
    public String getOutpatientRecord(String strSSID, String startNum, String endNum) throws Exception {

        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getOutpatientRecord(strSSID);
        }
        else{
            String startDate = "1900-01-01";
            String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
            String url = jwUrl + "/third/smjk/OutpatientRecord";

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            params.add(new BasicNameValuePair("startDate", startDate));
            params.add(new BasicNameValuePair("endDate", endDate));
            params.add(new BasicNameValuePair("startNum", startNum));
            params.add(new BasicNameValuePair("endNum", endNum));

            String response = HttpClientUtil.post(url, params, "UTF-8");
            JSONArray resultArray = new JSONArray();
            List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
            Map<String, String> systemDictMap = new HashMap<>();
            for (SystemDict systemDict : systemDictList) {
                systemDictMap.put(systemDict.getCode(), systemDict.getValue());
            }

            if (!StringUtils.isEmpty(response)){
                JSONObject responseObject = new JSONObject(response);
                int status = responseObject.getInt("status");
                if (status == 200){
                    String data = responseObject.getString("data");
                    if (!StringUtils.isEmpty(data)){
                        if (data.startsWith("error")) {
                            return data;
                        }
                        JSONObject jsonData = new JSONObject(data);
                        JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                        if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                            Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                            for (int i=0; i<jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String patientId = jsonObject.getString("XMAN_ID");
                                String eventNo = jsonObject.getString("EVENT");
                                Integer orgId = jsonObject.getInt("ORG_ID");
                                String key = patientId + eventNo + orgId;
                                JSONObject catalogObject = new JSONObject();
                                String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                                String endTimeNew = jsonObject.get("END_TIME").toString();
                                String catalogValue = systemDictMap.get(catalogCode);
                                jsonObject.remove("CATALOG_CODE");
                                if (jsonObjectMap.containsKey(key)) {
                                    jsonObject = jsonObjectMap.get(key);
                                    String endTimeOld = jsonObject.get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) < 0) {
                                        endTimeNew = endTimeOld;
                                    }
                                    catalogObject = jsonObject.getJSONObject("CATALOG");
                                }
                                catalogObject.put(catalogCode, catalogValue);
                                jsonObject.put("CATALOG", catalogObject);
                                jsonObject.put("END_TIME", endTimeNew);
                                jsonObjectMap.put(key, jsonObject);
                            }

                            for (String key : jsonObjectMap.keySet()) {
                                resultArray.put(jsonObjectMap.get(key));
                            }

                            JSONObject temp;
                            for (int i = 0; i < resultArray.length(); i++) {
                                for (int j = i+1; j < resultArray.length(); j++) {
                                    String endTimeNew = resultArray.getJSONObject(j).get("END_TIME").toString();
                                    String endTimeOld = resultArray.getJSONObject(i).get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) > 0) {
                                        temp = resultArray.getJSONObject(i);
                                        resultArray.put(i, resultArray.getJSONObject(j));
                                        resultArray.put(j, temp);  // 两个数交换位置
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return resultArray.toString();
        }
    }

    /**
     * 获取检查报告信息 （X）
     */
    private JSONArray getChecking(String strSSID, String startNum, String endNum) throws Exception {
        String api = "/third/smjk/ExamReport";
        return getResult(api, strSSID, startNum, endNum);
    }

    /**
     * 获取检验报告信息（X）
     */
    private JSONArray getInspection(String strSSID, String startNum, String endNum) throws Exception {
        String api = "/third/smjk/LabReport";
        return getResult(api, strSSID, startNum, endNum);
    }

    private JSONArray getResult(String api, String strSSID, String startNum, String endNum) {
        String startDate = "1900-01-01";
        String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
        String url = jwUrl + api;

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSSID", strSSID));
        params.add(new BasicNameValuePair("startDate", startDate));
        params.add(new BasicNameValuePair("endDate", endDate));
        params.add(new BasicNameValuePair("startNum", startNum));
        params.add(new BasicNameValuePair("endNum", endNum));

        String response = HttpClientUtil.post(url, params, "UTF-8");
        JSONArray resultArray = new JSONArray();
        List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
        Map<String, String> systemDictMap = new HashMap<>();
        for (SystemDict systemDict : systemDictList) {
            systemDictMap.put(systemDict.getCode(), systemDict.getValue());
        }

        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200){
                String data = responseObject.getString("data");
                if (!StringUtils.isEmpty(data)){
                    if (data.startsWith("error")) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("error", data);
                        resultArray.put(jsonObject);
                        return resultArray ;
                    }
                    JSONObject jsonData = new JSONObject(data);
                    JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                    if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                        for (int i=0; i<jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String patientId = jsonObject.getString("XMAN_ID");
                            String eventNo = jsonObject.getString("EVENT");
                            Integer orgId = jsonObject.getInt("ORG_ID");
                            String key = patientId + eventNo + orgId;
                            JSONObject catalogObject = new JSONObject();
                            String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                            String endTimeNew = jsonObject.get("END_TIME").toString();
                            String catalogValue = systemDictMap.get(catalogCode);
                            jsonObject.remove("CATALOG_CODE");
                            if (jsonObjectMap.containsKey(key)) {
                                jsonObject = jsonObjectMap.get(key);
                                String endTimeOld = jsonObject.get("END_TIME").toString();
                                if (endTimeNew.compareTo(endTimeOld) < 0) {
                                    endTimeNew = endTimeOld;
                                }
                                catalogObject = jsonObject.getJSONObject("CATALOG");
                            }
                            catalogObject.put(catalogCode, catalogValue);
                            jsonObject.put("CATALOG", catalogObject);
                            jsonObject.put("END_TIME", endTimeNew);
                            jsonObjectMap.put(key, jsonObject);
                        }

                        for (String key : jsonObjectMap.keySet()) {
                            resultArray.put(jsonObjectMap.get(key));
                        }
                    }
                }
            }
        }
        return resultArray;
    }

    /**
     * 获取检查检验 信息（X）
     * @param strSSID
     * @param startNum
     * @param endNum
     * @return
     * @throws Exception
     */
    public String getInspectionAndChecking(String strSSID, String startNum, String endNum) throws Exception {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getInspectionAndChecking(strSSID);
        }
        else {
            JSONArray total = new JSONArray();
            JSONArray check = getChecking(strSSID, startNum, endNum);
            if (!check.isNull(0)) {
                JSONObject jsonObject = check.getJSONObject(0);
                if (jsonObject.has("error")) {
                    return jsonObject.get("error").toString();
                }
            }
            JSONArray inspect = getInspection(strSSID, startNum, endNum);
            if (!inspect.isNull(0)) {
                JSONObject jsonObject = inspect.getJSONObject(0);
                if (jsonObject.has("error")) {
                    return jsonObject.get("error").toString();
                }
            }
            //TODO 检查检验数据合并
            for (int i = 0; i < check.length(); i++) {
                total.put(check.getJSONObject(i));
            }
            for (int i = 0; i < inspect.length(); i++) {
                total.put(inspect.getJSONObject(i));
            }
            JSONObject temp;
            for (int i = 0; i < total.length(); i++) {
                for (int j = i + 1; j < total.length(); j++) {
                    String endTimeNew = total.getJSONObject(j).get("END_TIME").toString();
                    String endTimeOld = total.getJSONObject(i).get("END_TIME").toString();
                    if (endTimeNew.compareTo(endTimeOld) > 0) {
                        temp = total.getJSONObject(i);
                        total.put(i, total.getJSONObject(j));
                        total.put(j, temp);  // 两个数交换位置
                    }
                }
            }
            return total.toString();
        }
    }

    /**
     * 获取用药记录（X）
     */
    public String getDrugsList(String strSSID, String startNum,String endNum) throws Exception {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getDrugsList(strSSID);
        }
        else {
            String startDate = "1900-01-01";
            String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
            String url = jwUrl + "/third/smjk/DrugsList";

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            params.add(new BasicNameValuePair("startDate", startDate));
            params.add(new BasicNameValuePair("endDate", endDate));
            params.add(new BasicNameValuePair("startNum", startNum));
            params.add(new BasicNameValuePair("endNum", endNum));

            String response = HttpClientUtil.post(url, params, "UTF-8");
            JSONArray resultArray = new JSONArray();
            List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
            Map<String, String> systemDictMap = new HashMap<>();
            for (SystemDict systemDict : systemDictList) {
                systemDictMap.put(systemDict.getCode(), systemDict.getValue());
            }

            if (!StringUtils.isEmpty(response)) {
                JSONObject responseObject = new JSONObject(response);
                int status = responseObject.getInt("status");
                if (status == 200) {
                    String data = responseObject.getString("data");
                    if (!StringUtils.isEmpty(data)) {
                        if (data.startsWith("error")) {
                            return data;
                        }
                        JSONObject jsonData = new JSONObject(data);
                        JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                        if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                            Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String patientId = jsonObject.getString("XMAN_ID");
                                String eventNo = jsonObject.getString("EVENT");
                                Integer orgId = jsonObject.getInt("ORG_ID");
                                String key = patientId + eventNo + orgId;
                                JSONObject catalogObject = new JSONObject();
                                String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                                String endTimeNew = jsonObject.get("END_TIME").toString();
                                String catalogValue = systemDictMap.get(catalogCode);
                                jsonObject.remove("CATALOG_CODE");
                                if (jsonObjectMap.containsKey(key)) {
                                    jsonObject = jsonObjectMap.get(key);
                                    String endTimeOld = jsonObject.get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) < 0) {
                                        endTimeNew = endTimeOld;
                                    }
                                    catalogObject = jsonObject.getJSONObject("CATALOG");
                                }
                                catalogObject.put(catalogCode, catalogValue);
                                jsonObject.put("CATALOG", catalogObject);
                                jsonObject.put("END_TIME", endTimeNew);
                                jsonObjectMap.put(key, jsonObject);
                            }

                            for (String key : jsonObjectMap.keySet()) {
                                resultArray.put(jsonObjectMap.get(key));
                            }

                            JSONObject temp;
                            for (int i = 0; i < resultArray.length(); i++) {
                                for (int j = i + 1; j < resultArray.length(); j++) {
                                    String endTimeNew = resultArray.getJSONObject(j).get("END_TIME").toString();
                                    String endTimeOld = resultArray.getJSONObject(i).get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) > 0) {
                                        temp = resultArray.getJSONObject(i);
                                        resultArray.put(i, resultArray.getJSONObject(j));
                                        resultArray.put(j, temp);  // 两个数交换位置
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return resultArray.toString();
        }
    }
}
