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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientEvent;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientEventDao;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by hzp on 2016/11/24.
 * 市民健康档案服务
 */
@Service
public class PatientRecordService {

    @Autowired
    private JwSmjkService jwSmjkService;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private PatientEventDao patientEventDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 字符串List排序
     */
    public List<Map<String, String>> sortMapList(List<Map<String, String>> mapList, final String sort, final String order) {
        Collections.sort(mapList, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String map1value = o1.get(sort);
                String map2value = o2.get(sort);
                if ("DESC".equals(order.toUpperCase())) {
                    return map2value.compareTo(map1value);
                } else {
                    return map1value.compareTo(map2value);
                }
            }
        });
        return mapList;
    }
    /******************************************************************************************************************/
    /**
     * 获取门/急诊记录 + 住院记录
     */
    public List<Map<String, String>> getAllEvent(String patientCode, String type, String page, String pageSize, String lastTime) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();

        //获取患者
        Patient patient = patientDao.findByCode(patientCode);
        //获取基卫数据
        String response = jwSmjkService.getResidentEventListJson(patient.getSsc(), type, page, pageSize);

        //获取app数据
        List<PatientEvent> eventList = new ArrayList<>();

        if (StringUtils.isEmpty(type)) {
            eventList = patientEventDao.findByPatient(patientCode);
        } else {
            eventList = patientEventDao.findByPatientAndEventType(patientCode, type);
        }

        if (!StringUtils.isEmpty(response)) {
            JSONArray array = new JSONArray(response);
            String max = "";
            String min = "";
            if (!"[{}]".equals(response)) {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    if (i == 0) //最大值
                    {
                        max = item.optString("END_TIME");
                    } else if (i == array.length() - 1) //最小值
                    {
                        min = item.optString("END_TIME");
                    }

                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.optString("EVENT"));
                    map.put("patient", patientCode);
                    map.put("eventDate", item.optString("END_TIME"));
                    map.put("eventType", item.optString("TYPE"));
                    map.put("orgName", item.optString("ORG_NAME"));
                    map.put("dianosis", item.optString("DIAGNOSIS"));
                    map.put("createTime", item.optString("END_TIME"));
                    map.put("dataFrom", "1");//基卫数据
                    re.add(map);
                }
            }

            //过滤
            for (PatientEvent item : eventList) {
                String eventDate = DateUtil.dateToStrLong(item.getEventDate());
                int maxCompare = eventDate.compareTo(max);
                int minCompare = eventDate.compareTo(min);
                Boolean contain = false;
                if (maxCompare < 0 && minCompare >= 0)       //时间范围内
                {
                    contain = true;
                }

                //第一页特殊处理
                if ("1".equals(page) && maxCompare >= 0) {
                    contain = true;
                }

                //最后一页特殊处理
                if (!"1".equals(page) && (array.length() == 0 || "[{}]".equals(response)) && !StringUtils.isEmpty(lastTime)) {
                    int lastTimeCompare = eventDate.compareTo(lastTime);
                    if (lastTimeCompare < 0) {
                        contain = true;
                    }
                }

                if (contain) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.getId().toString());
                    map.put("patient", item.getPatient());
                    map.put("eventDate", DateUtil.dateToStrLong(item.getEventDate()));
                    map.put("eventType", item.getEventType());
                    map.put("orgName", item.getOrgName());
                    map.put("dianosis", item.getDianosis());
                    map.put("createTime", DateUtil.dateToStrLong(item.getCreateTime()));
                    map.put("dataFrom", "2");   //APP数据
                    re.add(map);
                }
            }

            //排序
            re = sortMapList(re, "eventDate", "DESC");
        } else {
            if ("1".equals(page)) {
                for (PatientEvent item : eventList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.getId().toString());
                    map.put("patient", item.getPatient());
                    map.put("eventDate", DateUtil.dateToStrLong(item.getEventDate()));
                    map.put("eventType", item.getEventType());
                    map.put("orgName", item.getOrgName());
                    map.put("dianosis", item.getDianosis());
                    map.put("createTime", DateUtil.dateToStrLong(item.getCreateTime()));
                    map.put("dataFrom", "2");   //APP数据
                    re.add(map);
                }
            }
        }

        return re;
    }

    /**
     * 基卫通过event获取档案类型列表
     */
    public List<Map<String, String>> getEventCatalog(String patientCode, String strEvent) throws Exception {
        //获取患者
        Patient patient = patientDao.findByCode(patientCode);
        List<Map<String, String>> re = new ArrayList<>();

        String response = jwSmjkService.getEventCatalog(patient.getSsc(), strEvent);   //【基卫接口】
        JSONObject json = new JSONObject(response);
        JSONArray array = json.getJSONArray("RecordList");

        if (array != null && array.length() > 0) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject item = array.getJSONObject(i);
                Map<String, String> map = new HashMap<>();
                map.put("catalog", item.optString("CATALOG_CODE"));
                map.put("title", item.optString("TITLE"));
                map.put("serial", item.optString("SERIAL"));
                re.add(map);
            }
        }
        return re;
    }

    /**
     * 获取健康档案信息详情
     */
    public String getHealthData(String patientCode, String strEvent, String strCatalog, String strSerial) throws Exception {
        //获取患者
        Patient patient = patientDao.findByCode(patientCode);

        String respon = jwSmjkService.getHealthData(patient.getSsc(), strEvent, strCatalog, strSerial);  //【基卫接口】


        return respon;
    }


    /**
     * 获取检查检验列表
     */
    public List<Map<String, String>> getExamAndLabReport(String patientCode, String page, String pageSize, String lastTime) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();

        //获取患者
        Patient patient = patientDao.findByCode(patientCode);

        //获取基卫数据
        String response = jwSmjkService.getExamAndLabReport(patient.getSsc(), page, pageSize);     //【基卫接口】


        int pageInt = Integer.parseInt(page);
        int pageSizeInt = Integer.parseInt(pageSize);
        pageInt = pageInt > 0 ? pageInt -1 : 0;
        //获取app数据
        String sql = "select a.*,b.img_type as catalog,GROUP_CONCAT(b.img_label) as label \n" +
                "from wlyy_patient_event a,wlyy_patient_event_img b\n" +
                "where a.patient='" + patientCode + "' and b.event_id=a.id and b.img_type in ('检查报告','检验报告')  \n" +
                "group by b.event_id,b.img_type order by a.event_date desc";

        List<Map<String, Object>> appList = jdbcTemplate.queryForList(sql);

        if (!StringUtils.isEmpty(response) && !"[{}]".equals(response)) {
            JSONArray array = new JSONArray(response);
            String max = "";
            String min = "";

            for (int i = 0; i < array.length(); i++) {
                JSONObject item = array.getJSONObject(i);
                Map<String, String> map = new HashMap<>();
                if (i == 0) //最大值
                {
                    max = item.optString("END_TIME");
                } else if (i == array.length() - 1) //最小值
                {
                    min = item.optString("END_TIME");
                }

                map.put("id", item.optString("EVENT"));
                map.put("patient", patientCode);
                map.put("eventDate", item.optString("END_TIME"));
                String type = "";
                if ("0221".equals(item.optString("CATALOG_CODE"))) {
                    type = "检验";
                } else if ("0231".equals(item.optString("CATALOG_CODE"))) {
                    type = "检查";
                } else if ("0121".equals(item.optString("CATALOG_CODE"))) {
                    type = "检验";
                } else if ("0131".equals(item.optString("CATALOG_CODE"))) {
                    type = "检查";
                }
                map.put("type", type);
                map.put("catalogCode", item.optString("CATALOG_CODE")); //【基卫】档案类型
                map.put("serial", item.optString("SERIAL")); //【基卫】档案序号
                map.put("orgName", item.optString("ORG_NAME"));
                map.put("label", item.optString("ITEM")); //检测项目
                map.put("dataFrom", "1");//基卫数据
                re.add(map);
            }

            //过滤
            for (Map<String, Object> item : appList) {
                String eventDate = DateUtil.dateToStrLong((Date) item.get("event_date"));
                int maxCompare = eventDate.compareTo(max);
                int minCompare = eventDate.compareTo(min);
                Boolean contain = false;
                if (maxCompare < 0 && minCompare >= 0)       //时间范围内
                {
                    contain = true;
                }

                //第一页特殊处理
                if ("1".equals(page) && maxCompare >= 0) {
                    contain = true;
                }

                //最后一页特殊处理
                if (!"1".equals(page) && (array.length() == 0 || "[{}]".equals(response)) && !StringUtils.isEmpty(lastTime)) {
                    int lastTimeCompare = eventDate.compareTo(lastTime);
                    if (lastTimeCompare < 0) {
                        contain = true;
                    }
                }

                if (contain) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.get("id").toString());
                    map.put("patient", patientCode);
                    map.put("eventDate", eventDate);
                    String type = "";
                    if ("检验报告".equals(item.get("catalog"))) {
                        type = "检验";
                    } else if ("检查报告".equals(item.get("catalog"))) {
                        type = "检查";
                    }
                    map.put("type", type);
                    map.put("catalogCode", "");
                    map.put("serial", "");
                    map.put("orgName", String.valueOf(item.get("org_name")));
                    map.put("label", String.valueOf(item.get("label"))); //检测项目
                    map.put("dataFrom", "2");//基卫数据
                    re.add(map);
                }
            }

            //排序
            re = sortMapList(re, "eventDate", "DESC");
        } else {
            if ("1".equals(page)) {
                for (Map<String, Object> item : appList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", String.valueOf(item.get("id")));
                    map.put("patient", patientCode);
                    map.put("eventDate", DateUtil.dateToStrLong((Date) item.get("event_date")));
                    String type = "";
                    if ("检验报告".equals(item.get("catalog"))) {
                        type = "检验";
                    } else if ("检查报告".equals(item.get("catalog"))) {
                        type = "检查";
                    }
                    map.put("type", type);
                    map.put("catalogCode", "");
                    map.put("serial", "");
                    map.put("orgName", String.valueOf(item.get("org_name")));
                    map.put("label", String.valueOf(item.get("label"))); //检测项目
                    map.put("dataFrom", "2");//基卫数据
                    re.add(map);
                }
            }
        }

        return re;

    }

    /**
     * 获取用药列表
     */
    public String getDrugsListPage(String patientCode, String page, String pageSize) throws Exception {
        //获取患者
        Patient patient = patientDao.findByCode(patientCode);
        String response = jwSmjkService.getDrugsListPage(patient.getSsc(), page, pageSize);


        return response;
    }


}
