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

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SignFamilyRenewDao;
import com.yihu.wlyy.repository.patient.SignFamilyRenewLogDao;
import com.yihu.wlyy.repository.patient.SignWebDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 网络签约业务处理类
 *
 * @author George
 */
@Component
@Transactional
public class SignWebService extends BaseService {

    @Autowired
    private SignWebDao signWebDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PatientService patientService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private AdminTeamService adminTeamService;
    @Autowired
    private SystemDictService systemDictService;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private SignFamilyRenewDao signFamilyRenewDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private SignPatientLabelInfoService signPatientLabelInfoService;
    @Autowired
    private SignFamilyRenewLogDao signFamilyRenewLogDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private DoctorTeamMemberDao doctorTeamMemberDao;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;

    /**
     * 根据医生代码及签约状态编码 获取该医生签约患者的信息列表
     *
     * @param doctor
     * @param status
     * @param page
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> getSignWebByDoctor(String doctor, int status, int page, int pageSize) {
        // 查询语句
        String sql = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.idcard " +
                "    ,b.name " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                (status == 1 ? "    ,a.patient_apply_date as applyDate " : "    ,a.expenses_time as applyDate ") +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.renew_flag as renewFlag" +
                " from " +
                " ( select renew_flag,code,patient,doctor,status,id,apply_date,patient_apply_date,expenses_time,reason,begin from wlyy_sign_family where doctor = ?  and status = ? and type = 2" +
                (status == 3 ? " and expenses_status = '1'" : "") + " order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code  order by a.begin desc limit " + page * pageSize + "," + pageSize;

        // 未缴费查询语句
        String sqlExpenses = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.name " +
                "    ,b.idcard " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                "    ,a.apply_date as applyDate " +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.renew_flag as renewFlag" +
                " from " +
                " ( select renew_flag,code,patient,doctor,status,id,apply_date,reason,begin,expenses_status,LENGTH(trim(ifnull(expenses_status,''))) len from wlyy_sign_family where doctor = ?  and status > ? and type = 2 order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code and (a.expenses_status = '0' or a.len < 1) order by a.begin desc limit " + page * pageSize + "," + pageSize;

        // 已解约查询语句
        String surrSql = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.name " +
                "    ,b.idcard " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                "    ,a.apply_unsign_date as applyDate" +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.renew_flag as renewFlag" +
                " from " +
                " ( select renew_flag,code,patient,doctor,status,id,apply_date,apply_unsign_date,reason,begin from wlyy_sign_family where doctor = ?  and ( status = ? or status = ? ) and type = 2 order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code  order by a.begin desc limit " + page * pageSize + "," + pageSize;

        // 分页信息
        //PageRequest pageRequest = new PageRequest(page - 1, pageSize);
        //1:待签约 2, 待解约 3 已签约,4已经解约
        Page<Object> list = null;
        List<Map<String, Object>> patients = null;
        switch (status) {
            case 1:// 待签约
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, 0});
                break;
            case 2:// 待解约
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, 2});
                break;
            case 3:// 已签约
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, 1});
                break;
            case 4:// 4已经解约
                patients = jdbcTemplate.queryForList(surrSql, new Object[]{doctor, -3, -4});
                break;
            case 5: // 未缴费
                patients = jdbcTemplate.queryForList(sqlExpenses, new Object[]{doctor, 0});
        }

        return patients;
    }

    /**
     * 查询家庭签约已缴费未关注人数
     *
     * @param doctor
     * @return
     */
    public int isRemindFocusAll(String doctor) {
        boolean isAll = true;
        // 查询语句
        String sql = "select distinct b.code" +
                " from " +
                "     wlyy_sign_family f" +
                "     ,wlyy_patient b " +
                " where " +
                "     f.patient = b.code " +
                "     and (f.doctor = ? or f.doctor_health = ?)" +
                "     and f.expenses_status = '1' " +
                "     and f.status > 0 " +
                "     and f.type = 2 " +
                "     and LENGTH(trim(ifnull(b.openid,''))) < 1";

        List<String> result = jdbcTemplate.queryForList(sql, new Object[]{doctor, doctor}, String.class);

        if (result != null && result.size() > 0) {
            Set<String> set = redisTemplate.opsForSet().members("wechat:focus:remind:set");
            if (set == null) {
                isAll = false;
            } else if (!set.containsAll(result)) {
                isAll = false;
            }
        } else {
            isAll = true;
        }

        return isAll ? 1 : 0;
    }

    /**
     * 查询家庭签约已缴费未关注人数
     *
     * @param doctor
     * @return
     */
    public int isRemindExpensesAll(String doctor) {
        boolean isAll = true;
        // 查询语句
        String sql = "select distinct f.patient" +
                " from " +
                "     wlyy_sign_family f" +
                " where " +
                "     (f.doctor = ? or f.doctor_health = ?)" +
                "     and f.status > 0 " +
                "     and f.type = 2 " +
                "     and (f.expenses_status = 0 or LENGTH(trim(ifnull(f.expenses_status,''))) < 1)";

        List<String> result = jdbcTemplate.queryForList(sql, new Object[]{doctor, doctor}, String.class);

        if (result != null && result.size() > 0) {
            Set<String> set = redisTemplate.opsForSet().members("expenses:remind:set");
            if (set == null) {
                isAll = false;
            } else if (!set.containsAll(result)) {
                isAll = false;
            }
        } else {
            isAll = true;
        }

        return isAll ? 1 : 0;
    }

    /**
     * 根据代码查找签约信息明细
     *
     * @param code
     * @return
     */
    public SignWeb getSignWebByCode(String code) {
        return signWebDao.findByCode(code);
    }

    /**
     * 更新签约信息
     *
     * @return
     */
    public boolean saveSignWeb(SignWeb signWeb) {
        if (StringUtils.isEmpty(signWeb.getCode())) {
            signWeb.setCode(getCode());
            // 计算签约 月数
            if (signWeb.getBeginDate() != null && signWeb.getEndDate() != null) {
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(signWeb.getBeginDate());
                endDate.setTime(signWeb.getEndDate());

                int startYear = startDate.get(Calendar.YEAR);
                int startMonth = startDate.get(Calendar.MONTH);

                int endYear = endDate.get(Calendar.YEAR);
                int endMonth = endDate.get(Calendar.MONTH);

                int result = Math.abs(endMonth - startMonth);
                if (startYear != endYear) {
                    result = 12 * (endYear - startYear) + result;
                }
                signWeb.setMonths(result);
            }
        }
        signWebDao.save(signWeb);
        return true;
    }

    /**
     * 根据患者Code 获取患者当前签约的医生信息
     *
     * @param patient
     * @return
     */
    public SignWeb getSignWebByPatient(String patient) {
        return signWebDao.findSignWebByPatient(patient);
    }

    /**
     * 根据患者Code 查询条件 以及签约状态获取签约信息
     *
     * @param patient 患者Code
     * @param status  签约状态
     * @return
     */
    public Page<Object> getSignInfoByPatient(String patient, int status, long id, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize);

