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

import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.DateUtil;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Created by lyr-pc on 2017/1/10.
 */
@Service
public class ServiceStatisticsService extends BaseService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    SignFamilyDao signFamilyDao;

    @Autowired
    AdminTeamService teamService;

    public JSONObject getServiceStatistics(String patient, long teamCode, String doctor) throws Exception {
        JSONObject result = new JSONObject();
        AdminTeam team = teamService.getTeam(teamCode);
        SignFamily signFamily = signFamilyDao.findByPatientAndAdminTeamId(patient, teamCode, 2);

        if (signFamily == null) {
            signFamily = signFamilyDao.findByPatientAndAdminTeamId(patient, teamCode, 1);

            if (signFamily == null) {
                throw new Exception("patient and doctor no sign relation");
            } else {
                if((!doctor.equals(team.getLeaderCode()) && !doctor.equals(signFamily.getDoctor())
                        && !doctor.equals(signFamily.getDoctorHealth()))) {
                    throw new Exception("patient and doctor no sign relation");
                }
            }
        } else {
            if((!doctor.equals(team.getLeaderCode()) && !doctor.equals(signFamily.getDoctor())
                    && !doctor.equals(signFamily.getDoctorHealth()))) {
                signFamily = signFamilyDao.findByPatientAndAdminTeamId(patient, teamCode, 1);

                if (signFamily == null) {
                    throw new Exception("patient and doctor no sign relation");
                } else {
                    if((!doctor.equals(team.getLeaderCode()) && !doctor.equals(signFamily.getDoctor())
                            && !doctor.equals(signFamily.getDoctorHealth()))) {
                        throw new Exception("patient and doctor no sign relation");
                    }
                }
            }
        }

        if (signFamily == null) {
            signFamily = signFamilyDao.findByPatientAndAdminTeamId(patient, teamCode, 1);

            if (signFamily == null) {
                throw new Exception("sign info can not find");
            }
        }

        Calendar today = Calendar.getInstance();
        today.set(Calendar.DATE, 1);
        String monthBegin = DateUtil.dateToStrShort(today.getTime()) + " 00:00:00";
        String yearBegin = DateUtil.dateToStrShort(signFamily.getBegin()) + " 00:00:00";
        String yearEnd = DateUtil.dateToStrShort(signFamily.getEnd()) + " 23:59:59";
        JSONObject consult = getConsultStatistics(patient, teamCode, yearBegin, yearEnd, monthBegin);
        result.put("consult", consult);

        JSONObject followup = getFollowupStatistics(patient, teamCode, yearBegin, yearEnd, monthBegin);
        result.put("followup", followup);

        JSONObject reservation = getReservationStatistics(patient, teamCode, yearBegin, yearEnd, monthBegin);
        result.put("reservation", reservation);

        JSONObject guidance = getGuidanceStatistics(patient, teamCode, yearBegin, yearEnd, monthBegin);
        result.put("guidance", guidance);

        JSONObject article = getArticleStatistics(patient, teamCode, yearBegin, yearEnd, monthBegin);
        result.put("article", article);

        return result;
    }

    /**
     * 咨询统计
     *
     * @param patient
     * @param teamCode
     * @param yearBegin
     * @param yearEnd
     * @param monthBegin
     * @return
     */
    public JSONObject getConsultStatistics(String patient, long teamCode, String yearBegin, String yearEnd, String monthBegin) {
        JSONObject result = new JSONObject();
        result.put("history", 0);
        result.put("history", 0);
        result.put("history", 0);
        String sqlHistory = "select count(1) h from wlyy_consult_team where patient = ? and admin_team_code = ?";
        String sqlYear = "select count(1) y from wlyy_consult_team where patient = ? and admin_team_code = ? and czrq >= ? and czrq <= ?";
        String sqlMonth = "select count(1) m from wlyy_consult_team where patient = ? and admin_team_code = ? and czrq >= ?";
        String sql = "select * from " +
                "(" + sqlHistory + ") a" +
                ",(" + sqlYear + ") b" +
                ",(" + sqlMonth + ") c";

        List<Map<String, Object>> counts = jdbcTemplate.queryForList(sql, new Object[]{patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin
        });

        if (counts != null && counts.size() > 0) {
            result.put("history", counts.get(0).get("h").toString());
            result.put("year", counts.get(0).get("y").toString());
            result.put("month", counts.get(0).get("m").toString());
        }

        return result;
    }

    /**
     * 健康教育统计
     *
     * @param patient
     * @param teamCode
     * @param yearBegin
     * @param yearEnd
     * @param monthBegin
     * @return
     */
    public JSONObject getArticleStatistics(String patient, long teamCode, String yearBegin, String yearEnd, String monthBegin) {
        JSONObject result = new JSONObject();
        result.put("history", 0);
        result.put("year", 0);
        result.put("month", 0);
        String sqlHistory = "select count(1) h from wlyy_health_edu_article_patient where patient = ? and admin_team_code = ?";
        String sqlYear = "select count(1) y from wlyy_health_edu_article_patient where patient = ? and admin_team_code = ? and czrq >= ? and czrq <= ?";
        String sqlMonth = "select count(1) m from wlyy_health_edu_article_patient where patient = ? and admin_team_code = ? and czrq >= ?";
        String sql = "select * from " +
                "(" + sqlHistory + ") a" +
                ",(" + sqlYear + ") b" +
                ",(" + sqlMonth + ") c";

        List<Map<String, Object>> counts = jdbcTemplate.queryForList(sql, new Object[]{patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin
        });

        if (counts != null && counts.size() > 0) {
            result.put("history", counts.get(0).get("h").toString());
            result.put("year", counts.get(0).get("y").toString());
            result.put("month", counts.get(0).get("m").toString());
        }

        return result;
    }


    /**
     * 健康指导统计
     *
     * @param patient
     * @param teamCode
     * @param yearBegin
     * @param yearEnd
     * @param monthBegin
     * @return
     */
    public JSONObject getGuidanceStatistics(String patient, long teamCode, String yearBegin, String yearEnd, String monthBegin) {
        JSONObject result = new JSONObject();
        result.put("history", 0);
        result.put("year", 0);
        result.put("month", 0);
        String sqlHistory = "select count(1) h from wlyy_patient_health_guidance where patient = ? and admin_team_code = ?";
        String sqlYear = "select count(1) y from wlyy_patient_health_guidance where patient = ? and admin_team_code = ? and czrq >= ? and czrq <= ?";
        String sqlMonth = "select count(1) m from wlyy_patient_health_guidance where patient = ? and admin_team_code = ? and czrq >= ?";
        String sql = "select * from " +
                "(" + sqlHistory + ") a" +
                ",(" + sqlYear + ") b" +
                ",(" + sqlMonth + ") c";

        List<Map<String, Object>> counts = jdbcTemplate.queryForList(sql, new Object[]{patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin
        });

        if (counts != null && counts.size() > 0) {
            result.put("history", counts.get(0).get("h").toString());
            result.put("year", counts.get(0).get("y").toString());
            result.put("month", counts.get(0).get("m").toString());
        }

        return result;
    }

    /**
     * 随访计划统计
     *
     * @param patient
     * @param teamCode
     * @param yearBegin
     * @param yearEnd
     * @param monthBegin
     * @return
     */
    public JSONObject getFollowupStatistics(String patient, long teamCode, String yearBegin, String yearEnd, String monthBegin) {
        JSONObject result = new JSONObject();
        result.put("history", 0);
        result.put("year", 0);
        result.put("month", 0);
        String sqlHistory = "select count(1) h from wlyy_followup where patient_code = ? and admin_team_code = ?";
        String sqlYear = "select count(1) y from wlyy_followup where patient_code = ? and admin_team_code = ? and create_time >= ? and create_time <= ?";
        String sqlMonth = "select count(1) m from wlyy_followup where patient_code = ? and admin_team_code = ? and create_time >= ?";
        String sql = "select * from " +
                "(" + sqlHistory + " and status > 0" + ") a" +
                ",(" + sqlYear + " and status > 0" + ") b" +
                ",(" + sqlMonth + " and status > 0" + ") c" +
                ",(" + sqlHistory.replace(" h ", " hh ") + " and status = 1" + ") d" +
                ",(" + sqlYear.replace(" y ", " yy ") + " and status = 1" + ") e" +
                ",(" + sqlMonth.replace(" m ", " mm ") + " and status = 1" + ") f";

        List<Map<String, Object>> counts = jdbcTemplate.queryForList(sql, new Object[]{patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin, patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin
        });

        if (counts != null && counts.size() > 0) {
            result.put("history", counts.get(0).get("hh").toString() + "/" + counts.get(0).get("h").toString());
            result.put("year", counts.get(0).get("yy").toString() + "/" + counts.get(0).get("y").toString());
            result.put("month", counts.get(0).get("mm").toString() + "/" + counts.get(0).get("m").toString());
        }

        return result;
    }


    /**
     * 随访计划统计
     *
     * @param patient
     * @param teamCode
     * @param yearBegin
     * @param yearEnd
     * @param monthBegin
     * @return
     */
    public JSONObject getReservationStatistics(String patient, long teamCode, String yearBegin, String yearEnd, String monthBegin) {
        JSONObject result = new JSONObject();
        result.put("history", 0);
        result.put("year", 0);
        result.put("month", 0);
        String sqlHistory = "select count(1) h from wlyy_patient_reservation where patient = ? and admin_team_code = ?";
        String sqlYear = "select count(1) y from wlyy_patient_reservation where patient = ? and admin_team_code = ? and czrq >= ? and czrq <= ?";
        String sqlMonth = "select count(1) m from wlyy_patient_reservation where patient = ? and admin_team_code = ? and czrq >= ?";
        String sql = "select * from " +
                "(" + sqlHistory + ") a" +
                ",(" + sqlYear + ") b" +
                ",(" + sqlMonth + ") c";

        List<Map<String, Object>> counts = jdbcTemplate.queryForList(sql, new Object[]{patient, teamCode,
                patient, teamCode, yearBegin, yearEnd, patient, teamCode, monthBegin
        });

        if (counts != null && counts.size() > 0) {
            result.put("history", counts.get(0).get("h").toString());
            result.put("year", counts.get(0).get("y").toString());
            result.put("month", counts.get(0).get("m").toString());
        }

        return result;
    }

}
