package com.yihu.wlyy.service.app.record;

import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.XMLUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/17.
 */
@Service
public class InspectionService extends BaseService {

    @Autowired
    SystemDictService systemDictService;

    @Autowired
    EhrService ehrService;

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

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

    /**
     * 获取检查检验 信息
     * @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();
        }
    }


    public 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 = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + 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;
    }

    /**
     * 档案详情
     * @param strSSID       健康卡号
     * @param strEvent      事件ID
     * @param strCatalog    档案类型
     * @param strSerial     该类别顺序号，默认填1
     * @return
     * @throws Exception
     */
    public JSONObject getHealthData(String strSSID, String strEvent, String strCatalog, String strSerial) throws Exception {
        JSONObject result = new JSONObject();
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/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 data="";
        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){
                data = jsonObject.getString("data");

            }
        }

        //TODO  示例数据，未转成前端需要
        String xml = "<ClinicalDocument><version date=\"2009-12-01\" code=\"2.0.0.0\">根据卫生部标准第一次修订</version><ehr codeSystem=\"STD_EHR\" code=\"0101\">门诊基本诊疗信息</ehr><title>门诊基本诊疗信息</title><org codeSystem=\"STD_HEALTH_ORG\" code=\"350211A1049\"/><id eventno=\"\" extension=\"\"/><effectiveTime/><recordTarget><patient><id extension=\"B55553768744\"/><name>江良福</name><sex codeSystem=\"GB/T2261.1-2003\" code=\"1\">男性</sex><birthDate>1993-08-05 00:00:00.0</birthDate><marriage codeSystem=\"GB/T 2261.2-2003\" code=\"\"/></patient></recordTarget><component><section><code displayName=\"门诊基本诊疗信息\" codeSystem=\"\" code=\"common\"/><entry><onsetTime/><treatTime/><diagnosisDate/><reg><value/><type codeSystem=\"STD_REG_TYPE\" code=\"51\">急诊</type></reg><sec><value>null</value><type codeSystem=\"STD_SEC_TYPE\" code=\"3\">自费医疗</type></sec><dept codeSystem=\"GB/T 17538-1998\" code=\"31600\"/><doctor><id extension=\"83178\"/><name/><title codeSystem=\"GB/T 8561-1988\" code=\"null\">null</title></doctor><symptom/><diagnosis><item><icd codeSystem=\"ICD-10\" code=\"T11.900\">上肢损伤</icd><result codeSystem=\"CV5501.11\" code=\"\"/><prop codeSystem=\"STD_DIAGNOSIS_PROP\" code=\"\"/></item></diagnosis></entry></section></component></ClinicalDocument>";
        String xmlJson = XMLUtil.xml2json(xml);
        JSONObject root = new JSONObject(xmlJson);

        //病人信息
        JSONObject patient = root.getJSONObject("recordTarget").getJSONObject("patient");
        String strssid = patient.getJSONObject("id").get("@extension").toString();//
        String name = patient.getString("name");//名字
        String sexCode = patient.getJSONObject("sex").get("@code").toString();//性别
        String sexName = patient.getJSONObject("sex").get("#text").toString();
        String birthDate = patient.getString("birthDate");//出生日起
        String marriageCode = patient.getJSONObject("marriage").get("@code").toString();//婚姻状况
        String marriageName = patient.getJSONObject("marriage").get("#text").toString();

        //门诊诊疗信息
        JSONObject component = root.getJSONObject("component").getJSONObject("section").getJSONObject("entry");
//        String onsetTime=component.getString("onsetTime");//发病时间
//        String treatTime=component.getString("treatTime");//治疗日期
//        String diagnosisDate=component.getString("diagnosisDate");//诊断日期
        String eventCode = component.getJSONObject("reg").getJSONObject("type").get("@code").toString();//事件类型
        String eventName = component.getJSONObject("reg").getJSONObject("type").get("#text").toString();
        String costOriCode = component.getJSONObject("sec").getJSONObject("type").get("@code").toString();//费用来源
        String costOriName = component.getJSONObject("sec").getJSONObject("type").get("#text").toString();
        String doctorCode = component.getJSONObject("doctor").getJSONObject("title").get("@code").toString();//医生信息
        String doctorName = component.getJSONObject("doctor").getJSONObject("title").get("#text").toString();
//        JSONArray symptom = component.getJSONArray("symptom");//症状
        String diagnosisCode = component.getJSONObject("diagnosis").getJSONObject("item").getJSONObject("icd").get("@code").toString();//诊断结果
        String diagnosisName = component.getJSONObject("diagnosis").getJSONObject("item").getJSONObject("icd").get("#text").toString();

        //返回前端格式
        JSONObject patientJson = new JSONObject();
        patientJson.put("strssid",strssid);
        patientJson.put("name",name);
        patientJson.put("sexCode",sexCode);
        patientJson.put("sexName",sexName);
        patientJson.put("birthDate",birthDate);
        patientJson.put("marriageCode",marriageCode);
        patientJson.put("marriageName",marriageName);

        JSONObject diagnosisJson = new JSONObject();
//        diagnosisJson.put("onsetTime",onsetTime);
//        diagnosisJson.put("treatTime",treatTime);
//        diagnosisJson.put("diagnosisDate",diagnosisDate);
        diagnosisJson.put("eventCode",eventCode);
        diagnosisJson.put("eventName",eventName);
        diagnosisJson.put("costOriCode",costOriCode);
        diagnosisJson.put("costOriName",costOriName);
        diagnosisJson.put("doctorCode",doctorCode);
        diagnosisJson.put("doctorName",doctorName);
        diagnosisJson.put("diagnosisCode",diagnosisCode);
        diagnosisJson.put("diagnosisName",diagnosisName);

        result.put("patient",patientJson);
        result.put("diagnosis",diagnosisJson);
        result.put("title",root.getString("title"));
        result.put("strssid",strssid);


        return result;
    }
}