        Page<Object> listInfo = null;
        if (id > 0) {
            switch (status) {
                case 0:// 待签约
                    listInfo = signWebDao.findToBedSignInfoByPatient(patient, id, pageRequest);
                    break;
                case 1:// 已解约
                    listInfo = signWebDao.findCancelledSignInfoByPatient(patient, id, pageRequest);
                    break;
                case 2:// 已签约
                    listInfo = signWebDao.findSignedSignInfoByPatient(patient, id, pageRequest);
                    break;
                case 3:// 待解约
                    listInfo = signWebDao.findToCancelSignInfoByPatient(patient, id, pageRequest);
                    break;
                default:
                    listInfo = signWebDao.findSignInfoByPatient(patient, id, pageRequest);
            }
        } else {
            switch (status) {
                case 0:// 待签约
                    listInfo = signWebDao.findToBedSignInfoByPatient(patient, pageRequest);
                    break;
                case 1:// 已解约
                    listInfo = signWebDao.findCancelledSignInfoByPatient(patient, pageRequest);
                    break;
                case 2:// 已签约
                    listInfo = signWebDao.findSignedSignInfoByPatient(patient, pageRequest);
                    break;
                case 3:// 待解约
                    listInfo = signWebDao.findToCancelSignInfoByPatient(patient, pageRequest);
                    break;
                default:
                    listInfo = signWebDao.findSignInfoByPatient(patient, pageRequest);
            }
        }
        return listInfo;
    }

    /**
     * 获取已签约信息
     *
     * @param patient
     * @return
     */
    public List<Object> getSignInfoByStatus(String patient) {
        return signWebDao.findSignedSignInfoBystatus(patient);
    }

    /**
     * 通过身份证获取签约信息
     */
    public List<SignFamily> getSignInfoByIdcard(String idcard) {
        return signFamilyDao.findAllByIdcard(idcard);
    }

    public List<JSONObject> getSigns(String patient) {

        List<JSONObject> jsonArray = new ArrayList<JSONObject>();
        //加入续签表数据
//        List<SignFamilyRenew> renews = jdbcTemplate.queryForList(
//                "SELECT * FROM wlyy_sign_family_renew t " +
//                        "WHERE t.patient = '"+patient+"' AND t.status <> -1 and t.status <> -2",SignFamilyRenew.class);
        List<SignFamilyRenew> renews = signFamilyRenewDao.findAllActiveSignByPatient(patient);

        for (SignFamilyRenew renew : renews) {
            AdminTeam adminTeam = null;
            Doctor doctor = null;
            if (renew.getAdminTeamId() != null) {
                adminTeam = adminTeamService.getTeam(renew.getAdminTeamId());
                doctor = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
            }
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hospitalName", renew.getHospitalName());
            jsonObject.put("hospital", renew.getHospital());
            jsonObject.put("code", renew.getCode());
            jsonObject.put("teamCode", renew.getTeamCode());
            jsonObject.put("begin", renew.getBegin());
            jsonObject.put("end", renew.getEnd());
            jsonObject.put("status", renew.getStatus());
            jsonObject.put("leader", adminTeam.getLeaderCode());
            jsonObject.put("leaderName", doctor.getName());
            jsonObject.put("doctor", renew.getDoctor());
            jsonObject.put("doctorHealth", renew.getDoctorHealth());
            jsonObject.put("doctorName", renew.getDoctorName());
            jsonObject.put("doctorHealthName", renew.getDoctorHealthName());
            jsonObject.put("expensesStatus", StringUtils.isNotBlank(renew.getExpensesStatus()) ? renew.getExpensesStatus() : "1");
            jsonObject.put("applyDate", renew.getApplyDate());
            jsonObject.put("createTime", renew.getCzrq());
            jsonObject.put("type", renew.getType());
            jsonObject.put("typeName", renew.getType() == 1 ? "三师签约" : "家庭签约续签");
            jsonObject.put("isRenew", "1");
            String statusName = "";
            switch (jsonObject.getInt("status")) {
                case -4:
                    statusName = "已到期";
                    break;
                case -3:
                    statusName = "已解约";
                    break;
                case 0:
                    statusName = "待审核";
                    break;
                case 1:
                    if (jsonObject.getInt("expensesStatus") == 1) {
                        statusName = "已签约";
                    } else {
                        statusName = "待缴费";
                    }
                    break;
                case 2:
                    statusName = "患者申请取消签约";
                    break;
                case 3:
                    statusName = "医生申请取消签约";
                    break;
            }
            jsonObject.put("statusName", statusName);
            jsonArray.add(jsonObject);
        }

        //查询签约表数据
        List<SignFamily> signFamilys = signFamilyDao.findAllActiveSignByPatient(patient);

        for (SignFamily signFamily : signFamilys) {
            AdminTeam adminTeam = null;
            Doctor doctor = null;
            if (signFamily.getAdminTeamId() != null) {
                adminTeam = adminTeamService.getTeam(signFamily.getAdminTeamId());
                doctor = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
            }
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hospitalName", signFamily.getHospitalName());
            jsonObject.put("hospital", signFamily.getHospital());
            jsonObject.put("code", signFamily.getCode());
            jsonObject.put("teamCode", signFamily.getTeamCode());
            jsonObject.put("begin", signFamily.getBegin());
            jsonObject.put("end", signFamily.getEnd());
            jsonObject.put("status", signFamily.getStatus());
            jsonObject.put("leader", adminTeam.getLeaderCode());
            jsonObject.put("leaderName", doctor.getName());
            jsonObject.put("doctor", signFamily.getDoctor());
            jsonObject.put("doctorHealth", signFamily.getDoctorHealth());
            jsonObject.put("doctorName", signFamily.getDoctorName());
            jsonObject.put("doctorHealthName", signFamily.getDoctorHealthName());
            jsonObject.put("expensesStatus", StringUtils.isNotBlank(signFamily.getExpensesStatus()) ? signFamily.getExpensesStatus() : "1");
            jsonObject.put("applyDate", signFamily.getApplyDate());
            jsonObject.put("createTime", signFamily.getCzrq());
            jsonObject.put("type", signFamily.getType());
            jsonObject.put("typeName", signFamily.getType() == 1 ? "三师签约" : "家庭签约");
            if(StringUtils.isNotBlank(signFamily.getRenewFlag())){
                jsonObject.put("isRenew", "1");
            }else{
                jsonObject.put("isRenew", "0");
            }
            String statusName = "";
            switch (jsonObject.getInt("status")) {
                case -4:
                    statusName = "已到期";
                    break;
                case -3:
                    statusName = "已解约";
                    break;
                case 0:
                    statusName = "待签约";
                    break;
                case 1:
                    if (jsonObject.getInt("expensesStatus") == 1) {
                        statusName = "已签约";
                    } else {
                        statusName = "待缴费";
                    }
                    break;
                case 2:
                    statusName = "患者申请取消签约";
                    break;
                case 3:
                    statusName = "医生申请取消签约";
                    break;
            }
            jsonObject.put("statusName", statusName);
            jsonArray.add(jsonObject);
        }
        Collections.sort(jsonArray, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                Date o1Date = (Date) o1.get("createTime");
                Date o2Date = (Date) o2.get("createTime");
                if (o1Date.before(o2Date)) {
                    return 1;
                } else if (o1Date.after(o2Date)) {
                    return -1;
                }
                return 0;
            }
        });
        return jsonArray;
    }

    /**
     * 进行中的咨询获取服务团队信息
     * @param teamCode
     * @param code
     * @return
     */
    public JSONObject getConsultSignInfoOrRenewInfo(String teamCode, String code,String patient,String consultCode,Integer status) {

        //签约或续签参数
        String patientCode = null;
        Long adminTeamId = null;
        String doctorHealth = null;
        String doctor = null;
        //先查找续签表有没有记录
        List<SignFamilyRenew> renews = signFamilyRenewDao.findByTeamCodeIsValid(teamCode, code);

        if (renews == null || renews.size() == 0) {
            //再查找签约表记录
            SignFamily signFamily = null;
            if(consultCode==null){
                if(status==1){
                    signFamily = signFamilyDao.findByPatientCodeStatus(patient,status);
                }else {
                    signFamily = signFamilyDao.findOutTimeSigningByPatient(patient);
                }
            }else {
                signFamily = signFamilyDao.findByPatient(patient);
                Consult consult = consultDao.findByCode(consultCode);
                if(signFamily==null||signFamily.getApplyDate().getTime()-consult.getCzrq().getTime()>0){
                    signFamily = signFamilyDao.findOutTimeSigningByPatient(patient);
                }
            }
            if(signFamily==null){
                throw new RuntimeException("找不到签约关系！");
            }
            patientCode = signFamily.getPatient();
            adminTeamId = signFamily.getAdminTeamId();
            doctorHealth = signFamily.getDoctorHealth();
            doctor = signFamily.getDoctor();
        } else {
            SignFamilyRenew renew = renews.get(0);

            patientCode = renew.getPatient();
            adminTeamId = renew.getAdminTeamId();
            doctorHealth = renew.getDoctorHealth();
            doctor = renew.getDoctor();
        }


//        Patient p = patientService.findByCode(patientCode);
        JSONObject resultObject = new JSONObject();

        AdminTeam adminTeam = adminTeamService.getTeam(adminTeamId);
        //查找到团队领导
        Doctor leader = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
        JSONObject leaderObj = this.doctorParse(leader);
        resultObject.put("leader", leaderObj);

        //签约团队的健管师
        if (StringUtils.isNotBlank(doctorHealth)) {
            Doctor health = doctorService.findDoctorByCode(doctorHealth);
            if (health != null) {
                JSONObject healthObj = this.doctorParse(health);
                resultObject.put("doctorHealth", healthObj);
            } else {
                resultObject.put("doctorHealth", "");
            }
        }
        //签约团队的全科医生
        if (StringUtils.isNotBlank(doctor)) {
            Doctor qk = doctorService.findDoctorByCode(doctor);
            if (qk != null) {
                JSONObject healthObj = this.doctorParse(qk);
                resultObject.put("doctor", healthObj);
            } else {
                resultObject.put("doctor", "");
            }
        }
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int year = calendar.get(Calendar.YEAR);
        //统计当年咨询数量
        String consult_sql = "select count(1) as count from wlyy_consult_team  w where w.doctor = ? and w.patient =? and YEAR(w.czrq) = ? ";
        //统计随访数量
        String followup_sql = "select count(1) as count from wlyy_followup  w where (w.doctor_code = ? or w.doctor_code =?) and w.patient_code =? and YEAR(w.create_time) = ?  and w.followup_class is not null ";
        //统计待预约数量
        String reservation_sql = "select count(1) as count from wlyy_patient_reservation  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康教育数量
        String article_sql = "select count(1) as count from wlyy_health_edu_article_patient  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康指导数量
        String guidance_sql = "select count(1) as count from wlyy_patient_health_guidance  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";

        StringBuffer countSql = new StringBuffer();
        countSql.append(consult_sql).append(" union all ").append(followup_sql).append(" union all ").append(reservation_sql).append(" union all ").append(article_sql).append(" union all ").append(guidance_sql);
        List<Map<String, Object>> resultCount = jdbcTemplate.queryForList(countSql.toString(), new Object[]{doctorHealth, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year});
        resultObject.put("consultNum", resultCount.get(0).get("count"));
        resultObject.put("followupNum", resultCount.get(1).get("count"));
        resultObject.put("reservationNum", resultCount.get(2).get("count"));
        resultObject.put("articleNum", resultCount.get(3).get("count"));
        resultObject.put("guidanceNum", resultCount.get(4).get("count"));
        return resultObject;
    }

    /**
     * 已过时,启用getSignInfoOrRenewInfo
     *
     * @param teamCode
     * @return
     */
    public JSONObject getSignInfo(String teamCode, String code) {
        List<SignFamily> signFamilys = signFamilyDao.findByTeamCodeIsValid(teamCode, code);
        SignFamily signFamily = null;
        if (signFamilys == null || signFamilys.size() == 0) {
            throw new RuntimeException("找不到签约关系！");
        } else {
            signFamily = signFamilys.get(0);
            ;
        }
        Patient p = patientService.findByCode(signFamily.getPatient());
        String patient = p.getCode();
        JSONObject resultObject = new JSONObject();

        AdminTeam adminTeam = adminTeamService.getTeam(signFamily.getAdminTeamId());
        //查找到团队领导
        Doctor leader = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
        JSONObject leaderObj = this.doctorParse(leader);
        resultObject.put("leader", leaderObj);
        String doctorHealth = signFamily.getDoctorHealth();
        String doctor = signFamily.getDoctor();
        //签约团队的健管师
        if (StringUtils.isNotBlank(doctorHealth)) {
            Doctor health = doctorService.findDoctorByCode(doctorHealth);
            JSONObject healthObj = this.doctorParse(health);
            resultObject.put("doctorHealth", healthObj);
        }
        //签约团队的全科医生
        if (StringUtils.isNotBlank(doctor)) {
            Doctor qk = doctorService.findDoctorByCode(doctor);
            JSONObject qkObj = this.doctorParse(qk);
            resultObject.put("doctor", qkObj);
        }
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int year = calendar.get(Calendar.YEAR);
        //统计当年咨询数量
        String consult_sql = "select count(1) as count from wlyy_consult_team  w where w.doctor = ? and w.patient =? and YEAR(w.czrq) = ? ";
        //统计随访数量
        String followup_sql = "select count(1) as count from wlyy_followup  w where (w.doctor_code = ? or w.doctor_code =?) and w.patient_code =? and YEAR(w.create_time) = ? ";
        //统计待预约数量
        String reservation_sql = "select count(1) as count from wlyy_patient_reservation  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康教育数量
        String article_sql = "select count(1) as count from wlyy_health_edu_article_patient  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康指导数量
        String guidance_sql = "select count(1) as count from wlyy_patient_health_guidance  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";

        StringBuffer countSql = new StringBuffer();
        countSql.append(consult_sql).append(" union all ").append(followup_sql).append(" union all ").append(reservation_sql).append(" union all ").append(article_sql).append(" union all ").append(guidance_sql);
        List<Map<String, Object>> resultCount = jdbcTemplate.queryForList(countSql.toString(), new Object[]{doctorHealth, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year});
        resultObject.put("consultNum", resultCount.get(0).get("count"));
        resultObject.put("followupNum", resultCount.get(1).get("count"));
        resultObject.put("reservationNum", resultCount.get(2).get("count"));
        resultObject.put("articleNum", resultCount.get(3).get("count"));
        resultObject.put("guidanceNum", resultCount.get(4).get("count"));
        return resultObject;
    }

    private JSONObject doctorParse(Doctor doctor) {
        JSONObject object = new JSONObject();
        object.put("code", doctor.getCode());
        object.put("jobName", doctor.getJobName());
        object.put("level", doctor.getLevel());
        object.put("name", doctor.getName());
        object.put("evaluateScore", doctor.getEvaluateScore());
        object.put("photo", doctor.getPhoto());
        object.put("sex", doctor.getSex());
        object.put("hospitalName", doctor.getHospitalName());
        return object;
    }

    public JSONObject getSignServiceInfo(String signCode) {
        SignFamily signFamily = signFamilyDao.findByCode(signCode);
        if (signFamily == null) {
            return new JSONObject();
        }
        Patient p = patientService.findByCode(signFamily.getPatient());
        String patient = p.getCode();
        //获取咨询
        String consult_sql = "select w.consult,w.symptoms,w.czrq,w.status,1 as type from wlyy_consult_team  w where w.doctor = ? and w.patient =? and YEAR(w.czrq) = ? ";
        //获取随访
        String followup_sql = "select w.id,w.followup_type,w.followup_class,w.followup_date as czrq,w.followup_manager_status,w.status,2 as type from wlyy_followup  w where (w.doctor_code = ? or w.doctor_code =?) and w.patient_code =? and YEAR(w.create_time) = ?  ";
        //获取待预约
        String reservation_sql = "select w.code,w.id, w.doctor_name,w.doctor_code,w.doctor_job,w.doctor,w.dname,w.org_code,w.status,w.start_time as czrq,3 as type from wlyy_patient_reservation  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //获取健康教育
        String article_sql = "select w.id,w.article,w2.title,w2.summary,w.czrq,w.doctor,w.doctor_name,w.is_read,4 as type from wlyy_health_edu_article_patient  w,wlyy_health_edu_article w2 where w.article = w2.code and  (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //获取健康指导
        String guidance_sql = "select w.id,w.doctor,w.content,w.czrq,w.read_status,5 as type  from wlyy_patient_health_guidance  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";

        String doctorHealth = signFamily.getDoctorHealth();
        String doctor = signFamily.getDoctor();
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int year = calendar.get(Calendar.YEAR);
        //咨询量
        List<Map<String, Object>> consultResult = jdbcTemplate.queryForList(consult_sql, new Object[]{doctorHealth, patient, year});
        //随访量
        List<Map<String, Object>> followupResult = jdbcTemplate.queryForList(followup_sql, new Object[]{doctorHealth, doctor, patient, year});
        //待预约量
        List<Map<String, Object>> reservationResult = jdbcTemplate.queryForList(reservation_sql, new Object[]{doctorHealth, doctor, patient, year});
        //健康教育量
        List<Map<String, Object>> articleResult = jdbcTemplate.queryForList(article_sql, new Object[]{doctorHealth, doctor, patient, year});
        //健康指导量
        List<Map<String, Object>> guidanceResult = jdbcTemplate.queryForList(guidance_sql, new Object[]{doctorHealth, doctor, patient, year});
        List<JSONObject> objects = new ArrayList<>();
        int amount = consultResult.size() + followupResult.size() + reservationResult.size() + articleResult.size() + guidanceResult.size();
        int activeAmount = 0;
        objects.addAll(convertResult(consultResult));
        objects.addAll(convertResult(followupResult));
        objects.addAll(convertResult(reservationResult));
        objects.addAll(convertResult(articleResult));
        objects.addAll(convertResult(guidanceResult));
        for (JSONObject object : objects) {
            switch (object.get("type").toString()) {
                case "1":
                    activeAmount += ("1".equals(object.get("status")) ? 1 : 0);
                    break;
                case "2":
                    activeAmount += ("1".equals(object.get("status")) ? 1 : 0);
                    break;
                case "3":
                    activeAmount += ("1".equals(object.get("status")) ? 1 : 0);
                    break;
                case "4":
                    activeAmount += ("1".equals(object.get("is_read")) ? 0 : 1);
                    break;
                case "5":
                    activeAmount += ("1".equals(object.get("read_status")) ? 1 : 0);
                    break;
            }
        }
        objects.sort(new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                Date begin = DateUtil.strToDateLong(o1.get("czrq").toString());
                Date end = DateUtil.strToDateLong(o2.get("czrq").toString());

                if (begin != null && end != null && begin.before(end)) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        JSONObject object = new JSONObject();
        object.put("list", objects);
        object.put("amount", amount);
        object.put("activeAmount", activeAmount);
        return object;
    }

    private List<JSONObject> convertResult(List<Map<String, Object>> dataList) {
        List<JSONObject> objects = new ArrayList<>();
        JSONObject resultObject = new JSONObject();
        for (Map<String, Object> map : dataList) {
            switch (map.get("type").toString()) {
                case "1":
                    resultObject = convertConsult(map);
                    break;
                case "2":
                    resultObject = convertFollowup(map);
                    break;
                case "3":
                    resultObject = convertReservation(map);
                    break;
                case "4":
                    resultObject = convertArticle(map);
                    break;
                case "5":
                    resultObject = convertGuidance(map);
                    break;
            }
            objects.add(resultObject);
        }
        return objects;
    }

    /**
     * 返回值装换
     *
     * @param map
     * @return
     */
    private JSONObject convertConsult(Map<String, Object> map) {
        JSONObject resultObject = new JSONObject();
        for (String key : map.keySet()) {
            String value = map.get(key) + "";
            if ("status".equals(key)) {
                if ("1".equals(value)) {
                    resultObject.put("status_name", "已完成");
                } else {
                    resultObject.put("status_name", "进行中");
                }
            }
            resultObject.put(key, value);
        }
        return resultObject;
    }

    private JSONObject convertFollowup(Map<String, Object> map) {
        JSONObject resultObject = new JSONObject();
        if (map.get("followup_manager_status") == null) {
            map.put("followup_manager_status", "0");
        }
        if (map.get("followup_class") == null) {
            map.put("followup_class", "0");
        }
        for (String key : map.keySet()) {
            String value = map.get(key) + "";
            if ("followup_type".equals(key)) {
                String followupTypeName = systemDictService.getDictValue("FOLLOWUP_WAY_DICT", map.get(key) + "");
                resultObject.put("followup_type_name", followupTypeName);
            }
            if ("followup_class".equals(key)) {
                String followupClassName = systemDictService.getDictValue("FOLLOWUP_CLASS_DICT", map.get(key) + "");
                resultObject.put("followup_class_name", followupClassName);
            }
            if ("followup_manager_status".equals(key)) {
                String followupManagerStatusName = systemDictService.getDictValue("FOLLOWUP_MANAGER_STATUS", map.get(key) + "");
                resultObject.put("followup_manager_status_name", followupManagerStatusName);
            }
            if ("status".equals(key)) {
                if ("1".equals(value)) {
                    resultObject.put("status_name", "已完成");
                } else if ("2".equals(value)) {
                    resultObject.put("status_name", "未完成");
                } else if ("3".equals(value)) {
                    resultObject.put("status_name", "进行中");
                } else {
                    resultObject.put("status_name", "取消");
                }
            }
            resultObject.put(key, map.get(key) + "");
        }
        return resultObject;
    }

    private JSONObject convertReservation(Map<String, Object> map) {
        JSONObject resultObject = new JSONObject();
        for (String key : map.keySet()) {
            String value = map.get(key) + "";
            if ("status".equals(key)) {
                if ("1".equals(value)) {
                    resultObject.put("status_name", "已完成");
                } else {
                    resultObject.put("status_name", "已取消");
                }
            }
            resultObject.put(key, value);
        }
        return resultObject;
    }

    private JSONObject convertArticle(Map<String, Object> map) {
        JSONObject resultObject = new JSONObject();
        for (String key : map.keySet()) {
            String value = map.get(key) + "";
            if ("is_read".equals(key)) {
                if ("1".equals(value)) {
                    resultObject.put("status_name", "未读");
                } else {
                    resultObject.put("status_name", "已读");
                }
            }
            resultObject.put(key, value);
        }
        return resultObject;
    }

    private JSONObject convertGuidance(Map<String, Object> map) {
        JSONObject resultObject = new JSONObject();
        for (String key : map.keySet()) {
            String value = map.get(key) + "";
            if ("read_status".equals(key)) {
                if ("1".equals(value)) {
                    resultObject.put("status_name", "已读");
                } else {
                    resultObject.put("status_name", "未读");
                }
            }
            resultObject.put(key, value);
        }
        return resultObject;
    }

    /**
     * 根据医生代码及签约状态编码 获取该医生续签患者的信息列表
     *
     * @param doctor
     * @param status
     * @param page
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> getSignRenewWebByDoctor(String doctor, int status, int page, int pageSize) {
        // 查询语句
        String sql = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.idcard " +
                "    ,b.name " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                (status == 1 ? "    ,a.patient_apply_date as applyDate " : "    ,a.expenses_time as applyDate ") +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.czrq" +
                "    ,a.renew_flag as renewFlag "+
                " from " +
                " ( select czrq,code,patient,doctor,status,id,apply_date,patient_apply_date,expenses_time,reason,begin,renew_flag from wlyy_sign_family_renew where doctor = ? and status = ? and type = 2" +
                " order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code  order by a.begin desc limit " + page * pageSize + "," + pageSize;

        // 未缴费查询语句
        String sqlExpenses = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.name " +
                "    ,b.idcard " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                "    ,a.apply_date as applyDate " +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.czrq" +
                "    ,a.renew_flag as renewFlag "+
                " from " +
                " ( select czrq,renew_flag,code,patient,doctor,status,id,apply_date,reason,begin,expenses_status,LENGTH(trim(ifnull(expenses_status,''))) len from wlyy_sign_family_renew where doctor = ? and status > ? and type = 2 order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code and a.expenses_status = '0' order by a.begin desc limit " + page * pageSize + "," + pageSize;

        // 已签约
        String signedSql = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.idcard " +
                "    ,b.name " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                (status == 1 ? "    ,a.patient_apply_date as applyDate " : "    ,a.expenses_time as applyDate ") +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                "    ,a.czrq" +
                "    ,a.renew_flag as renewFlag "+
                " from " +
                " ( select expenses_status,czrq,code,patient,doctor,status,id,apply_date,patient_apply_date,expenses_time,reason,begin,renew_flag from wlyy_sign_family_renew where doctor = ? and status = ? and type = 2" +
                " order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code and a.expenses_status = '1' order by a.begin desc limit " + page * pageSize + "," + pageSize;


        //1:待签约 2, 待缴费 3 已签约
        Page<Object> list = null;
        List<Map<String, Object>> patients = null;
        switch (status) {
            case 1:// 待处理
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, 0});
                break;
            case 2:// 待缴费
                patients = jdbcTemplate.queryForList(sqlExpenses, new Object[]{doctor, 0});
                break;
            case 3:// 已签约
                patients = jdbcTemplate.queryForList(signedSql, new Object[]{doctor, 1});
                break;
        }

        return patients;
    }

    /**
     * 批量提醒用户
     *
     * @param access_token
     * @param doctor
     * @return
     * @throws Exception
     */
    public int sendRenewToPatients(String access_token, String doctor) throws Exception {
        String sql = "SELECT p.name,p.openid,t.doctor_name doctorName,p.code,p.mobile FROM wlyy_sign_family t ,wlyy_patient p " +
                "WHERE t.patient = p.code AND t.doctor = ? AND t.status >=0 AND t.expenses_status ='1' AND " +
                "NOT EXISTS" +
                "(SELECT 1 FROM wlyy_sign_family_renew a WHERE a.patient =t.patient)  ";

        List<Map<String, Object>> signFamilies = jdbcTemplate.queryForList(sql, new Object[]{doctor});

        if (signFamilies != null && signFamilies.size() > 0) {
            for (Map<String, Object> signFamily : signFamilies) {
                boolean flag = true;
                String openid = (String) signFamily.get("openid");
                String name = (String) signFamily.get("name");
                String doctorName = (String) signFamily.get("doctorName");
                JSONObject json = new JSONObject();
                String patient = (String) signFamily.get("code");
                json.put("toUser", patient);
                json.put("represented",patient);//被代理人
                json.put("keyword1", "续签家庭医生");
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark", "提醒医生 :" + doctorName + "\n"
                        + "我们将继续为您提供优质的健康服务。");
                if (StringUtils.isNotBlank(openid)) {
                    flag = false;
                    json.put("first", name + "，您好！\n" +
                            "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
                    PushMsgTask.getInstance().putWxMsg(access_token, 16, openid, name, json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient,openid);
                if(jsonArray!=null&&jsonArray.length()>0){
                    Patient p = patientService.findByCode(patient);
                    for (int i = 0;i<jsonArray.length();i++){
                        flag = false;
                        JSONObject j  = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser",member.getCode());
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                name + "，您好！\n" +
                                "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
                        PushMsgTask.getInstance().putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                    }
                }

                if(flag){
                    //发送短信
                    String mobile = (String) signFamily.get("mobile");
                    if (StringUtils.isNotBlank(mobile)) {
                        SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
                    }
                }

//                else {
//                    //如果自己没有绑定,则发给家人
//                    String code = (String) signFamily.get("code");
//                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(code);
//                    Patient member = (Patient) j.get("member");
//                    Patient p = patientService.findByCode(code);
//                    if (StringUtils.isNotBlank(member.getOpenid())) {
//                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
//                                name + "，您好！\n" +
//                                "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
//                        PushMsgTask.getInstance().putWxMsg(access_token, 16, member.getOpenid(), p.getName(), json);
//                    } else {
//                        //发送短信
//                        String mobile = (String) signFamily.get("mobile");
//                        if (StringUtils.isNotBlank(mobile)) {
//                            SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
//                        }
//                    }
//                }
            }
            return 1;
        }

        return 0;

    }

    /**
     * 批量提醒用户
     *
     * @param access_token
     * @param doctor
     * @return
     * @throws Exception
     */
    public int sendRenewOverToPatients(String access_token, String doctor) throws Exception {
        String sql = "SELECT " +
                " p. NAME, " +
                " p.openid, " +
                " t.doctor_name doctorName, " +
                " p. CODE, " +
                " p.mobile " +
                " FROM " +
                " wlyy_sign_family t, " +
                " wlyy_patient p " +
                " WHERE " +
                " t.patient = p. CODE " +
                " AND t.doctor = '"+doctor+"' " +
                " AND t.status =-4 " +
                " AND t.expenses_status = '1' " +
                " AND t.sign_year = '"+(DateUtil.getSignYear()-1)+"' " +
                " AND NOT EXISTS ( " +
                " SELECT " +
                "  1 " +
                " FROM " +
                "  wlyy_sign_family a " +
                " WHERE " +
                "  a.patient = t.patient " +
                " AND a.status>0  " +
                " AND a.sign_year = '"+DateUtil.getSignYear()+"' " +
                ")";

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

        if (signFamilies != null && signFamilies.size() > 0) {
            for (Map<String, Object> signFamily : signFamilies) {
                String openid = (String) signFamily.get("openid");
                String name = (String) signFamily.get("name");
                String doctorName = (String) signFamily.get("doctorName");
                JSONObject json = new JSONObject();
                Boolean flag = true;
                String patient = (String) signFamily.get("code");
                json.put("toUser", patient);
                json.put("represented",patient);//被代理人
                json.put("keyword1", "续签家庭医生");
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark", "提醒医生 :" + doctorName + "\n"
                        + "我们将继续为您提供优质的健康服务。");
                if (StringUtils.isNotBlank(openid)) {
                    json.put("first", name + "，您好！\n" +
                            "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
                    PushMsgTask.getInstance().putWxMsg(access_token, 16, openid, name, json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient,openid);
                if(jsonArray!=null&&jsonArray.length()>0){
                    Patient p = patientService.findByCode(patient);
                    for (int i = 0;i<jsonArray.length();i++){
                        flag = false;
                        JSONObject j  = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser",member.getCode());
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                name + "，您好！\n" +
                                "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
                        PushMsgTask.getInstance().putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
                    }
                }
                if(flag){
                    //发送短信
                    String mobile = (String) signFamily.get("mobile");
                    if (StringUtils.isNotBlank(mobile)) {
                        SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
                    }
                }

//                else {
//                    //如果自己没有绑定,则发给家人
//                    String code = (String) signFamily.get("code");
//                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(code);
//                    Patient member = (Patient) j.get("member");
//                    Patient p = patientService.findByCode(code);
//                    if (StringUtils.isNotBlank(member.getOpenid())) {
//                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
//                                name + "，您好！\n" +
//                                "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
//                        PushMsgTask.getInstance().putWxMsg(access_token, 16, member.getOpenid(), p.getName(), json);
//                    } else {
//                        //发送短信
//                        String mobile = (String) signFamily.get("mobile");
//                        if (StringUtils.isNotBlank(mobile)) {
//                            SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
//                        }
//                    }
//                }
            }
            return 1;
        }

        return 0;

    }

    /**
     * 同意或拒绝签约签约
     *
     * @param access_token
     * @param dotorCode
     * @param state        1成功 0拒绝
     * @return
     * @throws Exception
     */
    public int agreeRenew(String access_token, String dotorCode, String patientCode, String state, Long mesId, String signYear, String code,
                          String health,
                          String disease,
                          String custom,
                          String sevId,String healthDoctor,
                          Long teamCode,
                          String expenses) throws Exception {

//        List<SignFamilyRenew> renews = signFamilyRenewDao.findByDoctorAndPatientStatus0(dotorCode, patientCode, signYear);
//
//        if (renews == null || renews.size() == 0) {
//            renews = signFamilyRenewDao.findByDoctorHealthAndPatientStatus0(dotorCode, patientCode, signYear);
//        }
        SignFamilyRenew renew = signFamilyRenewDao.findByCode(code);

        if (renew != null) {
            int status = renew.getStatus();
            if (status == 0) {
                if (StringUtils.isNotBlank(state)) {
                    if ("0".equals(state)) {
                        renew.setStatus(-2);
                    } else if ("1".equals(state)) {
                        renew.setStatus(1);
                        //1.3.3.2新增需求
                        //设置居民服务类型
                        if(StringUtils.isNotBlank(sevId)){
                            setSevId(renew,sevId);
                        }
                        //1.3.3.2新增需求
                        //设置居民标签
                        signPatientLabelInfoService.setRenewPatientLabels(renew.getPatient(), health, disease,custom, renew.getDoctor(),renew.getDoctor());
                        //1.3.3.2设置可修改健康管理师
                        if(StringUtils.isNotBlank(healthDoctor)){
                            updateHealthDoctor(renew,healthDoctor);
                        }
                        //1.3.3.2设置新团队
                        if(teamCode!=null&&teamCode!=0){
                            renew.setAdminTeamId(teamCode);
                        }
                        renew.setExpensesType(StringUtils.isEmpty(expenses) ? "01" : expenses);//收费类别
                    }
                }
                renew.setApplyDate(new Date());
                //1.3.3.2 加入统计日志
                if ("1".equals(state)) {
                    setRenewLog(renew);
                }
                //1.3.3.4 根据团队设置标识
                setRenewFlag(renew,teamCode);

                signFamilyRenewDao.save(renew);

                setMessState(mesId);




                //发送微信模板消息
                JSONObject data = new JSONObject();
                data.put("doctorName", renew.getDoctorName());
                data.put("date", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                data.put("content", "家庭医生续签");
                data.put("doctor", dotorCode);
                data.put("toUser", patientCode);
                data.put("toName", renew.getName());
                data.put("isRenew","1");
                data.put("signState",state);

                Patient patient = patientService.findByCode(renew.getPatient());
                if (patient != null && StringUtils.isNotBlank(patient.getOpenid())) {

                    if ("0".equals(state)) {
                        data.put("first", renew.getName() + "，您好！\n" +
                                "您的家庭医生续签申请已被拒绝");
                        data.put("remark", "您可选择其他医生进行签约。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 2, patient.getOpenid(), patient.getName(), data);
                    } else if ("1".equals(state)) {
                        data.put("first", renew.getName() + "，您好！\n" +
                                "您的家庭医生续签申请已通过");
                        data.put("remark", "待自动扣费成功后，家庭医生将续签成功。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 1, patient.getOpenid(), patient.getName(), data);
                    }
                } else {
                    //如果自己没有绑定,则发给家人
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
                    Patient member = (Patient) j.get("member");
                    if (StringUtils.isNotBlank(member.getOpenid())) {

                        if ("0".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + "，您好！\n" +
                                    "您的家庭医生续签申请已被拒绝");
                            data.put("remark", "您可选择其他医生进行签约。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                        } else if ("1".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + "，您好！\n" +
                                    "您的家庭医生续签申请已通过");
                            data.put("remark", "待自动扣费成功后，家庭医生将续签成功。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                        }
                    }
                }

                //-1患者已取消，-2已拒绝，-3已解约，-4已到期，0待签约，1已签约，2患者申请取消签约，3医生申请取消签约
            } else if (status == 1) {
                //已经同意
                return 2;
            } else if (status == -1) {
                //-1患者已取消
                return 3;
            } else if (status == -2) {
                //已拒绝
                return 4;
            } else if (status == -3) {
                //已解约
                return 5;
            } else if (status == -4) {
                //已到期
                return 6;
            } else {
                //已申请取消
                return 7;
            }
        } else {
            //未找到签约关系
            return 0;
        }
        //成功
        return 1;
    }

    /**
     * 同意或拒绝签约签约(七月份的流程)
     *
     * @param access_token
     * @param dotorCode
     * @param state        1成功 0拒绝
     * @return
     * @throws Exception
     */
    public int agreeRenewOverDue(String access_token, String dotorCode, String patientCode, String state, Long mesId, String signYear, String signCode, String health,
                                 String disease,
                                 String custom,
                                 String sevId,String healthDoctor,
                                 Long teamCode,
                                 String expenses) throws Exception {

//        List<SignFamily> renews = signFamilyDao.findByDoctorAndPatientOverDue(dotorCode, patientCode, signYear);
//
//        if (renews == null || renews.size() == 0) {
//            renews = signFamilyDao.findByDoctorHealthAndPatient(dotorCode, patientCode, signYear);
//        }
        SignFamily renew = signFamilyDao.findByCode(signCode);

        if (renew != null) {
            int status = renew.getStatus();
            if (status == 0) {
                if (StringUtils.isNotBlank(state)) {
                    if ("0".equals(state)) {
                        renew.setStatus(-2);
                    } else if ("1".equals(state)) {
                        renew.setStatus(1);

                        //1.3.3.2新增需求
                        //设置居民服务类型
                        setSevId(renew,sevId);
                        //1.3.3.2新增需求
                        //设置居民标签
                        signPatientLabelInfoService.setPatientLabels(renew.getPatient(), renew.getIdcard(),"", health, disease, custom, renew.getDoctor(), renew.getDoctor());
                        //1.3.3.2设置可修改健康管理师
                        if(StringUtils.isNotBlank(healthDoctor)){
                            updateHealthDoctor(renew,healthDoctor);
                        }
                        //1.3.3.2设置新团队
                        if(teamCode!=null&&teamCode!=0){
                            renew.setAdminTeamId(teamCode);
                        }
                        renew.setExpensesType(StringUtils.isEmpty(expenses) ? "01" : expenses);//收费类别
                    }
                }
                renew.setApplyDate(new Date());
                //1.3.3.4 根据团队设置标识
                setRenewFlag(renew,teamCode);

                signFamilyDao.save(renew);
                //消息设为已读
                setMessState(mesId);

                if ("1".equals(state)) {
                    setRenewLog(renew);
                }

                //发送微信模板消息
                JSONObject data = new JSONObject();
                data.put("doctorName", renew.getDoctorName());
                data.put("date", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                data.put("content", "家庭医生续签");
                data.put("doctor", dotorCode);
                data.put("toUser", patientCode);
                data.put("toName", renew.getName());
                data.put("isRenew","1");//表示为续签操作

                Patient patient = patientService.findByCode(renew.getPatient());
                if (patient != null && StringUtils.isNotBlank(patient.getOpenid())) {

                    if ("0".equals(state)) {
                        data.put("first", renew.getName() + "，您好！\n" +
                                "您的家庭医生续签申请已被拒绝");
                        data.put("remark", "您可在到期后选择其他医生进行签约。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 2, patient.getOpenid(), patient.getName(), data);
                    } else if ("1".equals(state)) {
                        data.put("first", renew.getName() + "，您好！\n" +
                                "您的家庭医生续签申请已通过");
                        data.put("remark", "待自动扣费成功后，家庭医生将续签成功。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 1, patient.getOpenid(), patient.getName(), data);
                    }
                } else {
                    //如果自己没有绑定,则发给家人
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
                    Patient member = (Patient) j.get("member");
                    if (StringUtils.isNotBlank(member.getOpenid())) {

                        if ("0".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + "，您好！\n" +
                                    "您的家庭医生续签申请已被拒绝");
                            data.put("remark", "您可在到期后选择其他医生进行签约。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                        } else if ("1".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + "，您好！\n" +
                                    "您的家庭医生续签申请已通过");
                            data.put("remark", "待自动扣费成功后，家庭医生将续签成功。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                        }
                    }
                }
            } else if (status == 1) {
                //已经同意
                return 2;
            } else if (status == -1) {
                //已拒绝
                return 3;
            } else if (status == -2) {
                //已拒绝
                return 4;
            } else if (status == -3) {
                //已解约
                return 5;
            } else if (status == -4) {
                //已到期
                return 6;
            } else {
                //已取消
                return 7;
            }
        } else {
            return 0;
        }
        return 1;
    }

    /**
     * 获取年度列表
     * 团队
     * @return
     */
    public JSONObject getRenewYearCount(Long teamCode) {
        StringBuffer sql = new StringBuffer("SELECT t.sign_year labelCode,t.sign_year labelName,COUNT(1) amount " +
                "FROM  wlyy_sign_family t WHERE t.admin_team_code =" + teamCode + "  AND t.status=-4 AND sign_year IS NOT NULL GROUP BY t.sign_year DESC");
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result", rs);
        return json;
    }

    /**
     * 获取年度列表
     * 团队
     * @return
     */
    public JSONObject getRenewYearCountByDoctor(Long teamCode,String doctor) {
        StringBuffer sql = new StringBuffer("SELECT t.sign_year labelCode,t.sign_year labelName,COUNT(1) amount " +
                "FROM  wlyy_sign_family t WHERE t.doctor ='"+doctor+"' AND  t.admin_team_code =" + teamCode + "  AND t.status=-4 AND sign_year IS NOT NULL GROUP BY t.sign_year DESC");
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result", rs);
        return json;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public JSONObject getOverDuePatients(String year, Long teamCode,String doctor, Integer page, Integer pageSize) {
        StringBuffer sql = new StringBuffer("SELECT IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age," +
                "t.patient code,t.idcard,t.name,t.mobile,t.openid," +
                "t.ssc,t.type signType,p.sex ,t.expenses_status expensesStatus " +
                " FROM wlyy_sign_family t " +
                " LEFT JOIN wlyy_patient p ON t.patient = p.code " +
                " WHERE t.doctor ='"+doctor+"' AND t.admin_team_code =" + teamCode + " AND t.sign_year ='" + year + "' AND t.status =-4 LIMIT " + page * pageSize + "," + pageSize);
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result", rs);
        return json;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public JSONObject getOverDuePatientsByTeam(String year, Long teamCode, Integer page, Integer pageSize) {
        StringBuffer sql = new StringBuffer("SELECT IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age," +
                "t.patient code,t.idcard,t.name,t.mobile,t.openid," +
                "t.ssc,t.type signType,p.sex ,t.expenses_status expensesStatus " +
                " FROM wlyy_sign_family t " +
                " LEFT JOIN wlyy_patient p ON t.patient = p.code " +
                " WHERE t.admin_team_code =" + teamCode + " AND t.sign_year ='" + year + "' AND t.status =-4 LIMIT " + page * pageSize + "," + pageSize);
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result", rs);
        return json;
    }

    /**
     * 统计
     * 咨询量、获取待预约、获取健康教育、获取健康指导
     *
     * @param patient
     * @return
     */
    public JSONObject getSignCountInfoInYear(String patient) {

        JSONObject rs = new JSONObject();

        List<SignFamily> signFamilys = signFamilyDao.findByPatientsLastYear(patient, (DateUtil.getNowYear() - 1) + "");
        if (signFamilys == null || signFamilys.size() == 0) {
            throw new RuntimeException("找不到签约关系！");
        }
        SignFamily signFamily = signFamilys.get(0);
        String doctors_sql = "";
        if (StringUtils.isNotBlank(signFamily.getTeamCode())) {
            doctors_sql = "SELECT DISTINCT t.name,t.member_code member FROM wlyy_doctor_team_member t WHERE t.team ='" + signFamily.getTeamCode() + "' AND t.type <>5";
        } else {
            throw new RuntimeException("找不到团队关系！");
        }
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(doctors_sql);
        String doctorCodeSql = "";
        if (doctors != null && doctors.size() > 0) {
            for (int i = 0; i < doctors.size(); i++) {
                Map<String, Object> doctor = doctors.get(i);
                if (i == 0) {
                    doctorCodeSql = "'" + (String) doctor.get("member") + "'";
                } else {
                    doctorCodeSql += ",'" + (String) doctor.get("member") + "'";
                }
            }
        }
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //咨询量
        String consult_sql = "SELECT COUNT(1) AS consultCount,d.name doctorName FROM wlyy_consult_team t,wlyy_doctor d WHERE t.doctor = d.code AND t.patient ='" + patient + "' " +
                "AND t.czrq <='" + year + "-07-01' AND t.czrq >='" + (year - 1) + "-07-01' GROUP BY t.doctor DESC ";
        //获取待预约
        String reservation_sql = "SELECT COUNT(1) AS reservationCount FROM wlyy_patient_reservation  w " +
                " WHERE w.doctor in(" + doctorCodeSql + ") AND w.patient ='" + patient + "'" +
                " AND w.czrq <='" + year + "-07-01' AND w.czrq >='" + (year - 1) + "-07-01'  ";
        //获取健康教育
        String article_sql = "SELECT COUNT(1) AS articleCount FROM wlyy_health_edu_article_patient  w,wlyy_health_edu_article w2 WHERE w.article = w2.code " +
                "AND  w.doctor IN(" + doctorCodeSql + ") AND w.patient ='" + patient + "' " +
                "AND w.czrq <='" + year + "-07-01' AND w.czrq >='" + (year - 1) + "-07-01'  ";
        //获取健康指导
        String guidance_sql = "SELECT COUNT(1) AS guidanceCount  FROM wlyy_patient_health_guidance  w " +
                "WHERE w.doctor IN(" + doctorCodeSql + ") and w.patient ='" + patient + "' AND w.czrq <='" + year + "-07-01' AND w.czrq >='" + (year - 1) + "-07-01'  ";

        //咨询量
        List<Map<String, Object>> consultResult = jdbcTemplate.queryForList(consult_sql);
        //待预约量
        List<Map<String, Object>> reservationResult = jdbcTemplate.queryForList(reservation_sql);
        //健康教育量
        List<Map<String, Object>> articleResult = jdbcTemplate.queryForList(article_sql);
        //健康指导量
        List<Map<String, Object>> guidanceResult = jdbcTemplate.queryForList(guidance_sql);

        Long consultTotal = 0L;
        if (consultResult != null && consultResult.size() > 0) {
            for (Map<String, Object> map : consultResult) {
                Long c = (Long) map.get("consultCount");
                consultTotal += c;
            }
        }

        rs.put("consultTotal", consultTotal);
        rs.put("consultResult", consultResult);
        rs.put("doctors", doctors);
        rs.put("reservationResult", reservationResult);
        rs.put("articleResult", articleResult);
        rs.put("guidanceResult", guidanceResult);
        return rs;
    }

    /**
     * 提醒用户续签约
     *
     * @param access_token
     * @param patientCode
     * @param doctor
     * @return
     * @throws Exception
     */
    public int remainPatientRenew(String access_token, String patientCode, String doctor) throws Exception {

        Doctor d = doctorDao.findByCode(doctor);
        if (doctor == null) {
            return -1;
        }
        //发送微信模板消息
        Patient p = patientService.findByCode(patientCode);
        JSONObject json = new JSONObject();
        json.put("toUser", patientCode);
        json.put("represented",patientCode);//被代理人
        json.put("keyword1", "续签家庭医生");
        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
        json.put("remark", "提醒医生 :" + d.getName() + "\n"
                + "我们将继续为您提供优质的健康服务。");
        String openid = p.getOpenid();
        String name = p.getName();

        if (StringUtils.isNotBlank(openid)) {
            json.put("first", name + "，您好！\n" +
                    "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
            PushMsgTask.getInstance().putWxMsg(access_token, 16, openid, name, json);
            patientSetReminFlag(patientCode);
            return 1;
        }

        //发送代理人
        boolean flag = true;
        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patientCode,openid);
        if(jsonArray!=null&&jsonArray.length()>0){
            for (int i = 0;i<jsonArray.length();i++){
                flag = false;
                JSONObject j  = jsonArray.getJSONObject(i);
                Patient member = (Patient) j.get("member");
                JSONObject data = json;
                data.remove("toUser");
                data.put("toUser",member.getCode());
                json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                        name + "，您好！\n" +
                        "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
                PushMsgTask.getInstance().putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
            }
        }
        if(flag){
            //发送短信
            String mobile = p.getMobile();
            if (StringUtils.isNotBlank(mobile)) {
                SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
                patientSetReminFlag(patientCode);
                return 2;
            }
        }else {
            return 1;
        }

//        else {
//            //如果自己没有绑定,则发给家人
//            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patientCode);
//            Patient member = (Patient) j.get("member");
//            if (StringUtils.isNotBlank(member.getOpenid())) {
//                json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), name) + "\n" +
//                        name + "，您好！\n" +
//                        "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。");
//                PushMsgTask.getInstance().putWxMsg(access_token, 16, member.getOpenid(), name, json);
//                patientSetReminFlag(patientCode);
//                return 1;
//            } else {
//                //发送短信
//                String mobile = p.getMobile();
//                if (StringUtils.isNotBlank(mobile)) {
//                    SMSService.sendMsg(mobile, name + "您好！您的家庭医生将于6月30日到期，为了继续给您提供健康服务，请关注“厦门i健康”公众号，回复“续签”，进行家庭医生线上续签。");
//                    patientSetReminFlag(patientCode);
//                    return 2;
//                }
//            }
//        }
        return -1;
    }

    public void patientSetReminFlag(String patient) {
        String dateKey = DateUtil.dateToStr(new Date(), "yyyyMMdd");
        redisTemplate.opsForValue().set("renew:" + dateKey + ":" + patient, "1");
    }

    //判断用户当前年度是否有已经付费的签约记录
    public int checkNowYearSign(String doctor, String patient) {

        List<SignFamilyRenew> renews1 = signFamilyRenewDao.findByDoctorAndPatientIsValid(doctor, patient, DateUtil.getNowYear() + "");
        if (renews1 != null && renews1.size() > 0) {
            return 0;
        }
        List<SignFamilyRenew> renews2 = signFamilyRenewDao.findByDoctorHealthAndPatientIsValid(doctor, patient, DateUtil.getNowYear() + "");
        if (renews2 != null && renews2.size() > 0) {
            return 0;
        }
        List<SignFamily> sign1 = signFamilyDao.findByDoctorAndPatientIsValid(doctor, patient, DateUtil.getNowYear() + "");
        if (sign1 != null && sign1.size() > 0) {
            return 0;
        }
        List<SignFamily> sign2 = signFamilyDao.findByDoctorHealthAndPatientIsValid(doctor, patient, DateUtil.getNowYear() + "");
        if (sign2 != null && sign2.size() > 0) {
            return 0;
        }
        return 1;
    }

    /**
     * 设置消息为已读
     *
     * @param mesId
     */
    public void setMessState(Long mesId) {
        if (mesId != null && mesId > 0) {
            Message mes = messageDao.findOne(mesId);
            mes.setRead(0);//设置已读
            mes.setOver("0");//设置消息操作结束
            mes.setCzrq(new Date());
            messageDao.save(mes);
        }
    }

    public JSONObject getSignInfoOrRenewInfo(String teamCode, String code) {

        //签约或续签参数
        String patientCode = null;
        Long adminTeamId = null;
        String doctorHealth = null;
        String doctor = null;
        //先查找续签表有没有记录
        List<SignFamilyRenew> renews = signFamilyRenewDao.findByTeamCodeIsValid(teamCode, code);

        if (renews == null || renews.size() == 0) {
            //再查找签约表记录
            List<SignFamily> signFamilys = signFamilyDao.findByTeamCodeIsValid(teamCode, code);
            if (signFamilys == null || signFamilys.size() == 0) {
                throw new RuntimeException("找不到签约关系！");
            } else {
                SignFamily signFamily = signFamilys.get(0);

                patientCode = signFamily.getPatient();
                adminTeamId = signFamily.getAdminTeamId();
                doctorHealth = signFamily.getDoctorHealth();
                doctor = signFamily.getDoctor();
            }
        } else {
            SignFamilyRenew renew = renews.get(0);

            patientCode = renew.getPatient();
            adminTeamId = renew.getAdminTeamId();
            doctorHealth = renew.getDoctorHealth();
            doctor = renew.getDoctor();
        }


        Patient p = patientService.findByCode(patientCode);
        String patient = p.getCode();
        JSONObject resultObject = new JSONObject();

        AdminTeam adminTeam = adminTeamService.getTeam(adminTeamId);
        //查找到团队领导
        Doctor leader = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
        JSONObject leaderObj = this.doctorParse(leader);
        resultObject.put("leader", leaderObj);

        //签约团队的健管师
        if (StringUtils.isNotBlank(doctorHealth)) {
            Doctor health = doctorService.findDoctorByCode(doctorHealth);
            if (health != null) {
                JSONObject healthObj = this.doctorParse(health);
                resultObject.put("doctorHealth", healthObj);
            } else {
                resultObject.put("doctorHealth", "");
            }
        }
        //签约团队的全科医生
        if (StringUtils.isNotBlank(doctor)) {
            Doctor qk = doctorService.findDoctorByCode(doctor);
            if (qk != null) {
                JSONObject healthObj = this.doctorParse(qk);
                resultObject.put("doctor", healthObj);
            } else {
                resultObject.put("doctor", "");
            }
        }
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int year = calendar.get(Calendar.YEAR);
        //统计当年咨询数量
        String consult_sql = "select count(1) as count from wlyy_consult_team  w where w.doctor = ? and w.patient =? and YEAR(w.czrq) = ? ";
        //统计随访数量
        String followup_sql = "select count(1) as count from wlyy_followup  w where (w.doctor_code = ? or w.doctor_code =?) and w.patient_code =? and YEAR(w.create_time) = ? ";
        //统计待预约数量
        String reservation_sql = "select count(1) as count from wlyy_patient_reservation  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康教育数量
        String article_sql = "select count(1) as count from wlyy_health_edu_article_patient  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";
        //统计健康指导数量
        String guidance_sql = "select count(1) as count from wlyy_patient_health_guidance  w where (w.doctor = ? or w.doctor =?) and w.patient =? and YEAR(w.czrq) = ? ";

        StringBuffer countSql = new StringBuffer();
        countSql.append(consult_sql).append(" union all ").append(followup_sql).append(" union all ").append(reservation_sql).append(" union all ").append(article_sql).append(" union all ").append(guidance_sql);
        List<Map<String, Object>> resultCount = jdbcTemplate.queryForList(countSql.toString(), new Object[]{doctorHealth, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year, doctorHealth, doctor, patient, year});
        resultObject.put("consultNum", resultCount.get(0).get("count"));
        resultObject.put("followupNum", resultCount.get(1).get("count"));
        resultObject.put("reservationNum", resultCount.get(2).get("count"));
        resultObject.put("articleNum", resultCount.get(3).get("count"));
        resultObject.put("guidanceNum", resultCount.get(4).get("count"));
        return resultObject;
    }

    /**
     * 设置服务表服务类型
     * @param renew
     * @param sevId
     */
    public void setSevId(SignFamilyRenew renew, String sevId) {
        if (StringUtils.isNotBlank(sevId)) {
            int flag = sevId.indexOf("-");
            if (flag != -1) {
                String sql = "select d.name from wlyy_sign_dict d where d.code = '" + sevId + "' and d.year ='"+DateUtil.getSignYear()+"' ";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
                String[] keys = sevId.split("-");

                if (list != null && list.size() > 0) {
                    Map<String, Object> name = list.get(0);
                    String populationName = (String) name.get("name");
                    if (StringUtils.isNotBlank(populationName)) {
                        renew.setSpecialPopulation(keys[1]);
                        renew.setSpecialPopulationName(populationName);
                    }

                }

                if (keys != null && keys.length > 0) {
                    String sql2 = "select d.name from wlyy_sign_dict d where d.code = '" + keys[0] + "' and d.year ='"+DateUtil.getSignYear()+"' ";
                    List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                    if (list2 != null && list2.size() > 0) {
                        Map<String, Object> name = list2.get(0);
                        String serverTypeName = (String) name.get("name");
                        if (StringUtils.isNotBlank(serverTypeName)) {
                            renew.setServerType(keys[0]);
                            renew.setServerTypeName(serverTypeName);
                        }

                    }
                }
            } else {
                String sql2 = "select d.name from wlyy_sign_dict d where d.code = '" + sevId + "' and d.year ='"+DateUtil.getSignYear()+"' ";
                List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                if (list2 != null && list2.size() > 0) {
                    Map<String, Object> name = list2.get(0);
                    String serverTypeName = (String) name.get("name");
                    if (StringUtils.isNotBlank(serverTypeName)) {
                        renew.setServerType(sevId);
                        renew.setServerTypeName(serverTypeName);
                    }
                }
            }
        }
    }

    /**
     * 设置签约表服务类型
     * @param renew
     * @param sevId
     */
    public void setSevId(SignFamily renew, String sevId) {
        if (StringUtils.isNotBlank(sevId)) {
            int flag = sevId.indexOf("-");
            if (flag != -1) {
                String sql = "select d.name from wlyy_sign_dict d where d.code = '" + sevId + "' and d.year ='"+DateUtil.getSignYear()+"' ";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

                String[] keys = sevId.split("-");

                if (list != null && list.size() > 0) {
                    Map<String, Object> name = list.get(0);
                    String populationName = (String) name.get("name");
                    if (StringUtils.isNotBlank(populationName)) {
                        renew.setSpecialPopulation(keys[1]);
                        renew.setSpecialPopulationName(populationName);
                    }

                }

                if (keys != null && keys.length > 0) {
                    String sql2 = "select d.name from wlyy_sign_dict d where d.code = '" + keys[0] + "' and d.year ='"+DateUtil.getSignYear()+"' ";
                    List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                    if (list2 != null && list2.size() > 0) {
                        Map<String, Object> name = list2.get(0);
                        String serverTypeName = (String) name.get("name");
                        if (StringUtils.isNotBlank(serverTypeName)) {
                            renew.setServerType(keys[0]);
                            renew.setServerTypeName(serverTypeName);
                        }

                    }
                }
            } else {
                String sql2 = "select d.name from wlyy_sign_dict d where d.code = '" +sevId+ "' and d.year ='"+DateUtil.getSignYear()+"' ";
                List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                if (list2 != null && list2.size() > 0) {
                    Map<String, Object> name = list2.get(0);
                    String serverTypeName = (String) name.get("name");
                    if (StringUtils.isNotBlank(serverTypeName)) {
                        renew.setServerType(sevId);
                        renew.setServerTypeName(serverTypeName);
                    }

                }
            }
        }
    }

//    public void setHealthDoctor(SignFamilyRenew signFamilyRenew,String healthDoctor){
//        Doctor doctor = doctorDao.findByCode(healthDoctor);
//        signFamilyRenew.setDoctorHealth(doctor.getCode());
//        signFamilyRenew.setDoctorHealthName(doctor.getName());
//    }
//
//    public void setHealthDoctor(SignFamily signFamilyRenew,String healthDoctor){
//        Doctor doctor = doctorDao.findByCode(healthDoctor);
//        signFamilyRenew.setDoctorHealth(doctor.getCode());
//        signFamilyRenew.setDoctorHealthName(doctor.getName());
//    }

    public int setRenewLog(SignFamilyRenew renew){
        if(renew ==null) {
            return -1;
        }

        String sql = "SELECT * FROM wlyy_sign_family f WHERE f.patient ='"+renew.getPatient()+"' AND (f.`status` =-4 OR f.`status`>0) AND f.expenses_status ='1' AND f.sign_year >='"+(Integer.parseInt(renew.getSignYear())-1)+"' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,Object> sign = null;
        if(list!=null&&list.size()>0){
            sign = list.get(0);
        }
        SignFamilyRenewLog log = new SignFamilyRenewLog();
        //存储新记录
        log.setRenewSignCode(renew.getCode());
        log.setSignYear(renew.getSignYear());
        log.setIdcard(renew.getIdcard());
        log.setAdminTeamId(renew.getAdminTeamId());
        log.setDoctor(renew.getDoctor());
        log.setHospital(renew.getHospital());

        //存储旧签约记录
        if(sign!=null){
            Integer id =(Integer) sign.get("admin_team_code");
            log.setOldSignCode((String)sign.get("code"));
            log.setOldAdminTeamId(id.longValue());
            log.setOldHospital((String)sign.get("hospital"));
            log.setOldDoctor((String)sign.get("doctor"));
        }
        log.setNeedUpload("1");
        log.setCreateTime(new Date());
        log.setUpdateTime(new Date());
        signFamilyRenewLogDao.save(log);
        return 1;
    }

    public int setRenewLog(SignFamily renew){
        if(renew ==null) {
            return -1;
        }

        String sql = "SELECT * FROM wlyy_sign_family f WHERE f.patient ='"+renew.getPatient()+"' AND (f.`status` =-4 OR f.`status`>0) AND f.expenses_status ='1' AND f.sign_year >='"+(Integer.parseInt(renew.getSignYear())-1)+"' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,Object> sign = null;
        if(list!=null&&list.size()>0){
            sign = list.get(0);
        }
        SignFamilyRenewLog log = new SignFamilyRenewLog();
        //存储新记录
        log.setSignCode(renew.getCode());
        log.setSignYear(renew.getSignYear());
        log.setIdcard(renew.getIdcard());
        log.setAdminTeamId(renew.getAdminTeamId());
        log.setDoctor(renew.getDoctor());
        log.setHospital(renew.getHospital());

        //存储旧签约记录
        if(sign!=null){
            Integer id =(Integer) sign.get("admin_team_code");
            log.setOldSignCode((String)sign.get("code"));
            log.setOldAdminTeamId(id.longValue());
            log.setOldHospital((String)sign.get("hospital"));
            log.setOldDoctor((String)sign.get("doctor"));
        }
        log.setNeedUpload("1");
        log.setCreateTime(new Date());
        log.setUpdateTime(new Date());
        //1.3.4新增字段
        log.setStatus(renew.getStatus());
        if(StringUtils.isNotBlank(renew.getRenewChangeReason())){
            log.setRenewChangeReason(renew.getRenewChangeReason());
        }
        log.setApplyDate(renew.getApplyDate());
        log.setExpensesStatus(renew.getExpensesStatus());

        signFamilyRenewLogDao.save(log);
        return 1;
    }

    public void updateHealthDoctor(SignFamilyRenew renew ,String healthDoctor){

        DoctorTeam team =  doctorTeamDao.findByCode(renew.getTeamCode());
        if(StringUtils.isNotBlank(renew.getDoctorHealth())){
            //删除之前健管师成员
            doctorTeamMemberDao.deleteMember(renew.getDoctorHealth());
        }
        Doctor hd = doctorDao.findByCode(healthDoctor);
        if(hd==null){
            return ;
        }
        team.setName(renew.getDoctorName()+","+hd.getName()+","+renew.getName());
        //新建健康管理师
        DoctorTeamMember hdmb = new DoctorTeamMember();
        hdmb.setName(hd.getName());
        hdmb.setMemberCode(healthDoctor);
        hdmb.setCode(getCode());
        hdmb.setDel("1");
        hdmb.setCzrq(new Date());
        hdmb.setTeam(team.getCode());
        hdmb.setType(3);
        hdmb.setSignType("2");
        //新增团队成员
        doctorTeamMemberDao.save(hdmb);
        //保存团队
        doctorTeamDao.save(team);

        renew.setDoctorHealthName(hd.getName());
        renew.setDoctorHealth(hd.getCode());
    }

    public void updateHealthDoctor(SignFamily renew ,String healthDoctor){

        DoctorTeam team =  doctorTeamDao.findByCode(renew.getTeamCode());
        if(StringUtils.isNotBlank(renew.getDoctorHealth())){
            //删除之前健管师成员
            doctorTeamMemberDao.deleteMember(renew.getDoctorHealth());
        }
        Doctor hd = doctorDao.findByCode(healthDoctor);
        if(hd==null){
            return ;
        }
        team.setName(renew.getDoctorName()+","+hd.getName()+","+renew.getName());
        //新建健康管理师
        DoctorTeamMember hdmb = new DoctorTeamMember();
        hdmb.setName(hd.getName());
        hdmb.setMemberCode(healthDoctor);
        hdmb.setCode(getCode());
        hdmb.setDel("1");
        hdmb.setCzrq(new Date());
        hdmb.setTeam(team.getCode());
        hdmb.setType(3);
        hdmb.setSignType("2");
        //新增团队成员
        doctorTeamMemberDao.save(hdmb);
        //保存团队
        doctorTeamDao.save(team);

        renew.setDoctorHealthName(hd.getName());
        renew.setDoctorHealth(hd.getCode());
    }

    public JSONArray getRenewChangeReason(){
       List<SystemDict> systemDict = systemDictService.getDictByDictName("RENEW_CHANGE_REASON");
        return new JSONArray(systemDict);
    }

    public JSONObject getPatientSignLogInfo(String patient){
        Patient p = patientService.findByCode(patient);
        if(p!=null){
            String sql = "SELECT f.hospital_name as oldHospitalName,t.name AS oldTeamName,d.name as OldLeaderName,f.doctor_name AS OldDoctorName,f.doctor_health_name AS OldHealthDoctorName FROM wlyy_sign_family_renew_log r  " +
                    " LEFT JOIN wlyy_sign_family f ON r.old_sign_code = f.code " +
                    " LEFT JOIN wlyy_admin_team t ON r.old_admin_team_id = t.id " +
                    " LEFt JOIN wlyy_doctor d ON t.leader_code = d.code  " +
                    " WHERE r.idcard ='"+p.getIdcard()+"' AND r.sign_year='"+DateUtil.getSignYear()+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            if(list!=null&&list.size()>0){
               return new JSONObject(list.get(0));
            }
        }
        return new JSONObject();
    }

    public void setRenewFlag(SignFamily renew,Long teamCode){
        if(teamCode==null){
            return ;
        }
        String sql = "SELECT * FROM wlyy_sign_family f WHERE f.patient ='"+renew.getPatient()+"' AND (f.`status` =-4 OR f.`status`>0) AND f.expenses_status ='1' AND f.sign_year >='"+(Integer.parseInt(renew.getSignYear())-1)+"' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,Object> sign = null;
        if(list!=null&&list.size()>0){
            sign = list.get(0);
        }
        Integer i = (Integer)sign.get("admin_team_code");
        Long id = i.longValue();
        if(id==null){
            renew.setRenewFlag("2");
        }else{
            if(id==teamCode){
                renew.setRenewFlag("1");
            }else{
                renew.setRenewFlag("2");
            }
        }
    }

    public void setRenewFlag(SignFamilyRenew renew,Long teamCode){
        if(teamCode==null){
            return ;
        }
        String sql = "SELECT * FROM wlyy_sign_family f WHERE f.patient ='"+renew.getPatient()+"' AND (f.`status` =-4 OR f.`status`>0) AND f.expenses_status ='1' AND f.sign_year >='"+(Integer.parseInt(renew.getSignYear())-1)+"' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,Object> sign = null;
        if(list!=null&&list.size()>0){
            sign = list.get(0);
        }
        Integer i = (Integer)sign.get("admin_team_code");
        Long id = i.longValue();
        if(id==null){
            renew.setRenewFlag("2");
        }else{
            if(id==teamCode){
                renew.setRenewFlag("1");
            }else{
                renew.setRenewFlag("2");
            }
        }
    }
}
