package com.yihu.figure.service;

import com.yihu.figure.dao.disease.InspectionDao;
import com.yihu.figure.dao.disease.VisitDao;
import com.yihu.figure.model.disease.Inspection;
import com.yihu.figure.model.disease.Visit;
import com.yihu.figure.util.DateUtil;
import com.yihu.figure.util.HttpClientUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenweida on 2017/3/6.
 */
@Service
public class DiseaseService {
    private String baseurl = "http://120.41.252.108:8181/figure/";
    @Autowired
    private VisitDao visitDao;
    @Autowired
    private InspectionDao inspectionDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 造就诊事件的数据
     *
     * @param strSSID
     */
    @Transactional
    public void getResidentEventListJson(String strSSID, String patientCode) {
        String url = baseurl + "data/getResidentEventListJson?strSSID=" + strSSID;
        String response = HttpClientUtil.get(url, "UTF-8");
        JSONObject obj = new JSONObject(response);
        if (obj.has("门诊")) {
            List<Visit> visits = new ArrayList<>();
            JSONArray ja = obj.getJSONArray("门诊");
            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = ja.getJSONObject(i);
                Visit visit = new Visit(patientCode);
                visit.setDiagnosis(jo.getString("DIAGNOSIS"));
                visit.setEndTime(DateUtil.strToDate(jo.getString("END_TIME"), "yyyy-MM-dd HH:mm:ss"));
                visit.setEvent(jo.getString("EVENT"));
                visit.setOrgId(jo.getInt("ORG_ID"));
                visit.setOrgName(jo.getString("ORG_NAME"));
                visit.setR(jo.getInt("R") + "");
                visit.setType(jo.getInt("TYPE") + "");
                visit.setIcdCode(jo.getString("ICD_CODE"));
                visits.add(visit);
            }
            visitDao.save(visits);
        }
        if (obj.has("住院")) {
            List<Visit> visits = new ArrayList<>();
            JSONArray ja = obj.getJSONArray("住院");
            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = ja.getJSONObject(i);
                Visit visit = new Visit();
                visit.setDiagnosis(jo.getString("DIAGNOSIS"));
                visit.setEndTime(DateUtil.strToDate(jo.getString("END_TIME"), "yyyy-MM-dd HH:mm:ss"));
                visit.setEvent(jo.getString("EVENT"));
                visit.setOrgId(jo.getInt("ORG_ID"));
                visit.setOrgName(jo.getString("ORG_NAME"));
                visit.setR(jo.getInt("R") + "");
                visit.setType(jo.getInt("TYPE") + "");
                visit.setIcdCode(jo.getString("ICD_CODE"));
                visits.add(visit);
            }
            visitDao.save(visits);
        }
    }

    /**
     * 造检查检验的数据
     *
     * @param strSSID
     */
    @Transactional
    public void GetRecordListByCatalogcodesJson(String strSSID, String patientCode) {
        String url = baseurl + "data/GetRecordListByCatalogcodesJson?strSSID=" + strSSID;
        String response = HttpClientUtil.get(url, "UTF-8");
        JSONObject obj = new JSONObject(response);
        if (obj.has("检查")) {
            List<Inspection> inspections = new ArrayList<>();
            JSONArray ja = obj.getJSONArray("检查");
            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = ja.getJSONObject(i);
                Inspection inspection = new Inspection(patientCode);
                inspection.setCatalogCode(jo.getString("CATALOG_CODE"));
                inspection.setEhrCommitTime(DateUtil.strToDate(jo.getString("EHR_COMMIT_TIME"), "yyyy-MM-dd HH:mm:ss"));
                inspection.setEndTime(DateUtil.strToDate(jo.getString("END_TIME"), "yyyy-MM-dd HH:mm:ss"));
                inspection.setEvent(jo.getString("EVENT"));
                inspection.setItem(jo.getString("ITEM"));
                inspection.setOrgId(jo.getInt("ORG_ID"));
                inspection.setOrgName(jo.getString("ORG_NAME"));
                inspection.setR(jo.getInt("R"));
                inspection.setSerial(jo.getInt("SERIAL") + "");
                inspection.setType(jo.getInt("TYPE") + "");
                inspection.setUnionssid(jo.getString("UNIONSSID"));
                inspection.setXmanId(jo.getString("XMAN_ID"));
                inspections.add(inspection);
            }
            inspectionDao.save(inspections);
        }
    }

    /**
     * @param patientCode
     * @param time        2015
     * @return
     */
    public List<Visit> getVisits(String patientCode, String time, String icdName) {
        StringBuffer sql = new StringBuffer("select * from figure_visit f where 1=1 and  f.patient_code =? ");
        List<Object> params = new ArrayList<>();
        params.add(patientCode);

        if (!StringUtils.isEmpty(time)) {
            sql.append(" and f.end_time >= ? ");
            params.add(LocalDate.of(Integer.valueOf(time), 1, 1).toString());

            sql.append(" and f.end_time < ? ");
            params.add(LocalDate.of(Integer.valueOf(time), 1, 1).plusYears(1).toString());
        }
        if (!StringUtils.isEmpty(icdName)) {
            sql.append(" and f.diagnosis like ? ");
            params.add("%" + icdName + "%");
        }

        sql.append(" order by f.end_time desc ");

        List<Visit> visisList = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper(Visit.class));
        return visisList;
    }

    public List<Inspection> getInspections(String patientCode, String time, String type) {
        StringBuffer sql = new StringBuffer("select * from figure_inspection f where 1=1 and  f.patient_code =? ");
        List<Object> params = new ArrayList<>();
        params.add(patientCode);

        if (!StringUtils.isEmpty(time)) {
            sql.append(" and f.end_time >= ? ");
            params.add(LocalDate.of(Integer.valueOf(time), 1, 1).toString());

            sql.append(" and f.end_time < ? ");
            params.add(LocalDate.of(Integer.valueOf(time), 1, 1).plusYears(1).toString());
        }

        if (!StringUtils.isEmpty(type)) {
            sql.append(" and ( " +
                    " f.item like '%血常规%' or " +
                    " f.item like '%血糖%' or " +
                    " f.item like '%糖化%' or " +
                    " f.item like '%蛋白%' or " +
                    " f.item like '%眼底%' or " +
                    " f.item like '%肝功%'  ) ");
        }


        sql.append(" order by f.end_time desc ");
        List<Inspection> inspectionList = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper(Inspection.class));
        return inspectionList;
    }

    @Transactional
    public void deleteInspections(Long id) {
        inspectionDao.delete(id);
    }

    @Transactional
    public void deleteVisit(Long id) {
        visitDao.delete(id);
    }
}
