Sfoglia il codice sorgente

Merge branch 'dev' of http://192.168.1.220:10080/Amoy/patient-co-management into dev

yeshijie 7 anni fa
parent
commit
186b7f424c
26 ha cambiato i file con 7375 aggiunte e 101 eliminazioni
  1. 2 2
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/SignFamilyDao.java
  2. 17 13
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java
  3. 3 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java
  4. 1155 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  5. 160 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/consult/ConsultService.java
  6. 1388 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java
  7. 732 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java
  8. 2113 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  9. 1668 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java
  10. 2 0
      patient-co/patient-co-doctor-assistant/src/main/resources/application-dev.yml
  11. 2 0
      patient-co/patient-co-doctor-assistant/src/main/resources/application-devtest.yml
  12. 2 0
      patient-co/patient-co-doctor-assistant/src/main/resources/application-local.yml
  13. 2 0
      patient-co/patient-co-doctor-assistant/src/main/resources/application-localtest.yml
  14. 2 0
      patient-co/patient-co-doctor-assistant/src/main/resources/application-test.yml
  15. 3 1
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/Application.java
  16. 56 21
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java
  17. 3 4
      patient-co/patient-co-statistics-es/src/main/resources/application.yml
  18. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java
  19. 44 38
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  20. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionExpressageService.java
  21. 4 4
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionFollowupContentService.java
  22. 2 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java
  23. 3 9
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/call/CustomerService.java
  24. 3 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/call/CallRecordController.java
  25. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java
  26. 6 3
      patient-co/patient-co-wlyy/src/main/resources/config/fdfs_client.conf

+ 2 - 2
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/SignFamilyDao.java

@ -34,9 +34,9 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
    @Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
    List<SignFamily> findAllSignByPatient(String patient);
    @Query("select a from SignFamily a where a.patient = ?1 and a.status > 0 and expensesStatus=1")
    @Query("select a from SignFamily a where a.patient = ?1 and a.status > 0 and a.expensesStatus='1'")
    SignFamily findSignByPatient(String patient);
    @Query("select a from SignFamily a where a.patient = ?1 and a.status > 0 order by a.czrq desc")
    @Query("select a from SignFamily a where a.patient = ?1 and a.status > 0 and a.expensesStatus ='1' order by a.czrq desc")
    List<SignFamily> findSignInfo(String patient);
}

+ 17 - 13
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java

@ -384,20 +384,24 @@ public class DeviceService {
            if (result == null) {
                throw new Exception("This device is not relate patient!");
            } else {
    
                //患者信息
                String patientCode = result.getUser();
                Patient patient = patientDao.findByCode(patientCode);
                
                //血糖、血压数据需校验,如果超标,需要发送消息给医生
                if (1 == deviceType || 2 == deviceType) {
                    verifyHealthIndex(result);
                    //发送华三demo推送
	
	            //患者信息
	            String patientCode = result.getUser();
	            Patient patient = patientDao.findByCode(patientCode);
	
	            String patientsql = "select group_concat(label) disease from wlyy.wlyy_sign_patient_label_info where label_type = 3 and status=1 and (label = 1 or label = 2) and patient = '"+patient.getCode()+"' GROUP BY patient";
	
	            String patientdisease = jdbcTemplate.queryForObject(patientsql,String.class);
	
	            //血糖、血压数据需校验,如果超标,需要发送消息给医生
	            if (1 == deviceType || 2 == deviceType) {
		            verifyHealthIndex(result);
		            //发送华三demo推送
//                    messagePush(result);
                    
                    //判断是否有未结束的续方咨询,发送消息给对应的医生----huangwenjie--2017.11.06
                    sendPrescriptionHealthIndexMsgresult(result,patient);
                }
		
		            //判断是否有未结束的续方咨询,发送消息给对应的医生----huangwenjie--2017.11.06
		            sendPrescriptionHealthIndexMsgresult(result,patient);
	            }
                //指标数据上传基卫
                uploadHealthIndex(result);

+ 3 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java

@ -415,4 +415,7 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
    @Query(" select a from SignFamily a where a.patient = ?1 ")
    SignFamily findPatientExpensesStatus(String patient);
    // 查询团队已签约的总数
    @Query("select count(1) from SignFamily a where  a.adminTeamId = ?1 and (a.status = 1 or a.status = 2) and a.type = 2")
    int countAmountSignedByAdminTeam(Long id);
}

+ 1155 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java

@ -0,0 +1,1155 @@
package com.yihu.wlyy.service.app.account;
import com.yihu.wlyy.entity.address.City;
import com.yihu.wlyy.entity.address.Province;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.OperatorLog;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatientGroup;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.WlyyPatientSick;
import com.yihu.wlyy.entity.patient.prescription.Prescription;
import com.yihu.wlyy.repository.address.CityDao;
import com.yihu.wlyy.repository.address.ProvinceDao;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientSickDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.prescription.PrescriptionDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.third.httplog.LogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生基本信息类.
 *
 * @author George
 */
// Spring Service Bean的标识.
@Component
public class DoctorInfoService extends BaseService {
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ProvinceDao provinceDao;
    @Autowired
    private CityDao cityDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private DoctorTeamMemberDao doctorTeamDoctor;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private PatientSickDao patientSickDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    SMSService smsService;
    @Autowired
    DoctorWorkTimeService workTimeService;
    @Autowired
    WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    protected OperatorLogDao operatorLogDao;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private ImUtill ImUtill;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionDao prescriptionDao;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;//="http://192.168.131.131:8089";
    @Autowired
    private HttpClientUtil HttpClientUtil;
    @Autowired
    private LogService logService;
    /**
     * 获取医生的签约病人
     *
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatients(String doctor) {
        return signFamilyDao.findDoctorSignPatients(doctor);
    }
    /**
     * 获取医生的签约病人
     *SendPatientUtil
     *
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsLikeName(String doctor, String patientName) {
        return signFamilyDao.findDoctorSignPatientsLikeName(doctor, patientName);
    }
    /**
     * 获取医生的签约病人
     *
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsBySignType(String doctor, int type) {
        return signFamilyDao.findDoctorSignPatientsBySignType(doctor, type);
    }
    /**
     * 获取医生的签约病人
     *
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsByTypeName(String doctor, int type, String patientName) {
        return signFamilyDao.findDoctorSignPatientsByTypeName(doctor, type, patientName);
    }
    @Transactional
    public Doctor findDoctorByCode(String code) {
        return doctorDao.findByCode(code);
    }
    @Transactional
    public Doctor findDoctorByMobile(String mobile) {
        return doctorDao.findByMobile(mobile);
    }
    /**
     * 获取正常医生
     *
     * @param mobile
     * @return
     */
    @Transactional
    public Doctor findNormalByMobile(String mobile) {
        return doctorDao.findNormalByMobile(mobile);
    }
    /**
     * 更新医生基本信息
     *
     * @param doctor
     * @return
     */
    @Transactional
    public Doctor updateDoctor(Doctor doctor) {
        Province province = provinceDao.findByCode(doctor.getProvince());
        if (province != null) {
            doctor.setProvinceName(province.getName());
        }
        City city = cityDao.findByCode(doctor.getCity());
        if (city != null) {
            doctor.setCityName(city.getName());
        }
        Town town = townDao.findByCode(doctor.getTown());
        if (town != null) {
            doctor.setTownName(town.getName());
        }
        // Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
        // if(hospital != null){
        // doctor.setHosptialName(hospital.getName());
        // }
        // HospitalDept dept = hospitalDeptDao.findByCode(doctor.getDept());
        // if(dept != null){
        // doctor.setDeptName(dept.getName());
        // }
        // JobTitle job = jobDao.findByCode(doctor.getJob());
        // if(job != null){
        // doctor.setJobName(job.getName());
        // }
        return doctorDao.save(doctor);
    }
    /**
     * 修改医生密码
     */
    @Transactional
    public void updateDoctorPwd(Doctor doctor) {
        EncodesUtil.entryptPassword(doctor);
        doctorDao.save(doctor);
    }
    /**
     * 查询指定医生下的患者
     *
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> findPatientByDoctorSign(String doctor) {
        return doctorDao.findPatientByDoctorSign(doctor);
    }
    @Transactional
    public Page<Object> findPatientByDoctorSign(String doctor, long id,
                                                int pagesize, String patientName) {
        // return doctorDao.findPatientByDoctorSign(doctor);
        Page<Object> signList = null;
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize);
        if (StringUtils.isEmpty(patientName)) {
            // doctorDao.findPatientByDoctorSign(doctor);
            if (id > 0) {
                signList = doctorDao.findPatientByDoctorSign(doctor, id,
                        pageRequest);
            } else {
                signList = doctorDao.findPatientByDoctorSign(doctor,
                        pageRequest);
            }
        } else {
            patientName = "%" + patientName + "%";
            if (id > 0) {
                signList = doctorDao.findPatientByDoctorSign(doctor, id,
                        patientName, pageRequest);
            } else {
                signList = doctorDao.findPatientByDoctorSign(doctor,
                        patientName, pageRequest);
            }
        }
        return signList;
    }
    /**
     * 查该医生管理的患者总数
     *
     * @param doctor
     * @return
     */
    @Transactional
    public int amountPatientByDoctorSign(String doctor) {
        return doctorDao.amountPatientByDoctorSign(doctor);
    }
    /**
     * 查询指定医生的患者分组
     *
     * @param doctor
     * @return
     */
    @Transactional
    public Iterable<DoctorPatientGroup> findDoctorPatientGroup(String doctor) {
        return doctorDao.findDoctorPatientGroup(doctor);
    }
    @Transactional
    public Patient findPatientByCode(String code) {
        return doctorDao.findPatientByCode(code);
    }
    @Transactional
    public DoctorPatientGroupInfo findGroup(String user, String doctor) {
        return doctorDao.findGroup(user, doctor);
    }
    /**
     * 根据医院信息获取医生列表
     *
     * @param hospital 医院标识
     *                 页数
     * @return
     */
//    @Transactional
//    public Page<Doctor> getDoctorListByHospital(String query, String hospital,
//                                                int page, int pageSize) {
//        page = page <= 0 ? 0 : page - 1;
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "evaluateScore","id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(page, pageSize);
//        // 查询全部
//        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//        if (StringUtils.isNotEmpty(query)) {
//            query="%"+query+"%";
//        }else{
//            query="%";
//        }
//        if (StringUtils.isNotEmpty(hospital)) {
//            hospital = "%"+hospital.substring(0, 8)+"%";
//        }
//
//        filters.put("level", new SearchFilter("level", Operator.EQ, 2));
//        return doctorDao.getDoctorListByHospital(query,hospital,2, pageRequest);
//    }
    @Transactional
    public List<Doctor> getDoctorCombobxByHospital(String type, String hospital) {
        return doctorDao.getDoctorCombobxByHospital(hospital, Integer.valueOf(type));
    }
    @Transactional
    public Doctor getDoctor(int consultType, String patientCode) {
        //根据病人ID查找团队
        //DoctorTeam doctorTeam =doctorTeamDao.getBy
        return null;
    }
    @Transactional
    public Page<Doctor> getDoctorListByPatientCode(int consultType, String patientCode, String name, int page, int pageSize) {
        //
        return null;
    }
    @Transactional
    public Page<Doctor> getDoctorListByHospital(String name, String hospital, Integer page, Integer pageSize, Integer level) {
        if (pageSize == null | pageSize <= 0) {
            pageSize = 10;
        }
        if (page == null | page <= 0) {
            page = 1;
        }
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "evaluateScore");
        // 分页信息
        PageRequest pageRequest = new PageRequest(page - 1, pageSize, sort);
        // 查询全部
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNotEmpty(name)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, name));
        }
        if (StringUtils.isNotEmpty(hospital)) {
            filters.put("hospital", new SearchFilter("hospital", Operator.LIKE, "%" + hospital.substring(0, 8) + "%"));
        }
        filters.put("level", new SearchFilter("level", Operator.EQ, level));
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        return doctorDao.findAll(spec, pageRequest);
    }
    @Transactional
    public void doctor_1_Toteam(String teamCode, String doctor, String doctorName, String groupCode, String loginCode, String parientCode, String sickName, String sickNCode) {
        //得到患者所在的团队
        DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(parientCode);
        //添加专科医生
        //判断专科医生之前是否已经加入到这个团队
        DoctorTeamMember wlyyDoctorTeamDoctorTemp = doctorTeamDoctor.findMemberCodeAndTeam(doctorTeam.getCode(), doctor);
        if (wlyyDoctorTeamDoctorTemp != null) {
        } else {
            Patient patient = patientDao.findByCode(parientCode);
            patient.setDisease(Integer.valueOf(sickNCode));
            //更新之前这个团队的专业医生的del为0
            doctorTeamDoctor.updateType1Del(doctorTeam.getCode());
            //更新之前的患者病种表的del为0
            patientSickDao.updateType1Del(parientCode, sickNCode);
            // 专科医生没有分组的概念
            DoctorTeamMember wlyyDoctorTeamDoctor = new DoctorTeamMember();
            wlyyDoctorTeamDoctor.setTeam(doctorTeam.getCode());
            wlyyDoctorTeamDoctor.setMemberCode(doctor);
            wlyyDoctorTeamDoctor.setName(doctorName);
            wlyyDoctorTeamDoctor.setDel("1");
            wlyyDoctorTeamDoctor.setType(1);
            wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
            wlyyDoctorTeamDoctor.setCode(getCode());
            wlyyDoctorTeamDoctor.setCzrq(new Date());
            doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
            //添加患者患病表
            WlyyPatientSick wlyyPatientSick = new WlyyPatientSick();
            wlyyPatientSick.setDel("1");//未删除
            wlyyPatientSick.setCzrq(new Date());
            wlyyPatientSick.setCode(getCode());
            wlyyPatientSick.setPatientCode(parientCode);
            wlyyPatientSick.setDoctorCode(doctor);
            wlyyPatientSick.setSickName(sickName);
            wlyyPatientSick.setSickCode(sickNCode);
            wlyyPatientSick.setSignType("2");//家庭签约
            patientSickDao.save(wlyyPatientSick);
        }
        //把患者所在的健康管理师的组转慢病
        //查找出团队的全科医生
        //DoctorTeamMember doctor2= doctorTeamDoctor.findDoctor2ByTeam(doctorTeam.getCode(),"2");
        //查找出团队的健康管理师
        //DoctorTeamMember doctor3= doctorTeamDoctor.findDoctor2ByTeam(doctorTeam.getCode(),"3");
        //把患者转到的慢病组里
        doctorPatientGroupInfoDao.updateGroupByParient(parientCode);
    }
    @Transactional
    public List<Map> findNoInConsultDoctor(String existDoc, String consultCode, int page, int pageSzie) {
        int start = (page - 1) * pageSzie;
        String sql = "select p.* from wlyy_doctor p where " +
                "NOT EXISTS (SELECT 1 from wlyy_consult_team_doctor d WHERE d.to_doctor=p.code and d.consult='" + consultCode + "') " +
                " and p.level = 1 and p.iscertified=1 and p.status=1 and p.code<>'" + existDoc + "'" +
                " ORDER BY p.code limit " + start + "," + pageSzie;
        List rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    @Transactional
    public int countNoInConsultDoctor(String existDoc, String consultCode) {
        String sql = "SELECT count(*) as c FROM (" +
                "select 1 as c from wlyy_doctor p where " +
                "NOT EXISTS (SELECT 1 from wlyy_consult_team_doctor d WHERE d.to_doctor=p.code and d.consult='" + consultCode + "') " +
                " and p.level = 1 and p.iscertified=1 and p.status=1 and p.code<>'" + existDoc + "'" +
                ") b";
        List rs = jdbcTemplate.queryForList(sql);
        return ((Long) ((Map) rs.get(0)).get("c")).intValue();
    }
    @Transactional
    public Map<String, Object> getDoctor1ByParient(String consultCode, String parientCode, Integer page, Integer pageSzie) {
        Map<String, Object> returnMap = new HashMap<>();
        if (pageSzie == null | pageSzie <= 0) {
            pageSzie = 10;
        }
        if (page == null | page <= 0) {
            page = 1;
        }
        Consult consult = consultDao.findByCode(consultCode);
        if (consult.getType() == 2) {
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findByParientCodeAndSignType(parientCode, consult.getType() + "");
            //得到团队的专科医生
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctor2ByTeam(doctorTeam.getCode(), 1);
            String existDoc = doctorTeamMember != null ? doctorTeamMember.getMemberCode() : null;
            List<Map> rs = findNoInConsultDoctor(existDoc, consultCode, page, pageSzie);
            Doctor doctor = null;
            List<JSONObject> newDoctors = new ArrayList<>();
            JSONObject json;
            if (page == 1 && doctorTeamMember != null) {
                //如果专科存在
                if (consultTeamDoctorDao.isExist(consultCode, doctorTeamMember.getMemberCode()) == 0) {
                    doctor = doctorDao.findByCode(doctorTeamMember.getMemberCode());//专科医生
                    if (doctor != null) {
                        json = new JSONObject();
                        json.put("code", doctor.getCode());
                        json.put("name", doctor.getName());
                        json.put("photo", doctor.getPhoto());
                        json.put("id", doctor.getId());
                        json.put("hospital", doctor.getHospital());
                        json.put("hosptialName", doctor.getHospitalName());
                        newDoctors.add(json);
                    }
                }
            }
            if (rs != null) {
                for (Map m : rs) {
                    json = new JSONObject();
                    json.put("code", m.get("code"));
                    json.put("name", m.get("name"));
                    json.put("photo", m.get("photo"));
                    json.put("id", m.get("id"));
                    json.put("hospital", m.get("hospital"));
                    json.put("hosptialName", m.get("hospital_name"));
                    newDoctors.add(json);
                }
            }
            returnMap.put("doctors", newDoctors);
            int total = countNoInConsultDoctor(existDoc, consultCode);
            returnMap.put("totalPage", total / pageSzie + (total % pageSzie > 0 ? 1 : 0));
        } else {
            //三师只可以邀请自己的专科医生
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findByParientCodeAndSignType(parientCode, consult.getType() + "");
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctor2ByTeam(doctorTeam.getCode(), 1);
            Doctor doctor = doctorDao.findByCode(doctorTeamMember.getMemberCode());
            List<JSONObject> newDoctors = new ArrayList<>();
            JSONObject json = new JSONObject();
            json.put("code", doctor.getCode());
            json.put("name", doctor.getName());
            json.put("photo", doctor.getPhoto());
            json.put("id", doctor.getId());
            json.put("hospital", doctor.getHospital());
            json.put("hosptialName", doctor.getHospitalName());
            newDoctors.add(json);
            returnMap.put("doctors", newDoctors);
            returnMap.put("totalPage", 1);
        }
        return returnMap;
    }
    @Transactional
    public List<Doctor> findDoctorByLevelAndHospital(String hospital, Integer level) {
        return doctorDao.findDoctorByLevelAndHospital(hospital, level);
    }
    /**
     * 更新医生身份证号
     *
     * @param idcard
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateDoctorIdcard(String idcard, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setIdcard(idcard);
        return true;
    }
    /**
     * 更新医生专长
     *
     * @param expertise
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateExpertise(String expertise, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setExpertise(expertise);
        return true;
    }
    /**
     * 更新医生性别
     *
     * @param sex
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateSex(int sex, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setSex(sex);
        return true;
    }
    /**
     * 更新医生介绍
     *
     * @param introduce
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateIntroduce(String introduce, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setIntroduce(introduce);
        return true;
    }
    /**
     * 设置医生为名医
     *
     * @param doctorCode
     */
    @Transactional
    public void setFamous(String doctorCode, Integer status) {
        Doctor doctor = doctorDao.findByCode(doctorCode);
        //如果是空或者大于1 默认是关闭名医
        if (status == null || status > 1 || status == 0) {
            status = 0;
            doctor.setIsFamous(status);
            //更新医生改成可以接受咨询
            doctorWorkTimeService.updateDoctorWorkTime(doctorCode);
        } else {
            doctor.setIsFamous(status);
        }
    }
    @Transactional
    public Page<Doctor> findDoctorByDept(String dept, String hosptial, String key, int page, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        if (page <= 0) {
            page = 1;
        }
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        // 分页信息
        PageRequest pageRequest = new PageRequest(page - 1, pageSize, sort);
        // 查询全部
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNotEmpty(key)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, key));
        }
        if (StringUtils.isNotEmpty(dept)) {
            filters.put("dept", new SearchFilter("dept", Operator.EQ, dept));
        }
        if (StringUtils.isNotEmpty(hosptial)) {
            filters.put("hosptial", new SearchFilter("hosptial", Operator.EQ, hosptial));
        }
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        return doctorDao.findAll(spec, pageRequest);
    }
    @Transactional
    public Page<Doctor> findFamousDoctor(String key, Integer type, int page, int pageSize, Integer level) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        if (page <= 0) {
            page = 1;
        }
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        // 分页信息
        PageRequest pageRequest = new PageRequest(page - 1, pageSize, sort);
        // 查询全部
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNotEmpty(key)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, key));
        }
        filters.put("isFamous", new SearchFilter("isFamous", Operator.EQ, type));
        if (level != null && level > 0 && level < 4) {
            filters.put("level", new SearchFilter("level", Operator.EQ, level));
        }
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        return doctorDao.findAll(spec, pageRequest);
    }
    @Transactional
    public List<Doctor> findFamousDoctorList(String key, Integer type, int page, int pageSize, Integer level) throws Exception {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        if (page <= 0) {
            page = 1;
        }
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "name");
        // 查询全部
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNotEmpty(key)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, key));
        }
        if (type == 1) {
            filters.put("isFamous", new SearchFilter("isFamous", Operator.EQ, type));
        }
        if (level != null && level > 0 && level < 4) {
            filters.put("level", new SearchFilter("level", Operator.EQ, level));
        }
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        List<Doctor> doctors = doctorDao.findAll(spec, sort);
        List<Doctor> workingDoctor = new ArrayList<>();
        List<Doctor> returnList = new ArrayList<>();
        int start = (page - 1) * pageSize;
        int end = start + pageSize;
        if (doctors.size() > 0) {
            for (Doctor doc : doctors) {
                if (workingDoctor.size() > end) {
                    break;
                }
                if (type != 1) {
                    if (doc.getIsFamous() != null && doc.getIsFamous() == 1) {
                        continue;
                    }
                }
                JSONObject iswork = type == 1 ? workTimeService.isFamousDoctorWorking(doc.getCode()) : workTimeService.isDoctorWorking(doc.getCode());
                if (iswork.getString("status").equals("1")) {
                    workingDoctor.add(doc);
                }
            }
            if (end > workingDoctor.size()) {
                end = workingDoctor.size();
            }
            if (start < workingDoctor.size()) {
                returnList = workingDoctor.subList(start, end);
            }
        }
        return returnList;
    }
    @Transactional
    public JSONArray findWorkingDoctorListByDept(String dept, String hospital, String level, String key, int page, int pagesize) throws Exception {
        String sql = "select * from wlyy_doctor where  status = 1 ";
        List<Object> args = new ArrayList<>();
        if (!StringUtils.isEmpty(dept)) {
            sql += " and dept = ? ";
            args.add(dept);
        }
        if (!StringUtils.isEmpty(hospital)) {
            sql += " and hospital = ? ";
            args.add(hospital);
        }
        if (!StringUtils.isEmpty(level)) {
            sql += " and level = ? ";
            args.add(Integer.valueOf(level));
        }
        if (!StringUtils.isEmpty(key)) {
            sql += " and name like ? ";
            args.add("%" + key + "%");
        }
        if (page >= 0) {
            sql += " limit " + page * pagesize + "," + pagesize;
        }
        List<Doctor> doctors = jdbcTemplate.query(sql, args.toArray(), new BeanPropertyRowMapper(Doctor.class));
        JSONArray workingDoctor = new JSONArray();
        if (doctors.size() > 0) {
            for (Doctor doc : doctors) {
                JSONObject iswork = workTimeService.isDoctorWorking(doc.getCode());
                if (iswork.getString("status").equals("1")) {
                    JSONObject docJson = new JSONObject(doc);
                    if (docJson.has("password")) {
                        docJson.remove("password");
                    }
                    if (docJson.has("salt")) {
                        docJson.remove("salt");
                    }
                    workingDoctor.put(docJson);
                }
            }
        }
        return workingDoctor;
    }
    /**
     * 医生更换手机号
     *
     * @param doctor  医生code
     * @param mobile  新手机号
     * @param captcha 验证码
     * @return
     */
    @Transactional
    public int changeMobile(String doctor, String mobile, String captcha, int type) {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            return -1;
        }
        Doctor docMobile = doctorDao.findByMobile(mobile);
        if (docMobile != null && !docMobile.getCode().equals(doctor)) {
            return -2;
        }
        // 验证码验证
        int smsCheck = smsService.check(mobile, type == 1 ? 8 : 9, captcha);
        // 验证失败,不允许变更
        if (smsCheck != 1) {
            return -3;
        }
        //修改密码
        String oldPassword = doc.getPassword();
        //判断旧的密码是不是手机号码后六位
        String oldMobile = doc.getMobile();
        if (!org.springframework.util.StringUtils.isEmpty(oldMobile)) {
            String passwordTemp = oldMobile.substring(5);
            passwordTemp = MD5.GetMD5Code(passwordTemp + doc.getSalt());
            if (passwordTemp.equals(oldPassword)) {
                //如果密码是原来的电话号码后留位改成现在号码的后留位
                String newPassword = MD5.GetMD5Code(mobile.substring(5) + doc.getSalt());
                doc.setPassword(newPassword);
            }
        }
        doc.setMobile(mobile);
        return 1;
    }
    @Transactional
    public void updatePassword(String newPassword1, String newPassword2, String oldPassword, String doctorCode) throws Exception {
        if (!newPassword1.equals(newPassword2)) {
            throw new Exception("新密码不一致");
        }
        if (newPassword1.equals(oldPassword)) {
            throw new Exception("新旧密码一致");
        }
        Doctor doctor = doctorDao.findByCode(doctorCode);
        String oldPasswordTemp = MD5.GetMD5Code(oldPassword + doctor.getSalt());
        if (!oldPasswordTemp.equals(doctor.getPassword())) {
            throw new Exception("旧密码错误");
        }
        String newPassword1Temp = MD5.GetMD5Code(newPassword1 + doctor.getSalt());
        doctor.setPassword(newPassword1Temp);
    }
    /**
     * 查询患者是否与医生签约
     *
     * @param patient
     * @param doctor
     * @return
     */
    @Transactional
    public boolean isPatientSigned(String patient, String doctor) {
        boolean bo = false;
        //签约团队
        DoctorTeam dt = doctorTeamDao.findByPatientCode(patient);
        DoctorTeam dtSS = doctorTeamDao.findSsTeamByPatientCode(patient);
        //医生是否属于团队成员
        if (dt != null && doctorTeamDoctor.countMemberByTeamAndCode(dt.getCode(), doctor) > 0) {
            bo = true;
        }
        if (dtSS != null && doctorTeamDoctor.countMemberByTeamAndCode(dtSS.getCode(), doctor) > 0) {
            bo = true;
        }
        return bo;
    }
    /**
     * 手机号是否注册
     *
     * @param mobile
     * @return
     */
    @Transactional
    public int isMobileRegister(String mobile) {
        Doctor doc = doctorDao.findByMobile(mobile);
        if (doc != null) {
            return 1;
        } else {
            return 0;
        }
    }
    /**
     *  判断实名软证书是否已申请
     */
    public boolean judgeRealNameSoftCertIsApplied(String doctorCode) throws Exception{
        Doctor doctor = findDoctorByCode(doctorCode);
        String strUserIdcardNum = doctor.getIdcard();
        String data ="";
        String url = jwUrl+"/third/prescription/IsApplied";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strUserIdcardNum",strUserIdcardNum));
        params.add(new BasicNameValuePair("doctorCode",doctorCode));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200) {
                data = responseObject.getString("data");
                if("0".equals(data)){
                    return true;
                }
            }
        }else {
            throw new Exception("null response.");
        }
        return false;
    }
    /**
     * 获取线上CA是否认证过
     */
    public JSONObject isAuthentication(String doctorCode) throws Exception{
        Doctor doctor = findDoctorByCode(doctorCode);
//        String strUserIdcardNum = doctor.getIdcard();
        Boolean isSuccess = true;
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(doctor.getIscertified()==1){
            long certifiedOvertime = doctor.getCertifiedOvertime()!=null?doctor.getCertifiedOvertime().getTime():0;
            if(certifiedOvertime>System.currentTimeMillis()){
                //1、线上未认证,有证书,并有效,2、线上未认证,有证书,已过期,3、线上未认证,无证书,4、线上已认证,并有效
                jsonObject.put("type",4);
                String data = simpleDateFormat.format(doctor.getCertifiedOvertime());
                jsonObject.put("time",data);
            }else{
                jsonObject = getCAPastDue(doctorCode,jsonObject);
            }
        }else{
            boolean j = judgeRealNameSoftCertIsApplied(doctorCode);
            if(j){
                jsonObject = getCAPastDue(doctorCode,jsonObject);
            }else{
                jsonObject.put("type",3);
            }
        }
        return jsonObject;
    }
    /**
     * 获取CA证书过期时间
     */
    @Transactional
    public JSONObject getCAPastDue(String doctorCode,JSONObject jsonObject)  throws Exception{
        Doctor doctor = findDoctorByCode(doctorCode);
        String strUserIdcardNum = doctor.getIdcard();
        String data ="";
//        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = jwUrl+"/third/prescription/GetRealNameSoftCertExpiredDatetime";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strUserIdcardNum",strUserIdcardNum));
        params.add(new BasicNameValuePair("doctorCode",doctorCode));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200) {
                data = responseObject.getString("data");
                //1、线上未认证,有证书,并有效,2、线上未认证,有证书,已过期,3、线上未认证,无证书,4、线上已认证,并有效
                if(StringUtils.isNotEmpty(data)){
                    Date CertifiedOvertime = simpleDateFormat.parse(data);
                    doctor.setCertifiedOvertime(CertifiedOvertime);
                    doctorDao.save(doctor);
                    long times = CertifiedOvertime.getTime();
                    if(System.currentTimeMillis()<=times){
                        jsonObject.put("type",1);
                    }else{
                        jsonObject.put("type",2);
                    }
                }else{
//                        jsonObject.put("type",3);
                    throw new Exception("null data.");
                }
            } else {
                jsonObject.put("type",3);
            }
        }else {
            throw new Exception("null response.");
        }
        jsonObject.put("time",data);
        return jsonObject;
    }
    /**
     * 修改实名软证书调用保护口令
     */
    public boolean updateAuthenticationPassword(String strUserIdcardNum,String strOldCalledPasswd,String strNewCalledPasswd,String doctorCode) throws Exception{
        String url = jwUrl+"/third/prescription/ModifyRealNameSoftCertCalledPasswd";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strUserIdcardNum",strUserIdcardNum));
        params.add(new BasicNameValuePair("strOldCalledPasswd",strOldCalledPasswd));
        params.add(new BasicNameValuePair("strNewCalledPasswd",strNewCalledPasswd));
        params.add(new BasicNameValuePair("doctorCode",doctorCode));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            String msg = responseObject.getString("msg");
            if (status == 200) {
                String data = responseObject.getString("data");
                if("0".equals(data)){
                    Doctor doctor = findDoctorByCode(doctorCode);
                    doctor.setCheckPassword(strNewCalledPasswd);//保存密码,以便忘记密码时候使用
                    doctor.setIscertified(1);//说明已经(线上认证,已修改密码)
                    doctorDao.save(doctor);
                    return true;
                }
            }else{
                String error = msg.split(":")[2];
                throw new Exception(error);
            }
        }else{
            throw new Exception("null response.");
        }
        return false;
    }
    /**
     * 请求 实名软证书并进行数字签名
     * @param strUserIdcardNum
     * @param strRealNameSoftCertCalledPasswd
     * @param strOriginalData
     * @return
     * @throws Exception
     */
    @Transactional
    public JSONObject requestRealNameSoftCertAndSign(String strUserIdcardNum,String strRealNameSoftCertCalledPasswd,String strOriginalData,String prescriptionCode) throws Exception{
        String url = jwUrl+"/third/prescription/RequestRealNameSoftCertAndSign";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strUserIdcardNum",strUserIdcardNum));
        params.add(new BasicNameValuePair("strRealNameSoftCertCalledPasswd",strRealNameSoftCertCalledPasswd));
        String originalDataAbstract = MD5.GetMD5Code(strOriginalData);
        params.add(new BasicNameValuePair("strOriginalData",originalDataAbstract));
        params.add(new BasicNameValuePair("prescriptionCode",prescriptionCode));
//        params.add(new BasicNameValuePair("srcBusinessStreamNO",srcBusinessStreamNO));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            String msg = responseObject.getString("msg");
            if (status == 200) {
                String data = responseObject.getString("data");
                if (StringUtils.isEmpty(data)) {
                    throw new Exception("null data");
                }else{
                    String[] str = data.split("\\|\\|");
//                    String strSignData = str[0];
//                    String strCertData = str[1];
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("strSignData",str[0]);
                    jsonObject.put("strCertData",str[1]);
                    jsonObject.put("srcBusinessStreamNO",str[2]);
                    Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
                    prescription.setCaMessage(str[0]);
                    prescription.setCaCertData(str[1]);
                    prescription.setDigitalSignNo(str[2]);
                    prescription.setStrOriginalData(strOriginalData);
                    prescription.setOriginalDataAbstract(originalDataAbstract);
                    prescriptionDao.save(prescription);
//                    String srcBusinessStreamNO = str[2];//CA 数字签名唯一流水号
//                    return verifySignOnMultiServer(str[0],str[1],strOriginalData);
                    return jsonObject;
                }
            }else{
                String error = msg.split("\\|\\|")[0].split(":")[2];
                throw new Exception(error);
            }
        }else{
            throw new Exception("null response.");
        }
    }
    //验证签名( ( 带多服务器负载均衡) )
    public boolean verifySignOnMultiServer(String strSignData,String strCertData,String strOriginalData,String prescriptionCode) throws Exception{
        String url = jwUrl+"/third/prescription/VerifySignOnMultiServer";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSignData",strSignData));
        params.add(new BasicNameValuePair("strCertData",strCertData));
        params.add(new BasicNameValuePair("strOriginalData",MD5.GetMD5Code(strOriginalData)));
        params.add(new BasicNameValuePair("prescriptionCode",prescriptionCode));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            String msg = responseObject.getString("msg");
            if (status == 200) {
                String data = responseObject.getString("data");
                if("0".equals(data)){
                    return true;
                }
            }else{
                throw new Exception(responseObject.getString("msg"));
            }
        }else{
            throw new Exception("null response.");
        }
        return false;
    }
    //校验医师输入的CA证书是否正确
    public boolean  checkCertificate(String doctorCode,String certificateNum){
        int count = doctorDao.checkCertificate(doctorCode,certificateNum);
        if(count>0){
            return true;
        }
        return false;
    }
    @Transactional
    public boolean cancelAuthentication(String doctorCode) throws Exception{
        Doctor doctor = doctorDao.findByCode(doctorCode);
        boolean b = updateAuthenticationPassword(doctor.getIdcard(),doctor.getCheckPassword(),"11111111",doctorCode);
        if(b){
            doctor.setCheckPassword("");
            doctor.setIscertified(0);
            doctor.setCertifiedOvertime(null);
            doctorDao.save(doctor);
        }
        return b;
    }
}

+ 160 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/consult/ConsultService.java

@ -0,0 +1,160 @@
package com.yihu.wlyy.service.app.consult;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.consult.*;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.ImUtill;
import com.yihu.wlyy.util.SendPatientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
@Component
@Transactional
public class ConsultService extends BaseService {
	@Autowired
	public PatientDao patientDao;
	@Autowired
	public DoctorDao doctorDao;
	@Autowired
	public ConsultDao consultDao;
	@Autowired
	public ConsultMoViDao consultMoViDao;
	@Autowired
	public ConsultTeamDao consultTeamDao;
	@Autowired
	public ConsultPublicDao consultPublicDao;
	@Autowired
	public ConsultPublicReplyDao consultPublicReplyDao;
	@Autowired
	public ConsultCommunicationDao consultCommunicationDao;
	@Autowired
	public ConsultCommunicationReplyDao consultCommunicationReplyDao;
	@Autowired
	private SignFamilyDao signFamilyDao;
	@Autowired
	private PatientService patientService;
	@Autowired
	private ImUtill imUtill;
	/**
	 * 添加一条咨询记录
	 * @param patient 患者信息
	 * @param title 咨询标题
	 * @param type 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
	 * @return
	 */
	public Consult addConsult(String patient, String title, String symptoms, String images, int type) {
		Consult consult = new Consult();
		consult.setCode(getCode());
		consult.setCzrq(new Date());
		consult.setDel("1");
		consult.setPatient(patient);
		consult.setTitle(title);
		consult.setSymptoms(symptoms);
		consult.setImages(images);
		consult.setType(type);
		SignFamily signFamily = signFamilyDao.findByPatient(patient);
		if(signFamily!=null){
			consult.setSignCode(signFamily.getCode());
		}
		return consultDao.save(consult);
	}
	/**
	 * 查询患者所有的咨询记录
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<Object> findConsultRecordByPatient(String patient, long id, int pagesize,String title) {
		if (id < 0) {
			id = 0;
		}
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		if(!StringUtils.isEmpty(title)){
			title="%"+title+"%";
			if (id > 0) {
				return consultDao.findByPatient(patient,title, id, pageRequest);
			} else {
				return consultDao.findByPatient(patient,title, pageRequest);
			}
		}else{
			if (id > 0) {
				return consultDao.findByPatient(patient, id, pageRequest);
			} else {
				return consultDao.findByPatient(patient, pageRequest);
			}
		}
	}
	/**
	 * 按类型查找居民的咨询记录
	 * @return
     */
	public Page<Object> findConsultRecordByType(String patient,long id,int pagesize,Integer type,String title){
		if (id < 0) {
			id = 0;
		}
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest((int)id, pagesize, sort);
		if(!StringUtils.isEmpty(title)){
			title="%"+title+"%";
			return consultDao.findByPatientAndType(patient,title,type, pageRequest);
		}else{
			return consultDao.findByPatientAndType(patient,type, pageRequest);
		}
	}
	public Consult findOneConsult(String consult) {
		return consultDao.findByCode(consult);
	}
	public void sendMucMessageBySingnType(String doctor,String doctorName,String patient,String  content,String contentType,String title){
		Doctor d = doctorDao.findByCode(doctor);
		SignFamily signFamily = signFamilyDao.findByPatient(patient);//当前签约团队
		if(signFamily==null){
			List<SignFamily> signFamilys = signFamilyDao.findLastJySignByPatient(patient,2);//获取旧的家庭签约关系
			if(signFamilys!=null&&signFamilys.size()>0){
				signFamily = signFamilys.get(0);
			}
		}
		if(signFamily!=null){
			new SendPatientUtil(doctor,doctorName,patient, contentType, content,title,signFamily.getType()+"",signFamily.getTeamCode(),imUtill).start();
		}else {
			throw new RuntimeException("无法找到签约关系!");
		}
	}
}

+ 1388 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java

@ -0,0 +1,1388 @@
package com.yihu.wlyy.service.app.consult;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamDoctor;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroup;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.followup.Followup;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.prescription.*;
import com.yihu.wlyy.entity.zydict.ZyIvPhysicDict;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.repository.consult.ConsultTeamLogDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.followup.FollowUpDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.prescription.*;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import org.springside.modules.utils.Clock;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 網絡諮詢类.
 * test
 *
 * @author George
 */
// Spring Service Bean的标识.
@Component
@Transactional(rollbackFor = Exception.class)
public class ConsultTeamService extends ConsultService {
    private Clock clock = Clock.DEFAULT;
    // 咨询详细记录
    @Autowired
    private ConsultTeamLogDao consultTeamLogDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorPatientDao doctorPatientDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private DoctorTeamMemberDao doctorTeamDoctor;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientFamilyMemberDao familyMemberDao;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private com.yihu.wlyy.service.common.account.DoctorService doctorService;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private ImUtill ImUtill;
    @Autowired
    private HttpClientUtil HttpClientUtil;
    @Autowired
    private PrescriptionReviewedDao prescriptionReviewedDao;
    @Autowired
    private WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    private PatientService patientService;
    @Autowired
    private FollowUpDao followupDao;
    //健康问题 高血压
    private static final String gxy = "HP0093";
    //健康问题 糖尿病
    private static final String tnb ="HP0047";
    Map<Integer, String> relations = new HashMap<>();
    @Value("${im.im_list_get}")
    private String im_list_get;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionExplainDao prescriptionExplainDao;
    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
    }
    /**
     * 处方判断
     * @param patient
     * @return
     * @throws Exception
     */
    public JSONObject isPrescriptConsult(String patient) throws Exception{
        JSONObject json = new JSONObject();
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if(signFamily==null){
            json.put("msg","您还未签约,不能发起续方咨询");
            return json;
        }
        //点击后判断,如果用户当前存在可申请续方的处方记录,则进入续方申请流程,若不存在可续方记录,alert“当前没有可以申请续方的处方记录”
        // 智业接口没有返回列表,是单条 所以先不处理
//        int num = 0;
//        Patient p = patientDao.findByCode(patient);
//        String rp= jwPrescriptionService.getRecipeList(p.getSsc(),null,null,null);
//        com.alibaba.fastjson.JSONArray pres =presModeAdapter.modeToPrescription(rp);
//        Iterator iterator = pres.iterator();
//        while (iterator.hasNext()){
//            com.alibaba.fastjson.JSONObject r = ( com.alibaba.fastjson.JSONObject)iterator.next();
//            com.alibaba.fastjson.JSONArray des = r.getJSONArray("prescriptionDt");
//            for(int i=0 ;i<des.size();i++){
//                PrescriptionDiagnosis ds = des.getObject(i,PrescriptionDiagnosis.class);
//                if(gxy.equals(ds.getHealthProblem())||tnb.equals(ds.getHealthProblem())){
//                    //为糖尿病高血压
//                    num++;
//                    break;
//                }
//            }
//        }
//        if(num==0){
//            json.put("msg","当前没有可以申请续方的处方记录");
//            return json;
//        }
        //续方说明
        List<PrescriptionExplain> list = prescriptionExplainDao.findList();
        JSONArray ja = new JSONArray();
        for (PrescriptionExplain explain:list){
            ja.put(explain.getContent());
        }
        Doctor doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
        json.put("doctor",doctor.getCode());
        json.put("doctorName",doctor.getName());
        json.put("adminTeamId",signFamily.getAdminTeamId());
        json.put("hospital",doctor.getHospital());
        json.put("hospitalName",doctor.getHospitalName());
        json.put("prescriptionExplain",ja);
        return json;
    }
    /**
     * 查询患者是否还有未结束的三师咨询
     *
     * @param patient
     * @return
     */
    public boolean exist(String patient, Integer type) throws Exception {
        DoctorTeamMember member = null;
        String memberCode=null;
        // 咨询三师
        if (type == 1) {
            // 查询三师签约信息
            SignFamily sc = signFamilyDao.findBySanshiPatientYes(patient);
            if (sc == null) {
                throw new Exception("不存在三师签约");
            }
            // 设置健康管理师,三师咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findBySanshiParientCode(patient);
            //得到团队的健康管理师
            member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 3);
            if (member == null) {
                member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 2);
            }
            memberCode= member.getCode();
        } else if (type == 2) {
            // 咨询家庭医生
            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
            if (sf == null) {
                throw new Exception("不存在家庭签约");
            }
            if (StringUtils.isEmpty(sf.getDoctorHealth())){
                memberCode = sf.getDoctor();
            }else {
                memberCode = sf.getDoctorHealth();
            }
            // 设置健康管理师,家庭医生咨询默认给健康管理师处理
            //查找病人所在的团队
//            DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(patient);
//            //得到团队的健康管理师
//            member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 3);
//
//            if (member == null) {
//                member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 2);
//            }
        }
//        if (member == null) {
//            throw new Exception("找不到签约服务团队医生");
//        }
        int count = consultTeamDao.countByPatient(patient, memberCode);
        return count > 0;
    }
    /**
     * 查詢醫生網絡諮詢列表
     *
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的 5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
     * @param id
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    public Page<ConsultTeam> findByDoctor(String uid, int type, long id, int pagesize, String patient, String title) {
        if (id < 0) {
            id = 0;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        switch (type) {
            case 0:
                // 全部
                return findByDoctorType0(uid, id, patient, pagesize);
            case 1:
                // 咨询我的
                return findByDoctorType1(uid, type, id, pagesize);
            case 2:
                // 我感兴趣的
                return findByDoctorType2(uid, type, id, pagesize);
            case 3:
                // 我回复的
                return findByDoctorType3(uid, id, pagesize);
            case 4:
                // 已完成的
                return findByDoctorType4(uid, id, pagesize);
            case 5:
                // 5 名医咨询 全部
                return findByDoctorType5(uid, id, pagesize, title);
            case 6:
                //6 名医咨询 进行中
                return findByDoctorType6(uid, 0, id, pagesize, title);
            case 7:
                //7 名医咨询 已结束
                return findByDoctorType6(uid, 1, id, pagesize, title);
            case 8:
                return findByDoctorType8(uid, id, pagesize, title);
            case 9:
                return findByDoctorType9(uid, id, pagesize);
            case 10:
                //我咨询的
                return findByDoctorType10(uid, id, pagesize, title);
            case 11:
                //我咨询的 进行中
                return findByDoctorType11(uid, 0, id, pagesize, title);
            case 12:
                //我咨询的 已结束中
                return findByDoctorType11(uid, 1, id, pagesize, title);
        }
        return null;
    }
    private Page<ConsultTeam> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorType10(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorAllList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorAllList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorAllList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorAllList(uid, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorTypeSix(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorIngList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorIngList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorIngNoTitleList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorIngNoTitleList(uid, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorType8(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        sort.and(new Sort(Direction.DESC, "czrq"));
        sort.and(new Sort(Direction.DESC, "doctorRead"));
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorType5(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorAllList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorAllList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorAllList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorAllList(uid, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorType6(String uid, int type, long id, int pagesize, String title) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorDoingList(uid, id, title, type, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorDoingList(uid, title, type, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorDoingList(uid, id, type, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorDoingList(uid, type, pageRequest);
            }
        }
    }
    /**
     * 根据状态获取三师家庭咨询
     *
     * @param doctor
     * @param status   0未处理或未回复 1已回复 2已结束
     * @param id
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findConsultByDoctor(String doctor, int status, long id, int pagesize) {
        if (id < 0) {
            id = 0;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if (status == 0) {
            return findConsultByDoctorWcl(doctor, id, pagesize);
        } else if (status == 1) {
            return findConsultByDoctorIng(doctor, id, pagesize);
        } else {
            return findByDoctorType4(doctor, id, pagesize);
        }
    }
    /**
     * 获取三师家庭未处理咨询
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    private Page<ConsultTeam> findConsultByDoctorWcl(String uid, long id, int pagesize) {
        Sort sort = new Sort(Direction.DESC, "id");
        sort.and(new Sort(Direction.DESC, "czrq"));
        sort.and(new Sort(Direction.DESC, "doctorRead"));
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, pageRequest);
        }
    }
    /**
     * 获取三师家庭已回复咨询
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    private Page<ConsultTeam> findConsultByDoctorIng(String uid, long id, int pagesize) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorIngNoTitleList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorIngNoTitleList(uid, pageRequest);
        }
    }
    /**
     * 查询全部咨询记录
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType0(String uid, long id, String patient, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isEmpty(patient)) {
            if (id > 0) {
                return consultTeamDao.findDoctorList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findDoctorList(uid, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findDoctorPatientList(uid, patient, id, pageRequest);
            } else {
                return consultTeamDao.findDoctorPatientList(uid, patient, pageRequest);
            }
        }
    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid      医生标识
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType1(String uid, int type, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorPointList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorPointList(uid, pageRequest);
        }
    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid      医生标识
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType9(String uid, long id, int pagesize) {
        return null;
    }
    /**
     * 公共三师咨询列表查询
     *
     * @param uid      医生标识
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType2(String uid, int type, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 未指定医生
        filters.put("type", new SearchFilter("type", Operator.EQ, 0));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 未回复
        filters.put("status", new SearchFilter("status", Operator.EQ, 0));
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<ConsultTeam> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeam.class);
        return consultTeamDao.findAll(spec, pageRequest);
    }
    /**
     * 医生参与过的未结束的三师咨询列表查询
     *
     * @param uid
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType3(String uid, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorJoinList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorJoinList(uid, pageRequest);
        }
    }
    /**
     * 医生参与过的已结束的三师咨询列表查询
     *
     * @param uid
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType4(String uid, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorFinishList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorFinishList(uid, pageRequest);
        }
    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    public Page<ConsultTeamLog> findLogByConsult(String consult, long id, int pagesize) {
        if (id < 0) {
            id = 0;
        }
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("consult", new SearchFilter("consult", Operator.EQ, consult));
        if (id > 0) {
            if (pagesize > 0)
                filters.put("id", new SearchFilter("id", Operator.LT, id));
            else
                filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<ConsultTeamLog> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeamLog.class);
        if (pagesize <= 0) {
            Page<ConsultTeamLog> p = new PageImpl<>(consultTeamLogDao.findAll(spec));
            return p;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        return consultTeamLogDao.findAll(spec, pageRequest);
    }
    /**
     * 查询居民咨询记录
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pageSize
     * @return
     */
    public JSONArray findByPatientAndTeam(String patient, Long teamCode, int page, int pageSize) {
        PageRequest pageRequest = new PageRequest(page, pageSize);
        Patient p = patientDao.findByCode(patient);
        Page<Object> result = consultDao.findByPatientAndTeam(patient, teamCode, pageRequest);
        JSONArray array = new JSONArray();
        for (Object obj : result) {
            JSONObject consult = new JSONObject();
            Object[] objArr = (Object[]) obj;
            consult.put("id", objArr[0]);
            consult.put("code", objArr[2]);
            consult.put("type", objArr[1]);
            consult.put("title", objArr[3]);
            consult.put("symptoms", objArr[4]);
            consult.put("czrq", objArr[5]);
            consult.put("status", objArr[6]);
            consult.put("adminTeamCode", objArr[7]);
            consult.put("team", objArr[8]);
            consult.put("patient", patient);
            consult.put("patientName", p.getName());
            consult.put("patientPhoto", p.getPhoto());
            array.put(consult);
        }
        return array;
    }
    /**
     * 添加咨询记录
     *
     * @param log  日志对象
     * @param type 类型,0问,1回复,2追问,3评价
     * @return
     */
    public ConsultTeamLog reply(ConsultTeamLog log, String patient, String teamOrDoctor, int type) {
        log.setCzrq(clock.getCurrentDate());
        // 保存咨询记录
        ConsultTeamLog temp = consultTeamLogDao.save(log);
        if (temp != null) {
            // 发送消息
            if (type == 1) {
                // 医生回复,给患者发消息
                // sendMessage(patient, teamOrDoctor, "三师咨询", log.getDoctorName() + "回复了您的咨询", log.getConsult(), 214, 1, 0, 0);
                // 患者未读数量+1
                consultTeamDao.increasePatientRead(log.getConsult());
                // 医生有回复
                consultTeamDoctorDao.updateReply(log.getConsult(), teamOrDoctor);
                //shenzaixin v1.2.0 推送消息给患者
                //HttpUtil.sendWeixinWebsocketMsg(patient, "{busiType:'qianyuezixun',msgid:'" + log.getId() + "'}");
            } else if (type == 0 || type == 2) {
                // 查询相关联的医生
                Iterable<ConsultTeamDoctor> iterable = consultTeamDoctorDao.findByConsult(log.getConsult());
                if (iterable != null && iterable.iterator() != null && iterable.iterator().hasNext()) {
                    Iterator<ConsultTeamDoctor> iterator = iterable.iterator();
                    while (iterator.hasNext()) {
                        // 患者提问或追问,给医生发消息
                        ConsultTeamDoctor ctd = iterator.next();
                        if (ctd == null) {
                            continue;
                        }
                        // 推送消息给医生
                        pushMsgTask.put(ctd.getTo(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.D_CT_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.您有新的消息.name(), temp.getConsult());
                    }
                }
                // 医生未读数量+1
                consultTeamDao.increaseDoctorRead(log.getConsult());
            }
        }
        return temp;
    }
    /**
     * 保存审核提醒消息
     * @param prescription
     */
    public void addCheckMessage(Prescription prescription,String sessionId,Patient p){
        Message message = new Message();
        message.setCzrq(new Date());
        message.setCreateTime(new Date());
        message.setRead(1);//设置未读
        message.setOver("1");
        message.setSenderPhoto(p.getPhoto());
        message.setReceiver(prescription.getDoctor());
        message.setSender(prescription.getPatient());
        message.setCode(getCode());
        message.setSenderName(prescription.getPatientName());
        message.setTitle(prescription.getPatientName()+"申请续方");
        message.setContent("您有一条新的续方申请待处理!");
        message.setType(6);//续方咨询待审核提醒
        message.setReadonly(1);//是否只读消息
        message.setDel("1");
        message.setRelationCode(prescription.getConsult());
        message.setPrescriptionStatus("0");
        message.setSessionId(sessionId);
        message.setSessionName(prescription.getPatientName());
        messageDao.save(message);
    }
    public String getZyCommonDictName(String code){
        try{
            String sql  ="SELECT t.name FROM zy_common_dict t WHERE t.code=? AND t.dict_name='IV_RECIPE_FREQUENCY_DICT'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,new Object[]{code});
            if(list!=null&&list.size()>0){
                return (String)(list.get(0).get("name"));
            }
            return "";
        }catch (Exception e){
            return "";
        }
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param to
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendIM(String from, String to, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/pm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = HttpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param groupCode
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendGroupIM(String from, String groupCode, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/gm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("group", groupCode));
        params.add(new BasicNameValuePair("groupType", "1"));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = HttpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 查询咨询列表
     *
     * @param patientCode 患者标志
     * @param status      咨询状态(0未结束,1已结束,-1 已取消)
     * @param pageSize    页数
     * @return
     */
    public Page<ConsultTeam> findByPatient(String patientCode, int status, long id, int pageSize) {
        if (id < 0) {
            id = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
        Page<ConsultTeam> list = null;
        switch (status) {
            case 0:
                // 未结束
                if (id > 0) {
                    list = consultTeamDao.findNotFinishedBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findNotFinishedBypatient(patientCode, pageRequest);
                }
                break;
            case 1:
                // 已结束
                if (id > 0) {
                    list = consultTeamDao.findFinishedBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findFinishedBypatient(patientCode, pageRequest);
                }
                break;
            case -1:
                // 已取消
                if (id > 0) {
                    list = consultTeamDao.findCancelBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findCancelBypatient(patientCode, pageRequest);
                }
                break;
        }
        return list;
    }
    /**
     * 设置咨询已读
     *
     * @param consult
     * @return
     */
    @Transactional
    public int readMessage(String consult) {
        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
        consultTeam.setDoctorRead(0);
        return 1;
    }
    /**
     * 取消三师咨询
     *
     * @param consult
     * @return
     */
    public int cancel(String consult) {
        return consultTeamDao.cancel(consult);
    }
    public ConsultTeam findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }
    /**
     * 三师咨询转接医生
     *
     * @param from    转出医生标识
     * @param to      转入医生标识
     * @param consult 三师咨询标识
     * @return
     */
    public void transfer(String from, String to, String consult) {
        // 检查是否存在
        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
            ConsultTeam ct = consultTeamDao.findByConsult(consult);
            int count = consultTeamLogDao.countByConsult(consult);
            // 设置未读消息数
            ct.setDoctorRead(count);
            consultTeamDao.save(ct);
            // 查询医生信息
            Doctor d = doctorDao.findByCode(from);
            // 再保存
            ConsultTeamDoctor cd = new ConsultTeamDoctor();
            cd.setConsult(consult);
            cd.setDel("1");
            cd.setCzrq(new Date());
            cd.setFrom(d.getCode());
            cd.setFromName(d.getName());
            cd.setTo(to);
            consultTeamDoctorDao.save(cd);
        }
    }
    /**
     * 查询患者视频和三师咨询记录
     *
     * @param patient  患者标识
     * @param id
     * @param pagesize
     * @return
     */
    public Page<Consult> findConsultRecordByPatientType(String patient, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
        filters.put("type", new SearchFilter("type", Operator.LT, 3));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<Consult> spec = DynamicSpecifications.bySearchFilter(filters.values(), Consult.class);
        return consultDao.findAll(spec, pageRequest);
    }
    /**
     * 清空医生未读数量
     *
     * @param consult
     */
    public void clearDoctorRead(String consult) {
        consultTeamDao.clearDoctorRead(consult);
    }
    /**
     * 清空患者未读数量
     *
     * @param consult
     */
    public void clearPatientRead(String consult) {
        consultTeamDao.clearPatientRead(consult);
    }
    /**
     * 查询医生的咨询统计
     *
     * @param doctorCode
     * @return
     */
    public Map<String, Long> getAllCount(String doctorCode) {
        Map<String, Long> result = new HashMap<>();
        //根据医生code查询总咨询数
        long allCount = consultTeamDoctorDao.getAllCountByDoctorCode(doctorCode);
        //根据医生code查询今日咨询数
        long todayCount = consultTeamDoctorDao.getTodayCountByDoctorCode(doctorCode);
        result.put("all", allCount);
        result.put("today", todayCount);
        return result;
    }
    /**
     * 查找未完成咨询
     *
     * @param patient
     * @return
     */
    public List<ConsultTeam> getUnfinishedConsult(String patient) {
        return consultTeamDao.findUnfinishedConsult(patient);
    }
    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public List<ConsultTeam> getUnfinishedConsult(String patient, String doctor) {
        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
    }
    /**
     * 查询患者全部的咨询数目
     *
     * @param patientCode
     * @return
     */
    public Integer findByDoctorSize(String patientCode, String doctorCode) {
        return consultDao.findByPatient(patientCode, doctorCode);
    }
    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();
        for (int i = 0; i < consults.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(consults));
        paramList.addAll(Arrays.asList(consults));
        String sqlgp = "select DISTINCT consult,to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlgpm = "select DISTINCT to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.consult,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.to_doctor = b.qkdoctor_code group by a.consult ";
        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }
    public ConsultTeamLog oneLog(Long logId) {
        return consultTeamLogDao.findOne(logId);
    }
    public boolean isExistConsult(String uid, String doctor) {
        int consultTeam = consultTeamDao.countByPatient(uid, doctor);
        if (consultTeam > 0) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 进入咨询
     * @param consult
     * @param patient
     * @param agent
     * @return
     */
    public int intoTopic(String consult,String patient,String agent) throws Exception{
        ConsultTeam ct = consultTeamDao.findByConsult(consult);
        if(ct.getStatus()!=0){
            return -1;
        }
        String content = "进入了咨询";
        Patient p = patientDao.findByCode(patient);
        String intoUserName = p.getName();
        if(patient.equals(agent)){
            content = intoUserName+content;
        }else {
            PatientFamilyMember familyMember = familyMemberDao.findByPatientAndFamilyMember(patient,agent);
            Patient member = patientDao.findByCode(agent);
            content = member.getName() + "("+relations.get(familyMember.getFamilyRelation())+")"+content;
        }
        ImUtill.sendIntoTopicIM(ct.getPatient(),ct.getPatient(),ct.getConsult(),content,agent,intoUserName);
        return 0;
    }
    /**
     * 根据健康管理师和患者 找到正在进行中的咨询
     *
     * @param patientCode
     * @param doctor
     */
    public ConsultTeam getConsultByPatientAndDoctor(String patientCode, String doctor) {
        ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patientCode, doctor, 2);
        return consultTeam;
    }
    public void transfers(String uid, String doctor, String consult) {
        String[] doctors = doctor.split(",");
        for (int i = 0; i < doctors.length; i++) {
            transfer(uid, doctors[i], consult);
        }
    }
    public String produceConsultAdminTeamCode() {
        StringBuffer sf = new StringBuffer();
        StringBuffer sf1 = new StringBuffer();
        Long size = 0L;
        //找出家庭签约中团队code是空的
        List<ConsultTeam> consultTeams = consultTeamDao.findByTypeAndAdminTeamIdIsNull(2);
        sf.append("家庭签约咨询中团队code是空的数据数:" + consultTeams.size());
        for (ConsultTeam consultTeam : consultTeams) {
            //得到签约中的全科医生的团队
            SignFamily signfamily = signFamilyDao.findByjiatingPatient(consultTeam.getPatient());
            if (signfamily != null) {
                if (signfamily.getAdminTeamId() != null && signfamily.getAdminTeamId() > 0) {
                    consultTeam.setAdminTeamId(signfamily.getAdminTeamId());
                    size++;
                }
            } else {
                sf1.append(",找不到医生所属的团队,家庭签约咨询的Id:" + consultTeam.getId());
            }
        }
        sf.append(",填充团队的签约数据数:" + size);
        sf.append(sf1);
        return sf.toString();
    }
    public void save(ConsultTeam consult) {
        consultTeamDao.save(consult);
    }
    public ConsultTeam findByConsultCode(String consultCode) {
        return consultTeamDao.findByConsult(consultCode);
    }
    /**
     * @param consultCode
     * @return
     */
    public List<ConsultTeamLog> getConsultLog(String consultCode) {
        return consultTeamLogDao.getConsultLogByConsultLog(consultCode);
    }
    /**
     * @param ct
     * @param uid
     * @throws Exception
     */
    public void sendForHelpMsg(ConsultTeam ct, String uid, String oldConsultCode) throws Exception {
        ct.setPatient(uid);
        //推送给IM文字消息
        if (StringUtils.isNotEmpty(oldConsultCode)) {
            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
            if (oldConsult != null) {
                sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
                //推送给IM图片
                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
                    String[] images = oldConsult.getImages().split(",");
                    for (String image : images) {
                        if (StringUtils.isNoneEmpty(image)) {
                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                        }
                    }
                }
            }
        }
        sendIM(ct.getPatient(), ct.getDoctor(), "6", "咨询问题:" + ct.getSymptoms());
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                }
            }
        }
    }
    /**
     * @param uid
     * @throws Exception
     */
    public List<ConsultTeam> hasUnfinished(String doctorCode, String uid) throws Exception {
        return consultTeamDao.findUnfinishedConsult(uid, doctorCode);
    }
    /**
     * 判断两医生是否在同一团队内
     *
     * @param docCode1
     * @param docCode2
     * @return
     */
    public boolean isCommonTeam(String docCode1, String docCode2) {
        String sqlQuSum =
                "SELECT c.team_id FROM " +
                        "(SELECT a.* FROM wlyy_admin_team_member a where a.doctor_code='" + docCode1 + "' ) c " +
                        "LEFT JOIN " +
                        "(SELECT b.* FROM wlyy_admin_team_member b where b.doctor_code='" + docCode2 + "' ) d " +
                        "on c.team_id=d.team_id " +
                        "WHERE d.team_id IS NOT NULL";
        List ls = jdbcTemplate.queryForList(sqlQuSum);
        return ls != null && ls.size() > 0;
    }
    /**
     * 通过team获取医生code
     *
     * @param consult 关联的上一个咨询
     * @return
     */
    public List findByTeam(String consult) {
        return consultTeamDao.findByTeamAndType(consult, 10);
    }
    /**
     * 全科医生求助专科医生(同团队)
     *
     * @param ct
     * @param uid
     * @param oldConsultCode
     * @param isSend         是否转发患者咨询内容
     */
    public void addSeekHelpTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) {
        ct.setPatient(uid);
        //推送给IM文字消息
        JSONObject participants = new JSONObject();
        participants.put(ct.getPatient(), 0);
        participants.put(ct.getDoctor(), 0);
        Doctor doctor = doctorService.findDoctorByCode(uid);
        JSONObject sessionJson = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, doctor.getName() + "发起求助!", "");
        if (sessionJson.getInt("status") == -1) {
            throw new RuntimeException(sessionJson.getString("message"));
        }
        JSONObject session = sessionJson.getJSONObject("data");
        if (StringUtils.isNotEmpty(oldConsultCode)) {
            ct.setTeam(oldConsultCode);
            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
            if (oldConsult != null && isSend == 1) {
                ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "居民问题:" + oldConsult.getSymptoms(), "1");
                //推送给IM图片
                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
                    String[] images = oldConsult.getImages().split(",");
                    for (String image : images) {
                        if (StringUtils.isNoneEmpty(image)) {
                            ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
                        }
                    }
                }
            }
            Doctor doctorTemp = doctorDao.findByCode(ct.getDoctor());
            JSONObject qiuzuObj = new JSONObject();
            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
            qiuzuObj.put("patient", ct.getPatient());
            qiuzuObj.put("old_consult_code", oldConsultCode);
            qiuzuObj.put("doctor", ct.getDoctor());
            qiuzuObj.put("doctor_name", doctorTemp.getName());
            ImUtill.sendTopicIM(doctor.getCode(), doctor.getName(), oldConsultCode, "5", qiuzuObj.toString(),null);
        }
        ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "咨询问题:" + ct.getSymptoms(), "1");
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
                }
            }
        }
    }
    @Override
    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
        super.sendMucMessageBySingnType(doctor, doctorName, patient, content, contentType, title);
    }
    public void removeRenewPerson(JSONObject jsonObject,String uid){
        JSONArray j = jsonObject.getJSONArray("users");
        List<Integer> indexs =new ArrayList<>();
        if(j!=null&&j.length()>0){
            for(int i=0;i<j.length();i++){
                JSONObject doctor = (JSONObject) j.get(i);
                String code = (String)doctor.get("id");
                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+DateUtil.getSignYear()+"' AND t.patient ='"+uid+"' ";
                String SQL2 ="SELECT t.id FROM wlyy_sign_family t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+(DateUtil.getSignYear()-1)+"' AND t.patient ='"+uid+"' AND t.status>0 AND t.expenses_status ='1' ";
                List<Map<String,Object>> isExits = jdbcTemplate.queryForList(SQL);
                List<Map<String,Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
                if(isExitsSign==null){
                    if(isExits!=null&&isExits.size()>0){
                        indexs.add(i);
                    }
                }
            }
            if(indexs!=null&&indexs.size()>0){
                for(Integer index : indexs){
                    j.remove(index);
                }
            }
        }
    }
    public void removeRenewPerson(JSONArray j,String uid){
        List<Integer> indexs =new ArrayList<>();
        if(j!=null&&j.length()>0){
            for(int i=0;i<j.length();i++){
                JSONObject doctor = (JSONObject) j.get(i);
                String code = (String)doctor.get("id");
                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+DateUtil.getSignYear()+"' AND t.patient ='"+uid+"' ";
                String SQL2 ="SELECT t.id FROM wlyy_sign_family t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+(DateUtil.getSignYear()-1)+"' AND t.patient ='"+uid+"' AND t.status>0 AND t.expenses_status ='1' ";
                List<Map<String,Object>> isExits = jdbcTemplate.queryForList(SQL);
                List<Map<String,Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
                if(isExitsSign==null){
                    if(isExits!=null&&isExits.size()>0){
                        indexs.add(i);
                    }
                }
            }
            if(indexs!=null&&indexs.size()>0){
                for(Integer index : indexs){
                    j.remove(index);
                }
            }
        }
    }
    
    /**
     * 医生发送症状、体征及生活方式回复咨询
     * @param prescriptionCode
     * @param type
     */
    public void addPrescriptionFollowupContentConsult(String prescriptionCode, String type, String followupid) throws Exception {
        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
        JSONObject contentobj = new JSONObject();
        //医生发送的消息
        if("1".equals(type)){
            contentobj.put("text","请填写您近期身体异常症状问卷");
        }else{
            contentobj.put("text","请填写您近期体征及生活方式调查问卷");
        }
        contentobj.put("doctorremind","已向居民发送问卷填写请求,填写完成后您将收到消息提醒");
        contentobj.put("patientremind","填写完成并提交后,医生将可以查看您的问卷内容");
        contentobj.put("msgType",type);
        contentobj.put("isSendWxTemplate",true);//是否发送咨询回复的微信模板
        //医生发送Im消息
        ImUtill.sendTopicIM(prescription.getDoctor(), prescription.getDoctorName(), prescription.getConsult(), "17", contentobj.toString(), null);
//        contentobj.put("isSendWxTemplate",false);//是否发送咨询回复的微信模板
//        //居民发送Im消息
//        ImUtill.sendTopicIM(prescription.getPatient(), prescription.getPatientName(), prescription.getConsult(), "17", contentobj.toString(), null);
    }
    /**
     * 根据续方code获取咨询
     * @param prescriptionCode
     * @return
     */
    public ConsultTeam getConsultStatus(String prescriptionCode){
        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
        if(prescription!=null){
            return consultTeamDao.findByConsult(prescription.getConsult());
        }
        return null;
    }
}

+ 732 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java

@ -0,0 +1,732 @@
package com.yihu.wlyy.service.app.scheduling;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.schedule.DoctorFamousConsultTimesRemain;
import com.yihu.wlyy.entity.doctor.schedule.WlyyDoctorWorkTime;
import com.yihu.wlyy.entity.doctor.schedule.WlyyDoctorWorkWeek;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorWorkTimeDao;
import com.yihu.wlyy.repository.doctor.DoctorWorkWeekDao;
import com.yihu.wlyy.repository.doctor.FamousDoctorTimesRemainDao;
import com.yihu.wlyy.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生工作排班
 * <p>
 * Created by lyr on 2016/08/19.
 */
@Service
@Transactional
public class DoctorWorkTimeService extends BaseService {
    static Object obj = new Object();
    @Autowired
    private DoctorWorkTimeDao doctorWorkTimeDao;
    @Autowired
    private DoctorWorkWeekDao doctorWorkWeekDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private FamousDoctorTimesRemainDao timesRemainDao;
    @Transactional
    public void updateDoctorWorkTime(String doctorCode) {
        List<WlyyDoctorWorkTime> wlyyDoctorWorkTimess = doctorWorkTimeDao.findDoctorWorkTimes(doctorCode);
        if (wlyyDoctorWorkTimess != null && wlyyDoctorWorkTimess.size() > 0) {
            wlyyDoctorWorkTimess.stream().forEach( wt->{
                wt.setReceiveConsult("1");
            });
        }
    }
    /**
     * 查询医生工作时间列表
     *
     * @param doctor 医生标识
     * @return
     */
    public JSONObject findDoctorWorkTime(String doctor) throws Exception {
        JSONObject result = new JSONObject();
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("doctor not exist");
        }
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        List<WlyyDoctorWorkWeek> workWeekList = doctorWorkWeekDao.findDoctorWorkWeeks(doctor);
        result.put("workTime", workTime != null ? new JSONObject(workTime) : "");
        result.put("workWeeks", workWeekList != null ? new JSONArray(workWeekList) : "");
        JSONObject docJson = new JSONObject(doc);
        if (docJson.has("password")) {
            docJson.remove("password");
        }
        if (docJson.has("salt")) {
            docJson.remove("salt");
        }
        result.put("doctor", doc != null ? docJson : "");
        return result;
    }
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public JSONObject findDoctorWeekWorkTime(String doctor, String week) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        result.put("workTime", workTime != null ? new JSONObject(workTime) : "");
        result.put("workWeek", workWeek != null ? new JSONObject(workWeek) : "");
        return result;
    }
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public Map<String, Object> findDoctorWeekWork(String doctor, String week) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("doctor-worktime-error:doctor not exist");
        }
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        map.put("workTime", workTime);
        map.put("workWeek", workWeek);
        return map;
    }
    /**
     * 保存医生工作排班
     *
     * @param doctor         医生
     * @param workScheduling 排班配置
     * @return
     */
    public boolean saveDoctorWorkTime(String doctor, JSONObject workScheduling) throws Exception {
        JSONObject workTime = workScheduling.has("workTime") ? workScheduling.getJSONObject("workTime") : null;
        JSONArray workTWeeks = workScheduling.has("workWeeks") ? workScheduling.getJSONArray("workWeeks") : null;
        WlyyDoctorWorkTime doctorWorkTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        Doctor doc = doctorDao.findByCode(doctor);
        if (StringUtils.isEmpty(doctor) || doc == null) {
            throw new Exception("找不到对应医生!");
        }
        if (workTime == null) {
            throw new Exception("工作时间段不能为空!");
        }
        if (doctorWorkTime == null) {
            doctorWorkTime = new WlyyDoctorWorkTime();
            doctorWorkTime.setReceiveConsult("1");
            doctorWorkTime.setFamousConsultTimes(0);
        }
        // 医生
        doctorWorkTime.setDoctor(doctor);
        // 医生姓名
        doctorWorkTime.setDoctorName(doc.getName());
        // 上午开始时间
        doctorWorkTime.setMorningBegin(workTime.getString("morningBegin"));
        // 上午结束时间
        doctorWorkTime.setMorningEnd(workTime.getString("morningEnd"));
        // 下午开始时间
        doctorWorkTime.setAfternoonBegin(workTime.getString("afternoonBegin"));
        // 下午结束时间
        doctorWorkTime.setAfternoonEnd(workTime.getString("afternoonEnd"));
        // 晚上开始时间
        doctorWorkTime.setNightBegin(workTime.getString("nightBegin"));
        // 晚上结束时间
        doctorWorkTime.setNightEnd(workTime.getString("nightEnd"));
        // 更新时间
        doctorWorkTime.setCzrq(new Date());
        doctorWorkTimeDao.save(doctorWorkTime);
        doctorWorkWeekDao.deleteByDoctor(doctor);
        // 排班保存
        if (workTWeeks != null) {
            List<WlyyDoctorWorkWeek> weeks = new ArrayList<>();
            for (int i = 0; i < workTWeeks.length(); i++) {
                JSONObject object = workTWeeks.getJSONObject(i);
                WlyyDoctorWorkWeek week = new WlyyDoctorWorkWeek();
                week.setDoctor(doctor);
                week.setDoctorName(doc.getName());
                week.setWeek(object.getString("week"));
                week.setMorning(object.getString("morning"));
                week.setAfternoon(object.getString("afternoon"));
                week.setNight(object.getString("night"));
                week.setCzrq(new Date());
                weeks.add(week);
            }
            doctorWorkWeekDao.save(weeks);
        }
        if (doc.getIsFamous() != null && doc.getIsFamous() == 1) {
            JSONObject json = isDoctorWorkingToday(doctor);
            if (json.getString("status").equals("1")) {
                DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doctor,
                        new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                if (timesRemain == null) {
                    timesRemain = new DoctorFamousConsultTimesRemain();
                    timesRemain.setDoctor(doctor);
                    timesRemain.setTimesRemain(doctorWorkTime.getFamousConsultTimes());
                    timesRemain.setConsultDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    timesRemainDao.save(timesRemain);
                }
            }
        }
        return true;
    }
    /**
     * 医生设置是否接受咨询
     *
     * @param doctor         医生
     * @param receiveConsult 是否接受咨询
     * @return
     */
    public boolean setDoctorReceiveConsult(String doctor, String receiveConsult) throws Exception {
        try {
            WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
            Doctor doc = doctorDao.findByCode(doctor);
            if (doc == null) {
                throw new Exception("doctor not exist");
            }
            // 未有设置,则新建医生设置
            if (workTime == null) {
                workTime = new WlyyDoctorWorkTime();
                workTime.setDoctor(doctor);
                workTime.setDoctorName(doc.getName());
                workTime.setFamousConsultTimes(0);
            }
            // 设置是否接受咨询
            workTime.setReceiveConsult(receiveConsult);
            workTime.setCzrq(new Date());
            doctorWorkTimeDao.save(workTime);
            if (doc.getIsFamous() != null && doc.getIsFamous() == 1) {
                JSONObject json = isDoctorWorkingToday(doctor);
                if (json.getString("status").equals("1")) {
                    DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doctor,
                            new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    if (timesRemain == null) {
                        timesRemain = new DoctorFamousConsultTimesRemain();
                        timesRemain.setDoctor(doctor);
                        timesRemain.setTimesRemain(workTime.getFamousConsultTimes());
                        timesRemain.setConsultDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        timesRemainDao.save(timesRemain);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 医生是否在工作
     *
     * @param doctor 医生
     * @return
     */
    public JSONObject isDoctorWorking(String doctor) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("msg", "医生当前接受咨询");
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                // 医生设置不接受咨询
                json.put("status", "0");
                json.put("msg", "医生不接受咨询");
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("msg", "医生当前接受咨询");
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        if (flag == 1) {
                            json.put("status", "1");
                            json.put("msg", "医生当前接受咨询");
                        } else {
                            json.put("status", "2");
                            json.put("msg", "医生当前不在工作时间");
                        }
                    } else {
                        json.put("status", "2");
                        json.put("msg", "医生当前不在工作时间");
                    }
                }
            }
        }
        return json;
    }
    /**
     * 名医是否在工作查询
     *
     * @param doctor
     * @return
     * @throws Exception
     */
    public JSONObject isFamousDoctorWorking(String doctor) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("msg", "医生当前接受咨询");
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                // 医生设置不接受咨询
                json.put("status", "0");
                json.put("msg", "医生不接受咨询");
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("msg", "医生当前接受咨询");
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String start = "";
                        String end = "";
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            start = currentStart;
                            end = currentEnd;
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (StringUtils.isEmpty(start)) {
                                start = currentStart;
                            }
                            end = currentEnd;
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (StringUtils.isEmpty(start)) {
                                start = currentStart;
                            }
                            end = currentEnd;
                        }
                        if (current.compareTo(start) >= 0 && current.compareTo(end) < 0) {
                            flag = 1;
                        }
                        if (flag == 1) {
                            json.put("status", "1");
                            json.put("msg", "医生当前接受咨询");
                        } else {
                            json.put("status", "2");
                            json.put("msg", "医生当前不在工作时间");
                        }
                    } else {
                        json.put("status", "2");
                        json.put("msg", "医生当前不在工作时间");
                    }
                }
            }
        }
        return json;
    }
    /**
     * 查询名医当天是否接受咨询
     *
     * @param doctor
     * @return
     * @throws Exception
     */
    public JSONObject isDoctorWorkingToday(String doctor) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("times", 0);
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                json.put("status", "0");
                json.put("times", 0);
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("times", doctorWorkTime.getFamousConsultTimes());
                } else {
                    if (result.get("workWeek") != null) {
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        boolean flag = false;
                        if (StringUtils.isNotEmpty(workWeek.getMorning()) && workWeek.getMorning().equals("1")) {
                            json.put("status", "1");
                            json.put("times", doctorWorkTime.getFamousConsultTimes());
                            flag = true;
                        }
                        if (StringUtils.isNotEmpty(workWeek.getAfternoon()) && workWeek.getAfternoon().equals("1")) {
                            json.put("status", "1");
                            json.put("times", doctorWorkTime.getFamousConsultTimes());
                            flag = true;
                        }
                        if (StringUtils.isNotEmpty(workWeek.getNight()) && workWeek.getNight().equals("1")) {
                            json.put("status", "1");
                            json.put("times", doctorWorkTime.getFamousConsultTimes());
                            flag = true;
                        }
                        if (!flag) {
                            json.put("status", "0");
                            json.put("times", 0);
                        }
                    } else {
                        json.put("status", "0");
                        json.put("times", 0);
                    }
                }
            }
        }
        return json;
    }
    /**
     * 设置名医咨询次数
     *
     * @param doctor 医生
     * @return
     */
    public boolean setFamousDoctorConsultTimes(String doctor, int consultTimes) {
        try {
            WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
            Doctor doc = doctorDao.findByCode(doctor);
            int plus = 0;
            if (doc == null) {
                throw new Exception("doctor can not find");
            }
            // 未有设置,则新建医生设置
            if (workTime == null) {
                workTime = new WlyyDoctorWorkTime();
                workTime.setDoctor(doctor);
                workTime.setDoctorName(doc.getName());
                workTime.setReceiveConsult("1");
            } else {
                plus = consultTimes - workTime.getFamousConsultTimes();
            }
            // 设置名医咨询次数
            workTime.setFamousConsultTimes(consultTimes);
            workTime.setCzrq(new Date());
            doctorWorkTimeDao.save(workTime);
            if (doc.getIsFamous() != null && doc.getIsFamous() == 1) {
                JSONObject json = isDoctorWorkingToday(doctor);
                if (json.getString("status").equals("1")) {
                    DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doctor,
                            new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    if (timesRemain == null) {
                        timesRemain = new DoctorFamousConsultTimesRemain();
                        timesRemain.setDoctor(doctor);
                        timesRemain.setTimesRemain(consultTimes);
                        timesRemain.setConsultDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    } else {
                        if (plus >= 0) {
                            timesRemain.setTimesRemain(timesRemain.getTimesRemain() + plus);
                        } else {
                            if (workTime.getFamousConsultTimes() >= Math.abs(plus)) {
                                timesRemain.setTimesRemain(timesRemain.getTimesRemain() - Math.abs(plus));
                            } else {
                                timesRemain.setTimesRemain(0);
                            }
                        }
                    }
                    timesRemainDao.save(timesRemain);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 名医咨询当前剩余次数查询
     *
     * @param doctor 医生
     * @return
     */
    public int getDoctorConsultTimesRemain(String doctor) {
        int result = 0;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doctor, df.format(new Date()));
        if (timesRemain != null) {
            result = timesRemain.getTimesRemain();
        } else {
            WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
            if (workTime != null) {
                result = workTime.getFamousConsultTimes();
            }
        }
        return result;
    }
    /**
     * 名医咨询当前剩余次数减一
     *
     * @param doctor 医生
     * @return
     */
    public boolean setDoctorCurrentConsultTimesRemain(String doctor) {
        try {
            synchronized (obj) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doctor, df.format(new Date()));
                if (timesRemain != null) {
                    int times = timesRemain.getTimesRemain();
                    if (times < 1) {
                        throw new Exception("consult-times-error:doctor does not have not consult times remain");
                    }
                    timesRemain.setTimesRemain(times - 1);
                    timesRemainDao.save(timesRemain);
                } else {
                    DoctorFamousConsultTimesRemain timesRemainNew = new DoctorFamousConsultTimesRemain();
                    WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
                    if (workTime == null || workTime.getFamousConsultTimes() < 1) {
                        throw new Exception("consult-times-error:doctor does not have consult times setting");
                    }
                    timesRemainNew.setDoctor(doctor);
                    timesRemainNew.setConsultDate(df.format(new Date()));
                    timesRemainNew.setTimesRemain(workTime.getFamousConsultTimes() - 1);
                    timesRemainDao.save(timesRemainNew);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 名医咨询次数更新
     *
     * @param date
     */
    @Transactional
    public void consultTimesRemain(String date) {
        try {
            List<Doctor> doctors = doctorDao.findByIsFamous(1);
            for (Doctor doc : doctors) {
                JSONObject json = isDoctorWorkingToday(doc.getCode());
                if (json.getString("status").equals("1")) {
                    DoctorFamousConsultTimesRemain timesRemain = timesRemainDao.findByDoctorAndConsultDate(doc.getCode(), date);
                    if (timesRemain == null) {
                        timesRemain = new DoctorFamousConsultTimesRemain();
                    } else {
                        continue;
                    }
                    timesRemain.setDoctor(doc.getCode());
                    timesRemain.setConsultDate(date);
                    timesRemain.setTimesRemain(json.getInt("times"));
                    timesRemainDao.save(timesRemain);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 2113 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java

@ -0,0 +1,2113 @@
package com.yihu.wlyy.service.app.sign;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.OperatorLog;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.profile.DoctorService;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.statistics.WlyySignFamilyCodeDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.third.fzzb.HealthEducationArticleService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.task.SignUploadTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 家庭签约业务处理类
 *
 * @author George
 */
@Component
@Transactional
public class FamilyContractService extends BaseService {
    private Logger logger = LoggerFactory.getLogger(FamilyContractService.class);
    @Autowired
    private DoctorPatientDao doctorPatientDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorServiceDao doctorServiceDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private DoctorTeamMemberDao doctorTeamDoctor;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private WlyySignFamilyCodeDao wlyySignFamilyCodeDao;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private PatientDiseaseDao patientDiseaseDao;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    MessageService messageService;
    @Autowired
    SignPatientLabelDao labelDao;
    @Autowired
    SignPatientLabelLogDao labelLogDao;
    @Autowired
    SignPatientLabelInfoDao labelInfoDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private OperatorLogDao operatorLogDao;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private SignFamilyRenewDao signFamilyRenewDao;
    @Autowired
    private SignFamilyMappingDao signFamilyMappingDao;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private HealthEducationArticleService healthEducationArticleService;
    @Autowired
    private ImUtill ImUtill;
    @Autowired
    private HttpUtil httpUtil;
    @Value("${sign.check_upload}")
    private String jwUrl;
    @Value("${im.data_base_name}")
    private String im_dataBase_name;
    @Autowired
    private PushMsgTask pushMsgTask;
    public SignFamily findSignFamilyByCode(String code) {
        return signFamilyDao.findByCodeAndType(code, 2);
    }
    public SignFamily findByPatientByType(String patient, int type) {
        return signFamilyDao.findByPatientAndType(patient, type);
    }
    public SignFamily findByPatient(String patient) {
        return signFamilyDao.findByjiatingPatient(patient);
    }
    public SignFamily findSignByPatient(String patient) {
        return signFamilyDao.findSignByPatient(patient);
    }
    /**
     * 获取患者待签约数据
     *
     * @param patient
     * @return
     */
    public SignFamily findSigningByPatient(String patient) {
        return signFamilyDao.findSigningByPatient(patient);
    }
    /**
     * 获取患者待签约数据
     *
     * @param patient
     * @return
     */
    public SignFamily findSigningRenewByPatient(String patient) {
        return signFamilyDao.findSigningByPatient(patient);
    }
    /**
     * 查询医院列表
     *
     * @param type     医院类型:0全部,1大医院,2社区医院
     * @param province 省代码
     * @param city     城市代码
     * @param key      搜索关键字
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<Hospital> findHospitals(int type, String province, String city, String town, String key, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.ASC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (type == 1) {
            // 查询大医院
            filters.put("level", new SearchFilter("level", Operator.EQ, 1));
        } else if (type == 2) {
            // 查询社区医院
            filters.put("level", new SearchFilter("level", Operator.EQ, 2));
        }
        if (StringUtils.isNotEmpty(province)) {
            filters.put("province", new SearchFilter("province", Operator.EQ, province));
        }
        if (StringUtils.isNotEmpty(city)) {
            filters.put("city", new SearchFilter("city", Operator.EQ, city));
        }
        if (StringUtils.isNotEmpty(town)) {
            filters.put("town", new SearchFilter("town", Operator.EQ, town));
        }
        if (StringUtils.isNotEmpty(key)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, key));
        }
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<Hospital> spec = DynamicSpecifications.bySearchFilter(filters.values(), Hospital.class);
        return hospitalDao.findAll(spec, pageRequest);
    }
    /**
     * 查询医院下的医生
     *
     * @param hospital
     * @param level    医生类型:1专科医生,2全科医生,3健康管理师
     * @return
     */
    public Page<Doctor> findDoctors(String hospital, String city, String town, String name, Integer level, Long id, Integer pagesize) {
        if (pagesize == null || pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.ASC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNoneEmpty(hospital)) {
            filters.put("hospital", new SearchFilter("hospital", Operator.EQ, hospital));
        }
        if (!org.springframework.util.StringUtils.isEmpty(city)) {
            filters.put("city", new SearchFilter("city", Operator.EQ, city));
        }
        if (!org.springframework.util.StringUtils.isEmpty(town)) {
            filters.put("town", new SearchFilter("town", Operator.EQ, town));
        }
        if (!org.springframework.util.StringUtils.isEmpty(name)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, "%" + name + "%"));
        }
        if (id != null && id > 0) {
            filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        // 医生类型过滤
        if (level != null && level > 0) {
            filters.put("level", new SearchFilter("level", Operator.EQ, level));
        }
        // 未作废
        filters.put("status", new SearchFilter("status", Operator.EQ, 1));
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        return doctorDao.findAll(spec, pageRequest);
    }
    /**
     * 根据医生和患者获取患者的签约状态
     *
     * @param patient
     * @param doctor
     * @return
     */
    public List<SignFamily> getSign(String patient, String doctor) {
        List<SignFamily> sfList = signFamilyDao.findSSandFamilyByDoctorPatient(patient, doctor);
        return sfList;
    }
    /**
     * 查询集美医生主页信息
     *
     * @param doctor  医生标识
     * @param patient 患者标识
     * @return
     */
    public JSONObject findJiMeiDoctorMainPage(String patient, String doctor,Integer page,Integer pagesize) {
        JSONObject json = new JSONObject();
        // 查询医生基本信息
        Doctor d = doctorDao.findByCode(doctor);
        json.put("doctor", d.getCode());
        json.put("evaluateScore", d.getEvaluateScore());
        json.put("name", d.getName());
        json.put("photo", d.getPhoto());
        json.put("sex", d.getSex());
        json.put("job", d.getJob());
        json.put("jobName", d.getJobName());
        json.put("hospital", d.getHospitalName());
        json.put("dept", d.getDeptName());
        json.put("intro", d.getIntroduce());
        json.put("expertise", d.getExpertise());
        json.put("level", d.getLevel());
        SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
        if (sf == null) {
            // 没有签约信息
            json.put("sign", -1);
            json.put("isjimei", 0);
        } else {
            // 有签约信息
            json.put("sign", sf.getStatus());
            if(sf.getHospital().startsWith("350211")){
                json.put("isjimei", 1);
            }else {
                json.put("isjimei", 0);
            }
        }
        //获取健康文章
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        try {
            jsonArray = healthEducationArticleService.getDoctorArticalByUserId(null,1,null,page,pagesize,doctor);
        }catch (Exception e){
            logger.error("获取福州健康文章失败,"+e.getMessage());
        }
        json.put("healthEduArticles",jsonArray);
        return json;
    }
    /**
     * 查询患者与医生的签约信息
     *
     * @param patient
     * @param doctor
     * @return
     */
    public int findSignStatus(String patient, String doctor) {
        // 查询与当前医生的签约状态
        SignFamily sf = signFamilyDao.findByDoctorPatient(doctor, patient);
        if (sf == null) {
            // 没有签约信息
            return -1;
        } else {
            // 有签约信息
            return sf.getStatus();
        }
    }
    /**
     * 校验签约状态
     *
     * @return
     * @throws Exception
     */
    public JSONObject checkSign(Patient patient) throws Exception {
        JSONObject json = new JSONObject();
        // 查询是否已存在家庭签约
        SignFamily sf = signFamilyDao.findByIdcard(patient.getIdcard());
        if (sf != null) {
            // 已签约
            json.put("sign", 1);
        } else {
            // 未签约
            json.put("sign", 0);
        }
        return json;
    }
    /**
     * 校验当前openid是否签约家庭医生
     *
     * @return
     */
    public String checkPatient(String patient) {
        SignFamily sf = signFamilyDao.findByjiatingPatientStatus0(patient);
        if (sf != null) {
            return sf.getDoctor();
        }
        return null;
    }
    /**
     * 查询是否存在签约状态
     *
     * @param idcard
     * @return
     */
    public int hasSingStatus(String idcard) {
        return signFamilyDao.hasSingStatus(idcard);
    }
    /**
     * 取消签约申请
     *
     * @param patient 患者标识
     * @param doctor  医生标识
     * @return
     */
    public int unsign(String patient, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("doctor info can not find");
        }
        //修改签约标识为无效
        SignFamily sf = null;
        if (doc.getLevel() == 2) {
            sf = signFamilyDao.findByDoctorPatient(doctor, patient);
        } else if (doc.getLevel() == 3) {
            sf = signFamilyDao.findByDoctorHealthPatient(doctor, patient);
        }
        if (sf.getStatus() != 0 && sf.getStatus() != 2) {
            return -2;
        }
        if (sf != null) {
            sf.setStatus(-1);
        } else {
            return -2;
        }
        //结束与医生所有消息
        List<Message> messages = messageDao.findByPatient(patient, doctor);
        if (messages != null && messages.size() > 0) {
            for (Message message : messages) {
                //修改信息为无效
                if (message != null) {
                    message.setRead(0);
                    message.setOver("0");
                }
            }
        }
        return 200;
    }
    /**
     * 取消续签
     *
     * @param patient
     * @param doctor
     * @return
     * @throws Exception
     */
    public int unsignRenew(String patient, String doctor) throws Exception {
        if (DateUtil.getNowMonth() < 7) {
            SignFamilyRenew sf = signFamilyRenewDao.findByDoctorPatient(doctor, patient);
            if (sf != null && sf.getStatus() != 0 && sf.getStatus() != 2) {
                return -2;
            }
            sf.setStatus(-1);
        } else {
            SignFamily sf = signFamilyDao.findByDoctorPatient(doctor, patient);
            if (sf != null && sf.getStatus() != 0 && sf.getStatus() != 2) {
                return -2;
            }
            sf.setStatus(-1);
        }
        //结束与医生所有消息
        List<Message> messages = messageDao.findByPatientRenew(patient, doctor);
        if (messages != null & messages.size() > 0) {
            for (Message message : messages) {
                //修改信息为无效
                if (message != null) {
                    message.setRead(0);
                    message.setOver("0");
                    messageDao.save(message);
                }
            }
        }
        return 200;
    }
    /**
     * 申请解约
     *
     * @param patient 患者标识
     * @param doctor  医生标识
     * @param openid  微信openid
     * @param reason  解约理由
     * @return
     */
    public int surrender(String patient, String patientName, String userPhoto, String doctor, String doctorName, String openid, String reason, int sex) throws Exception {
        // 更新为待解约
        int res = signFamilyDao.surrender(patient, doctor);
        SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
        signFamily.setPatientApplyUnsignDate(new Date());
        if (res == 0) {
            return 0;
        }
        // 添加签约消息
        Message message = new Message();
        // 消息时间
        message.setCzrq(new Date());
        message.setCreateTime(new Date());
        // 消息内容
        message.setContent("申请解除与您的签约关系");
        // 未读
        message.setRead(1);
        message.setReceiverName(doctorName);
        // 接收人
        message.setReceiver(doctor);
        message.setCode(getCode());
        // 发送人
        message.setSender(patient);
        message.setSenderName(patientName);
        message.setSenderPhoto(userPhoto);
        // 标题
        message.setTitle("解除家庭签约申请");
        message.setType(1);
        message.setSignStatus("4");
        message.setReadonly(1);
        message.setSex(sex);
        message.setOver("1");
        // 设置解约理由
        message.setReason(reason);
        message.setData(signFamily.getCode());
        messageDao.save(message);
        // 发送消息给医生
        JSONObject jsonObject = doctorWorkTimeService.isDoctorWorking(doctor);
        if (jsonObject.getString("status").equals("1")) {
            //如果在工作时间内就推送
            pushMsgTask.put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_SIGN_WEB_RELIEVE.D_SW_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_SIGN_WEB_RELIEVE.家庭签约.name(), patientName + " 申请解除与您的家庭签约!", patient);
        }
        return 1;
    }
    /**
     * 查询患者的签约消息
     *
     * @param id
     * @param pagesize
     * @return
     */
    public Page<Message> findMessageByPatient(String patient, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, patient));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }
    /**
     * 查询跟医生相关的家庭签约信息
     *
     * @param type     0全部,1待签约,2已签约,3待解约,4已解约
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<SignFamily> findSignByDoctor(int type, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 只查家庭签约(网络签约)
        filters.put("type", new SearchFilter("type", Operator.EQ, 2));
        switch (type) {
            case 1:
                // 待签约
                filters.put("status", new SearchFilter("status", Operator.EQ, 0));
                break;
            case 2:
                // 已签约
                filters.put("status", new SearchFilter("status", Operator.EQ, 1));
                break;
            case 3:
                // 待解约
                filters.put("status", new SearchFilter("status", Operator.EQ, 2));
                break;
            case 4:
                // 已解约
                filters.put("status", new SearchFilter("status", Operator.EQ, -3));
                break;
        }
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<SignFamily> spec = DynamicSpecifications.bySearchFilter(filters.values(), SignFamily.class);
        return signFamilyDao.findAll(spec, pageRequest);
    }
    /**
     * 查询医生的签约消息
     *
     * @param doctor   医生标识
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<Message> findMessageByDoctor(String doctor, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC,"read"));
//        sort.and(new Sort(Direction.DESC,"czrq"));
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, doctor));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 只查询未处理的消息
        filters.put("type", new SearchFilter("type", Operator.EQ, 1));
        filters.put("over", new SearchFilter("over", Operator.EQ, 1));
        filters.put("read", new SearchFilter("read", Operator.EQ, 1));
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }
    /**
     * 查询已签约总数
     *
     * @param doctor
     * @return
     */
    public int countAmountSigned(String doctor) {
        AdminTeam adminTeam = doctorAdminTeamDao.findByLeaderCode(doctor);
        if (adminTeam != null) {
            //团队长只显示实际有签约关系的数量
            return signFamilyDao.countAmountSignedByAdminTeam(adminTeam.getId());
        } else {
            //不是团队长显示所有有服务关系的数量
            return signFamilyDao.countAmountSignedByDoctor(doctor);
        }
    }
    /**
     * 查询待签约总数
     *
     * @param doctor
     * @return
     */
    public int countAmountUnsign(String doctor) {
        return signFamilyDao.countAmountUnsignByDoctor(doctor);
    }
    public List<?> amountPatients(String uid) {
        return null;
    }
    public SignFamily getFamilyContractByIdcard(String idCard) {
        return signFamilyDao.findByIdcard(idCard);
    }
    public SignFamily getFamilyContractByMobile(String mobile) {
        return signFamilyDao.findByMobile(mobile);
    }
    /**
     * 生成签约标识
     *
     * @param doctor 医生标识
     * @return
     */
    private String createSignCode(String doctor, String hospital) {
        // 获取当前年份
        String year = DateUtil.getStringDate(DateUtil.YY);
        Hospital hospital1 = hospitalDao.findByCode(hospital);
        Integer amount = 0;
        SignFamilyCode wlyySignFamilyCode = wlyySignFamilyCodeDao.findByOrgCodeAndYear(hospital, year);
        if (wlyySignFamilyCode != null) {
            amount = wlyySignFamilyCode.getSequence() + 1;
            wlyySignFamilyCode.setSequence(amount);
            wlyySignFamilyCode.setModifyTime(new Date());
        } else {
            //创建序列
            amount = 1;
            SignFamilyCode wlyySignFamilyCodeTemp = new SignFamilyCode();
            wlyySignFamilyCodeTemp.setModifyTime(new Date());
            wlyySignFamilyCodeTemp.setOrgCode(hospital1.getCode());
            wlyySignFamilyCodeTemp.setOrgName(hospital1.getName());
            wlyySignFamilyCodeTemp.setYear(year);
            wlyySignFamilyCodeTemp.setSequence(1);
            wlyySignFamilyCodeDao.save(wlyySignFamilyCodeTemp);
        }
        return year + hospital1.getRoadCode() + hospital1.getCenterSite() + "Y" + StringUtils.leftPad(String.valueOf(amount + 1), 5, "0");
    }
    public SignFamily findBySanshiPatient(String code) {
        return signFamilyDao.findSanshiSignByPatient(code);
    }
    public SignFamily findByFamilySignPatient(String code) {
        return signFamilyDao.findFamilySignByPatient(code);
    }
    public SignFamily findByJiatingPatient(String code) {
        return signFamilyDao.findByjiatingPatientYes(code);
    }
    /**
     * 查询患者已签约信息
     *
     * @param code
     * @return
     */
    public SignFamily findBySsPatient(String code) {
        return signFamilyDao.findBySsPatient(code);
    }
    public List<Map<String, Object>> getDoctorsByhospitalNoPage(String hospital, String name, Integer type) {
        String sql = "select * from wlyy_doctor where 1=1 and del=1 and iscertified=1 and status=1 ";
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNoneEmpty(hospital)) {
            sql += " and hospital =? ";
            params.add(hospital);
        }
        if (StringUtils.isNoneEmpty(name)) {
            sql += " and name like ? ";
            params.add("%" + name + "%");
        }
        if (type != null && type > 0) {
            sql += " and level =? ";
            params.add(type);
        }
        return jdbcTemplate.queryForList(sql, params.toArray());
    }
    public Map<String, Object> getSanshiSignByPatientCode(String patientCode) {
        Map<String, Object> map = new HashMap<>();
        SignFamily signFamily = signFamilyDao.findBySanshiPatient(patientCode);
        //判斷之前有没有三师签约
        if (signFamily != null) {
            map.put("hasSanshi", "true");
            //得到团队的专科医生
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 1);
            map.put("zkCode", doctorTeamMember.getMemberCode());
            map.put("zkName", doctorTeamMember.getName());
            //得到团队的全科医生
            doctorTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 2);
            map.put("qkCode", doctorTeamMember.getMemberCode());
            map.put("qkName", doctorTeamMember.getName());
            //得到团队的健康管理医生
            doctorTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 3);
            map.put("glsCode", doctorTeamMember.getMemberCode());
            map.put("glsName", doctorTeamMember.getName());
            //得到之前病人得的病
            Patient pa = patientDao.findByCode(patientCode);
            map.put("disease", pa.getDisease());
        } else {
            map.put("hasSanshi", "false");
        }
        return map;
    }
    public SignFamily findByPatientYes(String id) {
        return signFamilyDao.findByjiatingPatient(id);
    }
    public SignFamily findBySanshiPatientYes(String id) {
        return signFamilyDao.findBySanshiPatientYes(id);
    }
    /**
     * 根据身份证号查找病人的三师签约信息
     *
     * @param idCard
     * @return
     */
    public JSONObject getSanshiSingInfoByPatientIdCard(String idCard) throws Exception {
        JSONObject result = new JSONObject();
        SignFamily sign = signFamilyDao.findByPatientSanshiSignInfo(idCard);
        SignFamily signFamily = signFamilyDao.findByPatientFamilySignInfo(idCard);
        Patient p = patientDao.findByIdcard(idCard);
        //if (p == null) {
        //    result.put("signStatus", "0");
        //    result.put("msg", "病人未注册");
        //    return result;
        //}
        if (signFamily != null) {
            result.put("signStatus", "2");
            result.put("msg", "病人已申请过家庭签约!");
            return result;
        }
        if (sign != null) {
            List<DoctorTeamMember> members = doctorTeamDoctor.findByTeamAndDel(sign.getTeamCode(), "1");
            if (members == null) {
                throw new Exception("签约团队信息有误!");
            }
            //三师签约医生信息
            for (DoctorTeamMember member : members) {
                if (member.getType() == 1) {
                    result.put("majorDoctor", member.getMemberCode());
                    result.put("majorDoctorName", member.getName());
                } else if (member.getType() == 2) {
                    Doctor doctor = doctorDao.findByCode(member.getMemberCode());
                    result.put("hospital", doctor.getHospital());
                    result.put("doctor", member.getMemberCode());
                    result.put("doctorName", member.getName());
                } else if (member.getType() == 3) {
                    result.put("healthDoctor", member.getMemberCode());
                    result.put("healthDoctorName", member.getName());
                }
            }
            // 查询患者疾病
            List<PatientDisease> diseases = patientDiseaseDao.findByPatientSsDisease(p.getCode());
            if (diseases != null && diseases.size() > 0) {
                JSONArray disArray = new JSONArray();
                for (PatientDisease dis : diseases) {
                    disArray.put(new JSONObject(dis));
                }
                result.put("diseases", disArray);
            } else {
                result.put("diseases", "");
            }
            result.put("signStatus", "1");
        } else {
            result.put("signStatus", "3");
        }
        if (p != null) {
            JSONObject pJson = new JSONObject(p);
            if (pJson.has("password")) {
                pJson.remove("password");
            }
            if (pJson.has("salt")) {
                pJson.remove("salt");
            }
            result.put("patient", pJson);
        }
        return result;
    }
    /**
     * 获取签约医生
     * @param patientCode
     * @return
     */
    public com.alibaba.fastjson.JSONArray getSignDoctors(String patientCode){
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        SignFamily jtSignFamily = signFamilyDao.findFamilySignByPatient(patientCode);
        if (jtSignFamily != null) {
            Patient patient = patientDao.findByCode(patientCode);
            Doctor doctor = doctorDao.findByCode(jtSignFamily.getDoctor());
            if (doctor != null) {
                com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
                jo.put("code", doctor.getCode());
                jo.put("sex", doctor.getSex());
                jo.put("name", doctor.getName());
                jo.put("photo", doctor.getPhoto());
                jo.put("hosptialName", doctor.getHospitalName());
                jo.put("level", doctor.getLevel());
                jo.put("signType", "2");//2是家庭
                jo.put("signStatus", jtSignFamily.getStatus());
                jo.put("jobName", doctor.getJobName());
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (jtSignFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
                } else {
                    jo.put("qyDate", DateUtil.dateToStrShort(jtSignFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(jtSignFamily.getEnd()));//结束时间
                }
                jsonArray.add(jo);
            }
        }
        return jsonArray;
    }
    public JSONArray getSignDoctorMessage(String patientCode) {
        JSONArray jsonArray = new JSONArray();
        //找出患者的三师签约信息
        SignFamily signFamily = signFamilyDao.findSanshiSignByPatient(patientCode);
        Patient patient = patientDao.findByCode(patientCode);
        if (signFamily != null) {
            //得到三师签约的服务团队
            List<Doctor> doctors = doctorDao.findSanshiDoctorByTeam(signFamily.getTeamCode());
            for (Doctor doctor : doctors) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctor.getCode());//医生code
                jo.put("sex", doctor.getSex());//医生性别  1男,2女)
                jo.put("name", doctor.getName());//医生名称
                jo.put("photo", doctor.getPhoto());//医生头像
                jo.put("hosptialName", doctor.getHospitalName());//所属机构名称
                jo.put("level", doctor.getLevel());//医生等级1专科医生,2全科医生,3健康管理师
                jo.put("signType", "1");//签约类别 1是三师 2是家庭
                jo.put("signStatus", signFamily.getStatus());//签约状态 0待签约,1已签约 2待解约
                jo.put("jobName", doctor.getJobName());//职称
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (signFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(signFamily.getPatientApplyDate()));//申请时间
                } else if (signFamily.getStatus() == 1) {
                    jo.put("qyDate", DateUtil.dateToStrShort(signFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(signFamily.getEnd()));//结束时间
                } else if (signFamily.getStatus() == 2) {
                    jo.put("qyDate", DateUtil.dateToStrShort(signFamily.getPatientApplyUnsignDate()));//申请解约时间
                    jo.put("endDate", DateUtil.dateToStrShort(signFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
        }
        //得到家庭签约
        SignFamily jtSignFamily = signFamilyDao.findFamilySignByPatient(patientCode);
        if (jtSignFamily != null) {
            //家庭签约只找全科医生
            Doctor doctor = doctorDao.findByCode(jtSignFamily.getDoctor());
            Doctor doctorHealth = doctorDao.findByCode(jtSignFamily.getDoctorHealth());
            if (doctor != null) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctor.getCode());
                jo.put("sex", doctor.getSex());
                jo.put("name", doctor.getName());
                jo.put("photo", doctor.getPhoto());
                jo.put("hosptialName", doctor.getHospitalName());
                jo.put("level", doctor.getLevel());
                jo.put("signType", "2");//2是家庭
                jo.put("signStatus", jtSignFamily.getStatus());
                jo.put("jobName", doctor.getJobName());
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (jtSignFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
                } else {
                    jo.put("qyDate", DateUtil.dateToStrShort(jtSignFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(jtSignFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
            if (doctorHealth != null) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctorHealth.getCode());
                jo.put("sex", doctorHealth.getSex());
                jo.put("name", doctorHealth.getName());
                jo.put("photo", doctorHealth.getPhoto());
                jo.put("hosptialName", doctorHealth.getHospitalName());
                jo.put("level", doctorHealth.getLevel());
                jo.put("signType", "2");//2是家庭
                jo.put("signStatus", jtSignFamily.getStatus());
                jo.put("jobName", doctorHealth.getJobName());
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (jtSignFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
                } else {
                    jo.put("qyDate", DateUtil.dateToStrShort(jtSignFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(jtSignFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
        }
        return jsonArray;
    }
    public SignFamily getPatientSign(String patient) {
        return signFamilyDao.findByPatient(patient);
    }
    public SignFamily getssPatientSign(String invitePatientCode) {
        return signFamilyDao.findBySsPatient(invitePatientCode);
    }
    /**
     * 患者家庭签约收费类型更新
     *
     * @param expensesType
     * @param patient
     * @return
     */
    public boolean updateExpensesType(String expensesType, String patient) {
        return signFamilyDao.updateExpensesType(expensesType, patient) > 0;
    }
    public boolean updateSignStatus(String patientCard) {
        // 判断患者有没有家庭签约
        SignFamily sf = signFamilyDao.findByPatientStatus(patientCard, 0);
        if (sf != null) {
            sf.setStatus(-1);
        }
        return true;
    }
    public String produceSignAdminTeamCode() {
        StringBuffer sf = new StringBuffer();
        StringBuffer sf1 = new StringBuffer();
        Long size = 0L;
        //找出家庭签约中团队code是空的
        List<SignFamily> signFamilys = signFamilyDao.findBySignTypeAndTeamCode();
        sf.append("家庭签约中团队code是空的数据数:" + signFamilys.size());
        for (SignFamily signFamily : signFamilys) {
            //得到签约中的全科医生的团队
            String doctorCode = signFamily.getDoctor();
            Long id = doctorAdminTeamDao.findIdByLeaderCode(doctorCode);
            if (id != null && id > 0) {
                size++;
                signFamily.setAdminTeamId(id);
            } else {
                sf1.append(",找不到医生所属的团队,医生code:" + doctorCode);
            }
        }
        sf.append(",填充团队的签约数据数:" + size);
        sf.append(sf1);
        return sf.toString();
    }
    public JSONObject findByParamsWithDoctor(String doctorCode, String teamCode, String params, int level) throws Exception {
        JSONObject returnMap = new JSONObject();
        String addressSql = "select a.signcode,a.name,a.address,a.code,a.hasopenid,a.idcard,a.photo from( SELECT " +
                "  sf.CODE signcode, " +
                "  p.photo photo, " +
                "  p.name name, " +
                "  p.address address, " +
                "  p.code code, " +
                "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                "  p.idcard idcard " +
                " FROM " +
                " wlyy_sign_family sf " +
                " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf. STATUS > 0 " +
                // " and sf.doctor = ? " +
                " and sf.admin_team_code = ? " +
                " AND ( " + (level == 2 ? "sf.doctor =?" : "sf.doctor_health =? ") + ") ) a where 1=1";
        if (!org.springframework.util.StringUtils.isEmpty(params)) {
            addressSql += " AND a.address like '%" + params + "%'";
        }
        List<Map<String, Object>> datas = jdbcTemplate.queryForList(addressSql, teamCode, doctorCode);
        if (datas != null && datas.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> map : datas) {
                JSONObject jo = new JSONObject();
                jo.put("signcode", map.get("signcode"));
                jo.put("name", map.get("name"));
                jo.put("photo", map.get("photo"));
                jo.put("address", map.get("address"));
                jo.put("code", map.get("code"));
                jo.put("hasopenid", map.get("hasopenid"));
                jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                jsonArray.put(jo);
            }
            returnMap.put("address", jsonArray);
        }
        String patientNameSql = "select a.signcode,a.name,a.address,a.code,a.hasopenid,a.idcard,a.photo from( SELECT " +
                "  sf.CODE signcode, " +
                "  p.name name, " +
                "  p.photo photo, " +
                "  p.address address, " +
                "  p.code code, " +
                "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                "  p.idcard idcard " +
                " FROM " +
                " wlyy_sign_family sf " +
                " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf. STATUS > 0 " +
                //" and sf.doctor = ? " +
                " and sf.admin_team_code = ? " +
                " AND ( " + (level == 2 ? "sf.doctor =?" : "sf.doctor_health =? ") + ") ) a where 1=1";
        if (!org.springframework.util.StringUtils.isEmpty(params)) {
            patientNameSql += " AND a.name like '%" + params + "%'";
        }
        datas = jdbcTemplate.queryForList(patientNameSql, teamCode, doctorCode);
        if (datas != null && datas.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> map : datas) {
                JSONObject jo = new JSONObject();
                jo.put("signcode", map.get("signcode"));
                jo.put("name", map.get("name"));
                jo.put("photo", map.get("photo"));
                jo.put("code", map.get("code"));
                jo.put("hasopenid", map.get("hasopenid"));
                jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                jsonArray.put(jo);
            }
            returnMap.put("name", jsonArray);
        }
        return returnMap;
    }
    public JSONObject findNoHealthSignFamilyHealthByParams(String doctorCode, String teamCode, String params) throws Exception {
        JSONObject returnMap = new JSONObject();
        String addressSql = "select a.signcode,a.name,a.address,a.code,a.hasopenid,a.idcard,a.photo from( SELECT " +
                "  sf.CODE signcode, " +
                "  p.photo photo, " +
                "  p.name name, " +
                "  p.address address, " +
                "  p.code code, " +
                "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                "  p.idcard idcard " +
                " FROM " +
                " wlyy_sign_family sf " +
                " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf. STATUS > 0 " +
                // " and sf.doctor = ? " +
                " and sf.admin_team_code = ? " +
                " AND ( sf.doctor_health is null or sf.doctor_health ='' ) ) a where 1=1";
        if (!org.springframework.util.StringUtils.isEmpty(params)) {
            addressSql += " AND a.address like '%" + params + "%'";
        }
        List<Map<String, Object>> datas = jdbcTemplate.queryForList(addressSql, teamCode);
        if (datas != null && datas.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> map : datas) {
                JSONObject jo = new JSONObject();
                jo.put("signcode", map.get("signcode"));
                jo.put("name", map.get("name"));
                jo.put("photo", map.get("photo"));
                jo.put("address", map.get("address"));
                jo.put("code", map.get("code"));
                jo.put("hasopenid", map.get("hasopenid"));
                jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                jsonArray.put(jo);
            }
            returnMap.put("address", jsonArray);
        }
        String patientNameSql = "select a.signcode,a.name,a.address,a.code,a.hasopenid,a.idcard,a.photo from( SELECT " +
                "  sf.CODE signcode, " +
                "  p.name name, " +
                "  p.photo photo, " +
                "  p.address address, " +
                "  p.code code, " +
                "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                "  p.idcard idcard " +
                " FROM " +
                " wlyy_sign_family sf " +
                " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf. STATUS > 0 " +
                //" and sf.doctor = ? " +
                " and sf.admin_team_code = ? " +
                " AND ( sf.doctor_health is null or sf.doctor_health ='' ) ) a where 1=1";
        if (!org.springframework.util.StringUtils.isEmpty(params)) {
            patientNameSql += " AND a.name like '%" + params + "%'";
        }
        datas = jdbcTemplate.queryForList(patientNameSql, teamCode);
        if (datas != null && datas.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> map : datas) {
                JSONObject jo = new JSONObject();
                jo.put("signcode", map.get("signcode"));
                jo.put("name", map.get("name"));
                jo.put("photo", map.get("photo"));
                jo.put("code", map.get("code"));
                jo.put("hasopenid", map.get("hasopenid"));
                jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                jsonArray.put(jo);
            }
            returnMap.put("name", jsonArray);
        }
        return returnMap;
    }
    public JSONObject findNoHealthSignFamilyHealth(String doctorCode, String labelType, String patientName, Long teamCode) throws Exception {
        JSONObject returnMap = new JSONObject();
        //健康管理师
        String sql = "SELECT " +
                "  sf. CODE signcode, " +
                "  p.photo photo, " +
                "  p.name name, " +
                "  p.code code, " +
                "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                "  sp.id labelid, " +
                "  CASE WHEN sp.label_name is null THEN '未标注' WHEN sp.label_name='' THEN '未标注' else sp.label_name END labelname, " +
                "  sp.label_type labeltype, " +
                "  p.idcard idcard " +
                " FROM " +
                " wlyy_sign_family sf " +
                " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                " left JOIN wlyy_sign_patient_label_info sp ON sf.patient = sp.patient AND sp.label_type = ? AND sp.`status` = 1 " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf. STATUS > 0 " +
                // " and sf.doctor = ? " +
                " and sf.admin_team_code = ? " +
                " AND ( sf.doctor_health is null or sf.doctor_health ='' ) ";
        List<Map<String, Object>> datas = null;
        //查找居民
        datas = jdbcTemplate.queryForList(sql, labelType, teamCode);
        //根据类别查找标签
        List<SignPatientLabel> s = labelDao.findByLabelTypeAndStatusAndTeamCode(labelType, 1, teamCode);
        if (s != null && s.size() > 0) {
            for (SignPatientLabel one : s) {
                returnMap.put(one.getLabelName(), new JSONArray());
            }
            if (datas != null && datas.size() > 0) {
                for (Map<String, Object> map : datas) {
                    JSONObject jo = new JSONObject();
                    jo.put("signcode", map.get("signcode"));
                    jo.put("name", map.get("name"));
                    jo.put("photo", map.get("photo"));
                    jo.put("code", map.get("code"));
                    jo.put("hasopenid", map.get("hasopenid"));
                    jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                    jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                    JSONArray jr = new JSONArray();
                    if (returnMap.has(map.get("labelname").toString())) {
                        jr = returnMap.getJSONArray(map.get("labelname").toString());
                    }
                    jr.put(jo);
                    returnMap.put(map.get("labelname").toString(), jr);
                }
            }
        }
        return returnMap;
    }
    /**
     * 查询居民的所有签约
     *
     * @param patient
     * @return
     */
    public List<SignFamily> findAllSignByPatient(String patient) {
        return signFamilyDao.findAllSignByPatient(patient);
    }
    public List<SignFamily> findNoHealthSignFamilyNum(long teamCode) {
        return signFamilyDao.findNoHealthSignFamilyNum(teamCode);
    }
    /**
     * 获取未分配健管师关注公众号人数
     *
     * @param teamCode
     * @return
     * @throws Exception
     */
    public int findNoHealthSignFamilyFocusNum(Long teamCode) throws Exception {
        String sql = "select count(distinct patient) count from wlyy_sign_family where admin_team_code = ? and doctor_health is null and status > 0 and length(trim(ifnull(openid,''))) > 1";
        List<Map<String, Object>> count = jdbcTemplate.queryForList(sql, teamCode);
        if (count != null && count.size() > 0 && count.get(0).containsKey("count")) {
            return Integer.valueOf(String.valueOf(count.get(0).get("count")));
        } else {
            return 0;
        }
    }
    /**
     * 判断居民与医生是否存在签约关系
     *
     * @param patient
     * @param doctor
     * @return
     */
    public JSONObject isPatientAndDoctorExistSign(String patient, String doctor) {
        JSONObject result = new JSONObject();
        SignFamily familySign = signFamilyDao.findFamilySignByPatient(patient);
        SignFamily sanshiSign = signFamilyDao.findSanshiSignByPatient(patient);
        if (familySign != null) {
            if (doctor.equals(StringUtils.isEmpty(familySign.getDoctor()) ? "" : familySign.getDoctor()) ||
                    doctor.equals(StringUtils.isEmpty(familySign.getDoctorHealth()) ? "" : familySign.getDoctorHealth())) {
                if (familySign.getStatus() == 0) {
                    result.put("status", "0");
                    result.put("msg", "已申请家庭签约");
                } else {
                    result.put("status", "1");
                    result.put("msg", "已有家庭签约");
                }
                return result;
            }
        }
        if (sanshiSign != null) {
            if (doctor.equals(StringUtils.isEmpty(sanshiSign.getDoctor()) ? "" : sanshiSign.getDoctor()) ||
                    doctor.equals(StringUtils.isEmpty(sanshiSign.getDoctorHealth()) ? "" : sanshiSign.getDoctorHealth())) {
                result.put("status", "2");
                result.put("msg", "已有三师签约");
                return result;
            }
        }
        result.put("status", "-1");
        result.put("msg", "无签约关系");
        return result;
    }
    public JSONObject getPatientSignDoctorsByTeam(String sessionId) {
        String infos[] = sessionId.split("_");
        JSONObject result = new JSONObject();
        Map<String, JSONObject> docMap = new HashMap<>();
        SignFamily ssSign = signFamilyDao.findSignByPatient(infos[0], 1);
//        SignFamily jtSign = signFamilyDao.findByTeamCode(infos[1]);
        SignFamily jtSign = getSignFamilyBySessionId(sessionId, infos[0]);
        JSONObject ssArray = new JSONObject();
        JSONObject jtArray = new JSONObject();
        if (ssSign != null) {
            JSONObject qkDoc = new JSONObject();
            qkDoc.put("doctor", ssSign.getDoctor());
            qkDoc.put("doctorName", ssSign.getDoctorName());
            ssArray.put("doctor", qkDoc);
            JSONObject jgDoc = new JSONObject();
            jgDoc.put("doctor", ssSign.getDoctorHealth());
            jgDoc.put("doctorName", ssSign.getDoctorHealthName());
            ssArray.put("doctorHealth", jgDoc);
        }
        if (jtSign != null) {
            JSONObject qkDoc = new JSONObject();
            qkDoc.put("doctor", jtSign.getDoctor());
            qkDoc.put("doctorName", jtSign.getDoctorName());
            jtArray.put("doctor", qkDoc);
            JSONObject jgDoc = new JSONObject();
            jgDoc.put("doctor", jtSign.getDoctorHealth());
            jgDoc.put("doctorName", jtSign.getDoctorHealthName());
            jtArray.put("doctorHealth", jgDoc);
        }
        result.put("ssSign", ssArray);
        result.put("jtSign", jtArray);
        return result;
    }
    /**
     * 根据会话id查询 家庭签约信息
     *
     * @param sessionId
     * @param patient
     * @return
     */
    public SignFamily getSignFamilyBySessionId(String sessionId, String patient) {
        SignFamily signFamily = null;
        String sql = "select id from " + im_dataBase_name + ".topics where  session_id = '" + sessionId + "' order by create_time desc limit 0, 1";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            String consultCode = list.get(0).get("id").toString();
            signFamily = signFamilyDao.findByPatient(patient);
            Consult consult = consultDao.findByCode(consultCode);
            if (signFamily == null || signFamily.getApplyDate().getTime() - consult.getCzrq().getTime() > 0) {
                signFamily = signFamilyDao.findOutTimeSigningByPatient(patient);
            }
        }
        return signFamily;
    }
    /**
     * 查询患者对应医生
     *
     * @param patient
     * @return
     */
    public JSONObject getPatientSignDoctors(String patient) {
        JSONObject result = new JSONObject();
        Map<String, JSONObject> docMap = new HashMap<>();
        SignFamily ssSign = signFamilyDao.findSignByPatient(patient, 1);
        SignFamily jtSign = signFamilyDao.findSignByPatient(patient, 2);
        JSONObject ssArray = new JSONObject();
        JSONObject jtArray = new JSONObject();
        if (ssSign != null) {
            JSONObject qkDoc = new JSONObject();
            qkDoc.put("doctor", ssSign.getDoctor());
            qkDoc.put("doctorName", ssSign.getDoctorName());
            ssArray.put("doctor", qkDoc);
            JSONObject jgDoc = new JSONObject();
            jgDoc.put("doctor", ssSign.getDoctorHealth());
            jgDoc.put("doctorName", ssSign.getDoctorHealthName());
            ssArray.put("doctorHealth", jgDoc);
        }
        if (jtSign != null) {
            JSONObject qkDoc = new JSONObject();
            qkDoc.put("doctor", jtSign.getDoctor());
            qkDoc.put("doctorName", jtSign.getDoctorName());
            jtArray.put("doctor", qkDoc);
            JSONObject jgDoc = new JSONObject();
            jgDoc.put("doctor", jtSign.getDoctorHealth());
            jgDoc.put("doctorName", jtSign.getDoctorHealthName());
            jtArray.put("doctorHealth", jgDoc);
        }
        result.put("ssSign", ssArray);
        result.put("jtSign", jtArray);
        return result;
    }
    public Map<String, List<Patient>> getPatientByLevel(String doctorCode, Long team) {
        Map<String, List<Patient>> returnMap = new HashMap<>();
        Doctor doctor = doctorDao.findByCode(doctorCode);
        //判断当前用户是健康管理师还是全科
        if (doctor.getLevel() == 3) {
            //健康管理师
            List<Patient> jkgl = signFamilyDao.findByDoctorHealthPatient(doctorCode, team);
            returnMap.put("jk", jkgl);
        } else if (doctor.getLevel() == 2) {
            //全科医生
            List<Patient> qkys = signFamilyDao.findByDoctorPatient(doctorCode, team);
            returnMap.put("qk", qkys);
            //健康管理师
            List<Patient> jkgl = signFamilyDao.findByDoctorHealthPatient(doctorCode, team);
            returnMap.put("jk", jkgl);
        }
        return returnMap;
    }
    //根据姓名、地址、身份证搜索已分配健管师的居民
    public List getPatientByLable(String doctorCode, String filter, String level, Long team, int page, int pagesize) throws Exception {
        List list = new ArrayList();
        //判断当前用户是健康管理师还是全科
        List<Map<String, Object>> datas = null;
        if (level.equals("3")) {
            //健康管理师
            String sql = "SELECT DISTINCT " +
                    "  p.photo photo, " +
                    "  p.name name, " +
                    "  p.code code, " +
                    "  p.sex sex," +
                    "  p.address address," +
                    "  p.idcard idcard " +
                    " FROM " +
                    " wlyy_sign_family sf " +
                    " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                    " left JOIN wlyy_sign_patient_label_info sp ON sf.patient = sp.patient AND sp.`status` = 1 " +
                    " WHERE " +
                    " sf.type = 2 " +
                    " AND sf. STATUS > 0 " +
                    " and sf.doctor_health = ? " +
                    " and sf.admin_team_code = ? " +
                    " AND (p.name like ? or p.address like ? or p.idcard like ? ) " +
                    " ORDER BY  p.name DESC,p.address DESC, p.idcard DESC " +
                    " limit " + (page - 1) * pagesize + "," + pagesize;
            //查找居民
            datas = jdbcTemplate.queryForList(sql, doctorCode, team, "%" + filter + "%", "%" + filter + "%", "%" + filter + "%");
        } else if (level.equals("2")) {
            //全科
            String sql = "SELECT  DISTINCT " +
                    "  p.photo photo, " +
                    "  p.name name, " +
                    "  p.code code, " +
                    "  p.sex sex," +
                    "  p.address address," +
                    "  p.idcard idcard " +
                    " FROM " +
                    " wlyy_sign_family sf " +
                    " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                    " left JOIN wlyy_sign_patient_label_info sp ON sf.patient = sp.patient AND sp.`status` = 1 " +
                    " WHERE " +
                    " sf.type = 2 " +
                    " AND sf. STATUS > 0 " +
                    " and  sf.doctor = ?  " +
                    " and sf.admin_team_code = ? " +
                    " AND (p.name like ? or p.address like ? or p.idcard like ? ) " +
                    " ORDER BY  p.name DESC,p.address DESC, p.idcard DESC " +
                    " limit " + (page - 1) * pagesize + "," + pagesize;
            //查找居民
            datas = jdbcTemplate.queryForList(sql, doctorCode, team, "%" + filter + "%", "%" + filter + "%", "%" + filter + "%");
        } else {
            throw new Exception("参数错误!");
        }
        if (datas != null && datas.size() > 0) {
            for (Map<String, Object> map : datas) {
                Map ma = new HashMap();
                ma.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard") == null ? "" : map.get("idcard").toString()));
                ma.put("photo", map.get("photo") == null ? "" : map.get("photo").toString());
                ma.put("name", map.get("name") == null ? "" : map.get("name").toString());
                ma.put("code", map.get("code") == null ? "" : map.get("code").toString());
                ma.put("sex", map.get("sex") == null ? "" : map.get("sex").toString());
                ma.put("address", map.get("address") == null ? "" : map.get("address").toString());
                ma.put("idcard", map.get("idcard") == null ? "" : map.get("idcard").toString());
                list.add(ma);
            }
        }
        return list;
    }
    public JSONObject getPatientByLable(String doctorCode, String labelType, String level, Long team) throws Exception {
        JSONObject returnMap = new JSONObject();
        //判断当前用户是健康管理师还是全科
        List<Map<String, Object>> datas = null;
        if (level.equals("3")) {
            //健康管理师
            String sql = "SELECT " +
                    "  sf. CODE signcode, " +
                    "  p.name name, " +
                    "  p.photo photo, " +
                    "  p.code code, " +
                    "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                    "  sp.id labelid, " +
                    " CASE WHEN sp.label_name is null THEN '未标注' WHEN sp.label_name='' THEN '未标注' else sp.label_name END labelname, " +
                    "  sp.label_type labeltype, " +
                    "  p.idcard idcard " +
                    " FROM " +
                    " wlyy_sign_family sf " +
                    " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                    " left JOIN wlyy_sign_patient_label_info sp ON sf.patient = sp.patient AND sp.label_type = ? AND sp.`status` = 1 " +
                    " WHERE " +
                    " sf.type = 2 " +
                    " AND sf. STATUS > 0 " +
                    " and sf.doctor_health = ? " +
                    " and sf.admin_team_code = ? ";
            //查找居民
            datas = jdbcTemplate.queryForList(sql, labelType, doctorCode, team);
        } else if (level.equals("2")) {
            //全科
            String sql = "SELECT " +
                    "  sf. CODE signcode, " +
                    "  p.name name, " +
                    "  p.photo photo, " +
                    "  p.code code, " +
                    "  CASE WHEN p.openid is null THEN '0' WHEN p.openid='' THEN '0' else 1 END hasopenid, " +
                    "  sp.id labelid, " +
                    " CASE WHEN sp.label_name is null THEN '未标注' WHEN sp.label_name='' THEN '未标注' else sp.label_name END labelname, " +
                    "  sp.label_type labeltype, " +
                    "  p.idcard idcard " +
                    " FROM " +
                    " wlyy_sign_family sf " +
                    " JOIN wlyy_patient p ON sf.patient = p.CODE " +
                    " left JOIN wlyy_sign_patient_label_info sp ON sf.patient = sp.patient AND sp.label_type = ? AND sp.`status` = 1 " +
                    " WHERE " +
                    " sf.type = 2 " +
                    " AND sf. STATUS > 0 " +
                    " and  sf.doctor = ?  " +
                    " and sf.admin_team_code = ? ";
            //查找居民
            datas = jdbcTemplate.queryForList(sql, labelType, doctorCode, team);
        } else {
            throw new Exception("参数错误!");
        }
        //根据类别查找标签
        List<SignPatientLabel> s = labelDao.findByLabelTypeAndStatusAndTeamCode(labelType, 1, team);
        if (s != null && s.size() > 0) {
            for (SignPatientLabel one : s) {
                returnMap.put(one.getLabelName(), new JSONArray());
            }
            if (datas != null && datas.size() > 0) {
                for (Map<String, Object> map : datas) {
                    JSONObject jo = new JSONObject();
                    jo.put("signcode", map.get("signcode"));
                    jo.put("name", map.get("name"));
                    jo.put("photo", map.get("photo"));
                    jo.put("code", map.get("code"));
                    jo.put("hasopenid", map.get("hasopenid"));
                    jo.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                    jo.put("sex", IdCardUtil.getSexForIdcard_new(map.get("idcard").toString()));
                    //判断name是否为空 为空就是未标注
                    //把患者添加到对应的组
                    JSONArray jr = new JSONArray();
                    if (returnMap.has(map.get("labelname").toString())) {
                        jr = returnMap.getJSONArray(map.get("labelname").toString());
                    }
                    jr.put(jo);
                    returnMap.put(map.get("labelname").toString(), jr);
                }
            }
        }
        return returnMap;
    }
    public Integer findPatientCountByAdminTeam(String doctorCode, String teamCode) {
        String sql = "select count(sf.id) " +
                " FROM " +
                " wlyy_sign_family sf " +
                " WHERE " +
                " sf.type = 2 " +
                " AND sf.STATUS > 0 " +
                " AND ( sf.doctor = ? or sf.doctor_health=? )" +
                " AND sf.admin_team_code =?";
        Object[] parms = new Object[]{doctorCode, doctorCode, teamCode};
        Integer count = jdbcTemplate.queryForObject(sql, parms, Integer.class);
        return count;
    }
    /**
     * @param code
     * @return
     */
    public String getTeamName(String code) {
        try {
            String sql = "SELECT t.name FROM wlyy_doctor_team t WHERE t.code ='" + code + "'";
            List<Map<String, Object>> map = jdbcTemplate.queryForList(sql);
            if (map != null && map.size() > 0) {
                return (String) map.get(0).get("name");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public JSONArray getSignDoctorMessageOverDue(String patientCode) {
        JSONArray jsonArray = new JSONArray();
        //找出患者的三师签约信息
        Patient patient = patientDao.findByCode(patientCode);
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //得到家庭签约
        SignFamily jtSignFamily = signFamilyDao.findFamilySignByPatientOverDue(patientCode, (year - 1) + "");
        if (jtSignFamily != null) {
            //家庭签约只找全科医生
            Doctor doctor = doctorDao.findByCode(jtSignFamily.getDoctor());
            Doctor doctorHealth = doctorDao.findByCode(jtSignFamily.getDoctorHealth());
            if (doctor != null) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctor.getCode());
                jo.put("sex", doctor.getSex());
                jo.put("name", doctor.getName());
                jo.put("photo", doctor.getPhoto());
                jo.put("hosptialName", doctor.getHospitalName());
                jo.put("level", doctor.getLevel());
                jo.put("signType", "2");//三师签约
                jo.put("signStatus", jtSignFamily.getStatus());
                jo.put("jobName", doctor.getJobName());
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (jtSignFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
                } else {
                    jo.put("qyDate", DateUtil.dateToStrShort(jtSignFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(jtSignFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
            if (doctorHealth != null) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctorHealth.getCode());
                jo.put("sex", doctorHealth.getSex());
                jo.put("name", doctorHealth.getName());
                jo.put("photo", doctorHealth.getPhoto());
                jo.put("hosptialName", doctorHealth.getHospitalName());
                jo.put("level", doctorHealth.getLevel());
                jo.put("signType", "2");//三师签约
                jo.put("signStatus", jtSignFamily.getStatus());
                jo.put("jobName", doctorHealth.getJobName());
                jo.put("disease", patient.getDisease());//0健康,1高血压,2糖尿病,3高血压+糖尿病
                if (jtSignFamily.getStatus() == 0) {
                    jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
                } else {
                    jo.put("qyDate", DateUtil.dateToStrShort(jtSignFamily.getBegin()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort(jtSignFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
        }
        return jsonArray;
    }
    /**
     * 存储同步纪委标识
     *
     * @param idCard
     * @param signYear
     */
    public void setSignFamilyMapping(String signCode, String idCard, String signYear) {
        SignFamilyMapping maping = new SignFamilyMapping();
        maping.setCode(signCode);
        maping.setCreateTime(new Date());
        maping.setIdcard(idCard);
        maping.setNeedUpdate("0");
        maping.setSignYear(signYear);
        //判断是否是预签约
        //判断规则:如果在4月份到7月份为预签约
        int month = DateUtil.getNowMonth();
        if (month >= 4 && month < 7) {
            //预签约逻辑
            maping.setNeedUpload("0");
            maping.setNeedRenewUpload("1");
        } else {
            maping.setNeedUpload("1");
            maping.setNeedRenewUpload("0");
        }
        signFamilyMappingDao.save(maping);
    }
    public SignFamily findOutTimeSigningByPatient(String patient) {
        return signFamilyDao.findOutTimeSigningByPatient(patient);
    }
    public JSONObject getServerPatientList(Long teamCode) {
        String serverSql = "SELECT " +
                " d.`code` As labelCode, " +
                " d.`name` AS label " +
                " FROM " +
                " wlyy_sign_dict d " +
                " WHERE " +
                " d.type IN ('1', '2') " +
                " AND d. YEAR = '" + DateUtil.getSignYear() + "' ";
        String patientSql = "SELECT " +
                " f.patient, " +
                " f.sign_year, " +
                " t.server_type AS serverType, " +
                " t.server_type_name AS specialPopulation " +
                "FROM " +
                " wlyy_sign_family_server t, " +
                " ( " +
                "  SELECT " +
                "   s.`code`, " +
                "   s.patient, " +
                "   s.sign_year " +
                "  FROM " +
                "   wlyy_sign_family s " +
                "  WHERE " +
                "   s.`status` >= 0 " +
                "  AND s.admin_team_code = " + teamCode +
                "  AND s.doctor_health IS NULL " +
                " ) f " +
                "WHERE " +
                " t.sign_code = f. CODE ";
        List<Map<String, Object>> patientList = jdbcTemplate.queryForList(patientSql);
        String totalSql = " SELECT " +
                " s.patient" +
                " FROM " +
                " wlyy_sign_family s " +
                " WHERE " +
                " s.`status` >= 0 " +
                " AND s.admin_team_code =" + teamCode +
                " AND s.doctor_health IS NULL";
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        JSONObject rs = new JSONObject();
        rs.put("count", (totalList != null && totalList.size() > 0) ? totalList.size() : 0);
        List<Map<String, Object>> serlist = jdbcTemplate.queryForList(serverSql);
        if (serlist != null && serlist.size() > 0) {
            if (patientList != null) {
                for (Map<String, Object> map : serlist) {
                    String labelCode = (String) map.get("labelCode");
                    List<Map<String, String>> codes = new ArrayList<>();
                    Iterator iterator = patientList.iterator();
                    while (iterator.hasNext()) {
                        Map<String, Object> p = (Map<String, Object>) iterator.next();
                        String serverType = p.get("serverType") == null ? "" : ((String) p.get("serverType"));
                        if (labelCode.equals(serverType)) {
                            Map<String, String> code = new HashMap<>();
                            code.put("code", (String) p.get("patient"));
                            codes.add(code);
                            iterator.remove();
                        }
                    }
                    map.put("codes", codes);
                    map.put("number", (codes != null && codes.size() > 0) ? codes.size() : 0);
                }
            }
        }
        rs.put("patients", serlist);
        return rs;
    }
    public JSONObject getCountryPatientList(Long teamCode) {
        String totalSql = " SELECT " +
                " s.patient,ifnull(s.sick_village,0) as labelCode" +
                " FROM " +
                " wlyy_sign_family s " +
                " WHERE " +
                " s.`status` >= 0 " +
                " AND s.admin_team_code = ? " +
                " AND s.doctor_health IS NULL";
        JSONObject rs = new JSONObject();
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql, new Object[]{teamCode});
        rs.put("count", (totalList != null && totalList.size() > 0) ? totalList.size() : 0);
        String patientSql = "SELECT " +
                " f.sick_village AS labelCode, " +
                " f.sick_village_name AS label, " +
                " COUNT(1) AS number " +
                " FROM " +
                " wlyy_sign_family f " +
                " WHERE " +
                " f.`status` >= 0 " +
                " AND f.admin_team_code = ? " +
                " AND f.doctor_health IS NULL " +
                " AND f.sick_village IS NOT NULL " +
                " GROUP BY " +
                " f.sick_village " +
                " ORDER BY " +
                " number DESC ";
        List<Map<String, Object>> patientList = jdbcTemplate.queryForList(patientSql, new Object[]{teamCode});
        if (patientList != null && patientList.size() > 0) {
            for (Map<String, Object> map : patientList) {
                String labelCode = (String) map.get("labelCode");
                if (StringUtils.isNotBlank(labelCode)) {
                    List<Map<String, String>> codes = new ArrayList<>();
                    Iterator iterator = totalList.iterator();
                    while (iterator.hasNext()) {
                        Map<String, Object> p = (Map<String, Object>) iterator.next();
                        String lbCode = p.get("labelCode") == null ? "" : ((String) p.get("labelCode"));
                        if (labelCode.equals(lbCode)) {
                            Map<String, String> code = new HashMap<>();
                            code.put("code", (String) p.get("patient"));
                            codes.add(code);
                            iterator.remove();
                        }
                    }
                    map.put("codes", codes);
                }
            }
        }
        rs.put("patients", patientList);
        return rs;
    }
    public JSONObject getTeamCountryPatientChangeDoctorList(Long teamCode, String level, String oldDoctorCode) {
        String totalSql = " SELECT " +
                " s.patient,ifnull(s.sick_village,0) as labelCode" +
                " FROM " +
                " wlyy_sign_family s " +
                " WHERE " +
                " s.`status` >= 0 " +
                " AND s.admin_team_code = ? ";
        if ("2".equals(level)) {
            totalSql = totalSql + " AND s.doctor ='" + oldDoctorCode + "'";
        } else {
            totalSql = totalSql + " AND s.doctor_health ='" + oldDoctorCode + "'";
        }
        JSONObject rs = new JSONObject();
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql, new Object[]{teamCode});
        rs.put("count", (totalList != null && totalList.size() > 0) ? totalList.size() : 0);
        String patientSql = "SELECT " +
                " f.sick_village AS labelCode, " +
                " f.sick_village_name AS label, " +
                " COUNT(1) AS number " +
                " FROM " +
                " wlyy_sign_family f " +
                " WHERE " +
                " f.`status` >= 0 " +
                " AND f.sick_village IS NOT NULL " +
                " AND f.admin_team_code = ? ";
        if ("2".equals(level)) {
            patientSql = patientSql + " AND f.doctor ='" + oldDoctorCode + "'";
        } else {
            patientSql = patientSql + " AND f.doctor_health ='" + oldDoctorCode + "'";
        }
        patientSql = patientSql + " GROUP BY " +
                " f.sick_village " +
                " ORDER BY " +
                " number DESC ";
        List<Map<String, Object>> patientList = jdbcTemplate.queryForList(patientSql, new Object[]{teamCode});
        if (patientList != null && patientList.size() > 0) {
            for (Map<String, Object> map : patientList) {
                String labelCode = (String) map.get("labelCode");
                if (StringUtils.isNotBlank(labelCode)) {
                    List<Map<String, String>> codes = new ArrayList<>();
                    Iterator iterator = totalList.iterator();
                    while (iterator.hasNext()) {
                        Map<String, Object> p = (Map<String, Object>) iterator.next();
                        String lbCode = p.get("labelCode") == null ? "" : ((String) p.get("labelCode"));
                        if (labelCode.equals(lbCode)) {
                            Map<String, String> code = new HashMap<>();
                            code.put("code", (String) p.get("patient"));
                            codes.add(code);
                            iterator.remove();
                        }
                    }
                    map.put("codes", codes);
                }
            }
        }
        rs.put("patients", patientList);
        return rs;
    }
    public JSONObject getServerPatientListNum(Long teamCode, String level, String oldDoctorCode) {
        String serverSql = "SELECT " +
                " d.`code` As labelCode, " +
                " d.`name` AS label " +
                " FROM " +
                " wlyy_sign_dict d " +
                " WHERE " +
                " d.type IN ('1', '2') " +
                " AND d. YEAR = '" + DateUtil.getSignYear() + "' ";
        String patientSql = "SELECT  " +
                " f.patient, " +
                " s.server_type AS serverType, " +
                " s.server_type_name AS serverTypeName " +
                " FROM  " +
                " wlyy_sign_family_server s, " +
                "( " +
                " SELECT " +
                " s.patient, " +
                " s.`code` " +
                " FROM " +
                " wlyy_sign_family s " +
                " WHERE " +
                " s.`status` >= 0 " +
                " AND s.admin_team_code = " + teamCode;
        //1查询全科,其他查询健管师
        if ("2".equals(level)) {
            patientSql = patientSql + " AND s.doctor ='" + oldDoctorCode + "'";
        } else {
            patientSql = patientSql + " AND s.doctor_health ='" + oldDoctorCode + "'";
        }
        patientSql = patientSql + " ) f WHERE f.`code` =s.sign_code";
        List<Map<String, Object>> patientList = jdbcTemplate.queryForList(patientSql);
        String totalSql = " SELECT " +
                " s.patient " +
                " FROM " +
                " wlyy_sign_family s " +
                " WHERE " +
                " s.`status` >= 0 " +
                " AND s.admin_team_code =" + teamCode;
        //1查询全科,其他查询健管师
        if ("2".equals(level)) {
            totalSql = totalSql + " AND s.doctor ='" + oldDoctorCode + "'";
        } else {
            totalSql = totalSql + " AND s.doctor_health ='" + oldDoctorCode + "'";
        }
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        JSONObject rs = new JSONObject();
        rs.put("count", (totalList != null && totalList.size() > 0) ? totalList.size() : 0);
        List<Map<String, Object>> serlist = jdbcTemplate.queryForList(serverSql);
        if (serlist != null && serlist.size() > 0) {
            if (patientList != null) {
                for (Map<String, Object> map : serlist) {
                    String labelCode = (String) map.get("labelCode");
                    List<Map<String, String>> codes = new ArrayList<>();
                    Iterator iterator = patientList.iterator();
                    while (iterator.hasNext()) {
                        Map<String, Object> p = (Map<String, Object>) iterator.next();
                        String serverType = p.get("serverType") == null ? "" : ((String) p.get("serverType"));
                        if (labelCode.equals(serverType)) {
                            Map<String, String> code = new HashMap<>();
                            code.put("code", (String) p.get("patient"));
                            codes.add(code);
                            iterator.remove();
                        }
                    }
                    map.put("codes", codes);
                    map.put("number", (codes != null && codes.size() > 0) ? codes.size() : 0);
                }
            }
        }
        rs.put("patients", serlist);
        return rs;
    }
    public List<Map<String, Object>> patientGroupByServerType(String doctor) {
        // 先根据server_type分组查找wlyy_sign_family表中该医生的签约的患者,然后wlyy_sign_dict left join 得到全部的类型
        String sql = "SELECT " +
                " sd.CODE labelCode, " +
                " sd.NAME labelName, " +
                "  IFNULL(t.count,0) amount " +
                "FROM " +
                " wlyy_sign_dict sd " +
                "LEFT JOIN ( " +
                " SELECT " +
                "  s.server_type, " +
                "  s.server_type_name, " +
                "  COUNT(1) count " +
                " FROM " +
                "  wlyy_sign_family_server s, " +
                "  ( " +
                "   SELECT " +
                "    f. CODE " +
                "   FROM " +
                "    wlyy_sign_family f " +
                "   WHERE " +
                "    ( " +
                "     f.doctor = ? " +
                "     OR f.doctor_health = ?" +
                "    ) " +
                "   AND f.`status` > 0 " +
                "  ) f " +
                " WHERE " +
                "  s.sign_code = f.`code` " +
                " GROUP BY " +
                "  s.server_type " +
                ") t ON sd.CODE = t.server_type " +
                "WHERE " +
                " sd.`year` = '" + DateUtil.getSignYear() + "'";
        List<Map<String, Object>> queryData = jdbcTemplate.queryForList(sql, doctor, doctor);
        return queryData;
    }
    /**
     * 判断患者和医生是否有去年的签约记录
     *
     * @param patient
     * @param doctor
     * @return
     */
    public Map<String, Object> checkLastYearIsSign(String patient, String doctor) {
        String sql = "SELECT f.id,f.admin_team_code FROM wlyy_sign_family f WHERE f.doctor ='" + doctor + "' AND f.patient='" + patient + "' AND f.sign_year='" + (DateUtil.getSignYear() - 1) + "' AND f.`status`=-4 AND f.expenses_status ='1'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    /**
     * 查找医生所属团队下的某个居民
     *
     * @param teamCode
     * @param patientName
     * @param page
     * @param pageSize
     * @return
     */
    public List<Patient> signPatientsByName(Long teamCode, String patientName, Integer page, Integer pageSize) {
        StringBuffer sb = new StringBuffer("SELECT " +
                "  p.* " +
                " FROM " +
                "  wlyy_sign_family a ," +
                "  wlyy_patient p ," +
                "WHERE " +
                "  a.admin_team_code =? " +
                " AND a.patient=p.`code` " +
                " AND a.`status` IN (1, 2) ");
        List params = new ArrayList<>();
        params.add(teamCode);
        if (!org.springframework.util.StringUtils.isEmpty(patientName)) {
            sb.append(" AND a.`name` LIKE ? ");
            params.add("%" + patientName + "%");
        }
        pageSize = page * pageSize;
        page = (page - 1) * pageSize;
        sb.append(" limit " + page + "," + pageSize);
        List<Patient> patients = jdbcTemplate.query(sb.toString(), params.toArray(), new BeanPropertyRowMapper(Patient.class));
        return patients;
    }
    public Integer signPatientsByNameCount(Long teamCode, String patientName) {
        StringBuffer sb = new StringBuffer("SELECT " +
                "  p.* " +
                " FROM " +
                "  wlyy_sign_family a ," +
                "  wlyy_patient p ," +
                "WHERE " +
                "  a.patient=p.`code` " +
                " AND a.`status` IN (1, 2) ");
        List params = new ArrayList<>();
        if (teamCode != null && teamCode > 0) {
            sb.append(" AND a.admin_team_code =?  ");
            params.add(teamCode);
        }
        if (!org.springframework.util.StringUtils.isEmpty(patientName)) {
            sb.append(" AND a.`name` LIKE ? ");
            params.add("%" + patientName + "%");
        }
        Integer patients = jdbcTemplate.queryForObject(sb.toString(), params.toArray(), Integer.class);
        return patients;
    }
}

+ 1668 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java

@ -0,0 +1,1668 @@
package com.yihu.wlyy.web.doctor.account;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.profile.DoctorComment;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.organization.HospitalDept;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamDao;
import com.yihu.wlyy.repository.doctor.SignPatientLabelDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.hospital.HospitalDeptService;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.account.RoleService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdcardValidator;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * 用户注册的Controller.
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/doctor", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生")
public class DoctorController extends BaseController {
    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private HospitalDeptService hospitalDeptService;
    @Autowired
    private HospitalDeptService deptService;
    @Autowired
    private DoctorWorkTimeService workTimeService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    SignPatientLabelDao labelDao;
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private RSAUtils rsaUtils;
    /**
     * 社区医院下医生列表查询接口 没分页
     *
     * @param hospital 医院标识
     * @return
     */
    @ApiOperation("社区医院下医生列表查询接口 没分页")
    @RequestMapping(value = "getDoctorsByhospitalNoPage",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorsByhospitalNoPage(
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type) {
        try {
            JSONArray array = new JSONArray();
            List<Map<String, Object>> list = familyContractService.getDoctorsByhospitalNoPage(hospital, name, type);
            if (list != null) {
                for (Map<String, Object> doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.get("id"));
                    // 医生标识
                    json.put("code", doctor.get("code"));
                    // 医生姓名
                    json.put("name", doctor.get("name"));
                    // 所在医院名称
                    json.put("hospital", doctor.get("hospital"));
                    // 所在医院名称
                    json.put("hospital_name", doctor.get("hospital_name"));
                    // 科室名称
                    json.put("dept_name", (doctor.get("dept_name") == null ||
                            StringUtils.isEmpty(doctor.get("dept_name").toString())) ? " " : doctor.get("dept_name"));
                    // 职称名称
                    json.put("job_name", (doctor.get("job_name") == null ||
                            StringUtils.isEmpty(doctor.get("job_name").toString())) ? " " : doctor.get("job_name"));
                    // 头像
                    json.put("photo", doctor.get("photo"));
                    // 简介
                    json.put("introduce", doctor.get("introduce"));
                    // 专长
                    json.put("expertise", doctor.get("expertise"));
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院下医生列表查询接口 有分页
     *
     * @param hospital 医院标识
     * @return
     */
    @ApiOperation("社区医院下医生列表查询接口 有分页")
    @RequestMapping(value = "getDoctorsByhospital",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String getDoctorsByhospital(
            @RequestParam(required = false) String hospital, //医院code
            @RequestParam(required = false) String city, //市代码
            @RequestParam(required = false) String town, //区代码
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String name, //名称
            @RequestParam(required = true) Long id,
            @RequestParam(required = true) Integer pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = familyContractService.findDoctors(hospital, city, town, name, type, id, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHospitalName());
                    // 科室名称
                    json.put("dept_name", StringUtils.isEmpty(doctor.getDeptName()) ? " " : doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", StringUtils.isEmpty(doctor.getJobName()) ? " " : doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院列表查询接口
     *
     * @param type     医院类型:0全部,1大医院,2社区医院
     * @param province 患标识
     * @param city     城市标识
     * @param key      搜索关键字,用于搜索医院名称
     * @return
     */
    @ApiOperation("社区医院列表查询接口")
    @RequestMapping(value = "hospitals",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String hospitals(
            int type,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String town,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Hospital> list = familyContractService.findHospitals(type, province, city, town, key, id, pagesize);
            if (list != null) {
                for (Hospital hospital : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    // 医院标识
                    json.put("code", hospital.getCode());
                    // 医院名称
                    json.put("name", hospital.getName());
                    // 省名
                    json.put("province_name", hospital.getProvinceName());
                    // 城市名
                    json.put("city_name", hospital.getCityName());
                    // 区县名
                    json.put("town_name", hospital.getTownName());
                    // 详细地址
                    json.put("address", hospital.getAddress());
                    // 简介
                    json.put("intro", hospital.getIntro());
                    // 医院图片
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "获取医院列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院列表失败!");
        }
    }
    /**
     * 查询存在医生的医院列表
     *
     * @param type     类型 1:医院 2社区
     * @param province 省份
     * @param city     城市
     * @param town     城镇
     * @param key      名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @ApiOperation("查询存在医生的医院列表")
    @RequestMapping(value = "hospitals_list",method =RequestMethod.POST)
    @ResponseBody
    public String hospitalL(@RequestParam(required = true) int type,
                            @RequestParam(required = false) String province,
                            @RequestParam(required = false) String city,
                            @RequestParam(required = false) String town,
                            @RequestParam(required = false) String key,
                            @RequestParam(required = true) int page,
                            @RequestParam(required = true) int pagesize) {
        try {
            if (type != 1 && type != 2) {
                return error(-1, "医院类型错误");
            }
            page = page >= 1 ? page - 1 : 0;
            List<Hospital> hos = hospitalService.getHospitals(type, province, city, town, key,null, page, pagesize);
            return write(200, "查询成功", "data", hos);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询某个医院存在医生科室列表
     *
     * @param hospital 医院
     * @param key      科室名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @ApiOperation("查询某个医院存在医生科室列表")
    @RequestMapping(value = "/dept_list",method =RequestMethod.POST)
    @ResponseBody
    public String deptList(@RequestParam(required = true) String hospital,
                           @RequestParam(required = false) String key,
                           @RequestParam(required = true) int page,
                           @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(hospital)) {
                return error(-1, "医院不能为空");
            }
            page = page >= 1 ? page - 1 : 0;
            List<HospitalDept> dept = deptService.getHospitalDept(hospital, key, page, pagesize);
            return write(200, "查询成功", "data", dept);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据科室查询当前在工作医生
     *
     * @param dept
     * @param hospital
     * @param level
     * @param key
     * @param page
     * @param pagesize
     * @return
     */
    @ApiOperation("根据科室查询当前在工作医生")
    @RequestMapping(value = "/doctors_list",method =RequestMethod.POST)
    @ResponseBody
    public String findWorkingDoctorByDept(@RequestParam(required = false) String dept,
                                          @RequestParam(required = false) String hospital,
                                          @RequestParam(required = false, defaultValue = "1") String level,
                                          @RequestParam(required = false, defaultValue = "") String key,
                                          @RequestParam(required = false, defaultValue = "1") int page,
                                          @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (page >= 1) {
                page = page - 1;
            }
            JSONArray doctors = doctorInfoService.findWorkingDoctorListByDept(dept, hospital, level, key, page, pagesize);
            return write(200, "查询成功", "data", doctors);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据机构查找科室
     *
     * @param hospital 机构code
     * @param key      科室名称
     * @param id       主键
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("根据机构查找科室")
    @RequestMapping(value = "findDeptByHsoptail",method =RequestMethod.POST)
    @ResponseBody
    public String findDeptByHsoptail(
            String hospital,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<HospitalDept> list = hospitalDeptService.findDeptByHsoptail(hospital, key, id, pagesize);
            if (list != null) {
                for (HospitalDept dept : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", dept.getId());
                    // 科室标识
                    json.put("code", dept.getCode());
                    // 科室名称
                    json.put("name", dept.getName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 根据科室查找医生
     *
     * @param dept     科室code
     * @param key      医生名称
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("根据科室查找医生")
    @RequestMapping(value = "findDoctorByDept",method =RequestMethod.POST)
    @ResponseBody
    public String findDoctorByDept(
            @RequestParam(required = false) String dept,
            @RequestParam(required = false) String hosptial,
            @RequestParam(required = false) String key,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = doctorInfoService.findDoctorByDept(dept, hosptial, key, page, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 名医列表
     *
     * @param key      医生名称
     * @param type     是否是名医 1是  0不是
     * @param level    医生的等级 1专科医生,2全科医生,3健康管理师 不传默认是全部
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("名医列表")
    @RequestMapping(value = "findFamousDoctor",method =RequestMethod.POST)
    @ResponseBody
    public String findFamousDoctor(
            @RequestParam(required = false) String key,
            @RequestParam(required = false) Integer level,
            Integer type,
            int page,
            int pagesize) {
        try {
            com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
            List<Doctor> list = doctorInfoService.findFamousDoctorList(key, type, page, pagesize, level);
            if (list != null) {
                for (Doctor doctor : list) {
                    com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    json.put("expertise", doctor.getExpertise());
                    json.put("isworking", 1);
                    array.add(json);
                }
            }
            return write(200, "获取名医列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取名医列表失败!");
        }
    }
    /**
     * 退出登录
     *
     * @return
     */
    @ApiOperation("退出登录")
    @RequestMapping(value = "loginout",method =RequestMethod.POST)
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(2, getUID());
            return success("已成功退出!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @ApiOperation("医生基本信息查询接口")
    @RequestMapping(value = "baseinfo",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String baseinfo(
            @RequestParam(required = false) String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                code = getUID();
            }
            Doctor temp = doctorInfoService.findDoctorByCode(code);
            Integer leader = doctorAdminTeamDao.findLeader(code);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生手机号码
                json.put("mobile", temp.getMobile());
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", temp.getPhoto());
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院名称
                json.put("hospitalName", temp.getHospitalName());
                // 设置医院
                json.put("hospital", temp.getHospital());
                // 设置部门名称
                json.put("deptName", StringUtils.isNotEmpty(temp.getDeptName()) ? temp.getDeptName() : "");
                // 设置职称
                json.put("jobName", StringUtils.isNotEmpty(temp.getJobName()) ? temp.getJobName() : "");
                // 设置医生专长
                json.put("expertise", StringUtils.isNotEmpty(temp.getExpertise()) ? temp.getExpertise() : "");
                // 设置医生简介
                json.put("introduce", StringUtils.isNotEmpty(temp.getIntroduce()) ? temp.getIntroduce() : "");
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                // 审核总数
                json.put("signed_amount", familyContractService.countAmountSigned(code));
                // 等审核总数
                json.put("unsign_amount", familyContractService.countAmountUnsign(code));
                // 咨询统计
                Map<String, Long> consultCount = consultTeamService.getAllCount(code);
                // 咨询总数
                json.put("consultAmount", consultCount.get("all"));
                // 当天咨询数
                json.put("consultAmountToday", consultCount.get("today"));
                //身份类型
                json.put("level", temp.getLevel().intValue());
                //身份证号
                json.put("idcard", temp.getIdcard());
                //是否认证
                json.put("isCertified", temp.getIscertified());
                //是否名医
                json.put("isFamous", temp.getIsFamous());
                //是否医生提示 提示过是1 其他都是0
                json.put("isPasswordPrompt", StringUtils.isEmpty(temp.getIsPasswordPrompt()) ? "0" : temp.getIsPasswordPrompt());
                //获取医生角色和区域权限
                List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(temp.getCode());
                json.put("userRole", roleMap);
                json.put("evaluateScore", temp.getEvaluateScore());
//                是否团队长
                json.put("isLeader", leader == null ? "0" : "1");
//                团队长所管辖的团队code 一个团队长只管辖一个团队
                json.put("adminTeamCode", leader);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @ApiOperation("医生基本信息查询接口")
    @RequestMapping(value = "baseinfoCount",method =RequestMethod.POST)
    @ResponseBody
    public String baseinfoCount(
            String doctorType) {
        try {
            Doctor temp = doctorInfoService.findDoctorByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                int count = familyContractService.countAmountSigned(getUID());
                // 审核总数
                json.put("signed_amount", count);
                int count1 = familyContractService.countAmountUnsign(getUID());
                // 等审核总数
                json.put("unsign_amount", count1);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 患者基本信息保存
     *
     * @param photo     頭像
     * @param sex       性別
     * @param expertise 专长
     * @param introduce 简介
     * @param province  省标识
     * @param city      市标识
     * @return
     */
    @ApiOperation("患者基本信息保存")
    @RequestMapping(value = "save",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String save(
            @RequestParam(required = false) String photo,
            @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String expertise,
            @RequestParam(required = false) String introduce,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String mobile) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (StringUtils.isNotEmpty(mobile)) {
                if (!mobile.equals(doctor.getMobile())) {
                    if (doctorInfoService.findNormalByMobile(mobile) != null) {
                        return error(-2, "该手机号码已被注册!");
                    }
                    doctor.setMobile(mobile);
                }
            }
            // 设置头像
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
                if (StringUtils.isNotEmpty(photo)) {
                    doctor.setPhoto(photo);
                }
            }
            // 设置性别
            if (sex != null) {
                doctor.setSex(sex);
            }
            // 设置生日
            // if (StringUtils.isNotEmpty(birthday)) {
            // doctor.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
            // }
            // 设置医生专长
            if (StringUtils.isNotEmpty(expertise)) {
                doctor.setExpertise(expertise);
            }
            // 设置介绍内容
            if (StringUtils.isNotEmpty(introduce)) {
                doctor.setIntroduce(introduce);
            }
            // 设置省份标识
            if (StringUtils.isNotEmpty(province)) {
                doctor.setProvince(province);
            }
            // 设置城市标识
            if (StringUtils.isNotEmpty(city)) {
                doctor.setCity(city);
            }
            // 设置区县标识
            // if (StringUtils.isNotEmpty(town)) {
            // doctor.setTown(town);
            // }
            // 设置医院标识
            // if (StringUtils.isNotEmpty(hospital)) {
            // doctor.setHospital(hospital);
            // }
            // // 设置部门标识
            // if (StringUtils.isNotEmpty(dept)) {
            // doctor.setDept(dept);
            // }
            // // 设置职称
            // if (StringUtils.isNotEmpty(job)) {
            // doctor.setJob(job);
            // }
            if (doctorInfoService.updateDoctor(doctor) != null) {
                // 修改成功
                return write(200, "保存成功!", "data", doctor.getPhoto());
            } else {
                // 注册失败
                return error(-1, "保存失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 根据类别获取医院列表
     *
     * @param type
     * @param query    查询条件 医院名称
     * @param id
     * @param pageSize 页数
     * @return
     */
    @ApiOperation("根据类别获取医院列表")
    @RequestMapping(value = "/hospital_list",method =RequestMethod.POST)
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) Integer type,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) long id,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Hospital> hospitalList = hospitalService.getHospitalList(query, type, id, pageSize);
            JSONArray array = new JSONArray();
            if (hospitalList != null) {
                for (Hospital hospital : hospitalList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    json.put("code", hospital.getCode());
                    json.put("name", hospital.getName());
                    json.put("province", hospital.getProvince());
                    json.put("provinceName", hospital.getProvinceName());
                    json.put("city", hospital.getCity());
                    json.put("cityName", hospital.getCityName());
                    json.put("town", hospital.getTown());
                    json.put("townName", hospital.getTownName());
                    json.put("level", hospital.getLevel());
                    String levelName = "";
                    switch (hospital.getLevel()) {
                        case 1:
                            levelName = "医院";
                            break;
                        case 2:
                            levelName = "社区医院";
                            break;
                    }
                    json.put("levelName", levelName);
                    json.put("address", hospital.getAddress());
                    json.put("intro", hospital.getIntro());
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 邀请医生咨询
     *
     * @param patientCode
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation("根据类别获取医院列表")
    @RequestMapping(value = "/hospital_list_type",method =RequestMethod.POST)
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = true) int consultType,
            @RequestParam(required = true) String patientCode,
            @RequestParam(required = false) String name,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            if (doctorType == 3) {
                //查找所有的全科医生
                Doctor doctor = doctorInfoService.getDoctor(consultType, patientCode);
                return null;
            } else if (doctorType == 2) {
                //查找所有的专科医生
                Page<Doctor> doctorList = doctorInfoService.getDoctorListByPatientCode(consultType, patientCode, name, page, pageSize);
                JSONArray array = new JSONArray();
                if (doctorList != null) {
                    for (Doctor doctor : doctorList) {
                        JSONObject json = new JSONObject();
                        json.put("id", doctor.getId());
                        json.put("code", doctor.getCode());
                        json.put("name", doctor.getName());
                        json.put("photo", doctor.getPhoto());
                        json.put("sex", doctor.getSex());
                        String sexName = "";
                        switch (doctor.getSex()) {
                            case 1:
                                sexName = "男";
                                break;
                            case 2:
                                sexName = "女";
                                break;
                        }
                        json.put("sexName", sexName);
                        json.put("job", doctor.getJob());
                        json.put("jobName", doctor.getJobName());
                        json.put("hospital", doctor.getHospital());
                        json.put("hospitalName", doctor.getHospitalName());
                        json.put("dept", doctor.getDept());
                        json.put("deptName", doctor.getDeptName());
                        array.put(json);
                    }
                }
                return write(200, "查询成功!", "list", array);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            error(ex);
            return error(-1, "查询失败!");
        }
        return null;
    }
    /**
     * 根据医院标识获取医生信息
     *
     * @param hospital 医院标识
     * @param query    查询条件 :医生名称
     * @param page
     * @param pageSize 页数
     * @return
     */
    @ApiOperation("根据医院标识获取医生信息")
    @RequestMapping(value = "/doctor_list",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(query, hospital, page, pageSize,2);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("evaluateScore", doctor.getEvaluateScore());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * @param type 医生类别 1专科医生,2全科医生,3健康管理师
     * @return
     */
    @RequestMapping(value = "/doctor_combobox",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorCombobxByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String type) {
        try {
            List<Doctor> doctorList = doctorInfoService.getDoctorCombobxByHospital(type, hospital);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 患者端 专科医生列表
     *
     * @param name
     * @param paitentCode
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation("专科医生列表")
    @RequestMapping(value = "/doctor_1_list",method =RequestMethod.POST)
    @ResponseBody
    public String doctor_1_list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String paitentCode,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(name, null, page, pageSize,1);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
//					json.put("photo", doctor.getPhoto());
//					json.put("sex", doctor.getSex());
//					String sexName = "";
//					switch (doctor.getSex()) {
//						case 1:
//							sexName = "男";
//							break;
//						case 2:
//							sexName = "女";
//							break;
//					}
//					//json.put("sexName", sexName);
//					json.put("job", doctor.getJob());
//					json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
//					json.put("dept", doctor.getDept());
//					json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 把专科医生拉到团队里面
     *
     * @param teamCode   团队code
     * @param doctor     专科医生code
     * @param sickNCode  慢病code
     * @param sickName   慢病名字
     * @param doctorName 专科医生名字
     * @return
     */
    @ApiOperation("把专科医生拉到团队里面")
    @RequestMapping(value = "/doctor_1_Toteam",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String doctor_1_Toteam(
            @RequestParam(required = false) String teamCode, //没用
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = false) String groupCode,//没用
            @RequestParam(required = true) String doctor,
            @RequestParam(required = true) String doctorName,
            @RequestParam(required = true) String sickName,
            @RequestParam(required = true) String sickNCode) {
        try {
            doctorInfoService.doctor_1_Toteam(teamCode, doctor, doctorName, groupCode, super.getIMEI(), parientCode, sickName, sickNCode);
            return write(200, "成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个
     *
     * @param parientCode 病人code
     * @return
     */
    @ApiOperation("根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个")
    @RequestMapping(value = "/getDoctor1ByParient",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctor1ByParient(
            @RequestParam(required = true) String consultCode,
            @RequestParam(required = true) String parientCode,
            Integer page,
            Integer pageSize) {
        try {
            Map<String, Object> doctorList = doctorInfoService.getDoctor1ByParient(consultCode, parientCode, page, pageSize);
            JSONObject jo = new JSONObject();
            List<JSONObject> doctors = doctorList.get("doctors") != null ? (List<JSONObject>) doctorList.get("doctors") : new ArrayList<>();
            for (JSONObject obj : doctors) {
                JSONObject iswork = workTimeService.isDoctorWorking(obj.getString("code"));
                if (iswork.getString("status").equals("1")) {
                    obj.put("isworking", 1);
                } else {
                    obj.put("isworking", 0);
                }
            }
            jo.put("totalPage", doctorList.get("totalPage"));
            jo.put("doctors", doctors);
            return write(200, "查询成功!", "data", jo);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 验证患者的名字,身份证和医保卡
     *
     * @return
     */
    @ApiOperation("验证患者的名字,身份证和医保卡")
    @RequestMapping(value = "/validatePatient",method =RequestMethod.POST)
    @ResponseBody
    public String validatePatient(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) String idcard,
            @RequestParam(required = true) String ssc) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致,请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0 && ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                    return error(-1, "您的社保卡不支持线上签约,请到社区卫生服务中心办理线下签约");
                }
            } else {
                return error(-1, "您的社保卡不支持线上签约,请到社区卫生服务中心办理线下签约");
            }
            return write(200, "查询成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据level查找机构下的类别医生
     *
     * @param hospital
     * @param level
     * @return
     */
    @ApiOperation("根据level查找机构下的类别医生")
    @RequestMapping(value = "/findDoctorByLevelAndHospital",method =RequestMethod.POST)
    @ResponseBody
    public String findDoctorByLevelAndHospital(String hospital, Integer level) {
        try {
            List<Doctor> doctorList = doctorInfoService.findDoctorByLevelAndHospital(hospital, level);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "doctors", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 更新身份证号
     *
     * @param idcard
     * @return
     */
    @ApiOperation("更新身份证号")
    @RequestMapping(value = "/idcard_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateIdcard(String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateDoctorIdcard(idcard, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生性别
     *
     * @param sex
     * @return
     */
    @ApiOperation("更新医生性别")
    @RequestMapping(value = "/sex_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateSex(int sex) {
        try {
            if (doctorInfoService.updateSex(sex, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生介绍
     *
     * @param introduce
     * @return
     */
    @ApiOperation("更新医生介绍")
    @RequestMapping(value = "/introduce_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateIntroduce(String introduce) {
        try {
            if (StringUtils.isEmpty(introduce)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateIntroduce(introduce, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生专长
     *
     * @param expertise
     * @return
     */
    @ApiOperation("更新医生专长")
    @RequestMapping(value = "/expertise_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateExpertise(String expertise) {
        try {
            if (StringUtils.isEmpty(expertise)) {
                return error(-1, "专长不能为空");
            }
            if (doctorInfoService.updateExpertise(expertise, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "更新失败");
        }
    }
    /**
     * 设置给医生名医
     *
     * @param doctorCode 医生code
     * @param status     1 是 0否
     * @return
     */
    @ApiOperation("设置给医生名医")
    @RequestMapping(value = "/setFamous",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String setFamous(String doctorCode, Integer status) {
        try {
            doctorInfoService.setFamous(doctorCode, status);
            return write(200, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 医生手机号变更
     *
     * @param mobile  新手机号
     * @param captcha 验证码
     * @param type    1:变更手机号  2:绑定手机号
     * @return
     */
    @ApiOperation("医生手机号变更")
    @RequestMapping(value = "/mobile_update", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String changeDoctorMobile(String mobile, String captcha, int type) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "请填写新手机号码");
            }
            if (StringUtils.isEmpty(captcha)) {
                return error(-1, "请输入验证码");
            }
            if (type != 1 && type != 2) {
                return error(-1, "操作类型参数错误");
            }
            int result = doctorInfoService.changeMobile(getUID(), mobile, captcha, type);
            if (result == -1) {
                return error(-1, "医生信息查找失败");
            } else if (result == -2) {
                return error(-1, "手机已注册");
            } else if (result == -3) {
                return error(-1, "验证码错误");
            } else if (result == 1) {
                return write(200, "手机号更新成功");
            } else {
                return write(-1, "手机号更新失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "手机号更新失败");
        }
    }
    /**
     * 手机号是否注册
     *
     * @param mobile 手机号
     * @return
     */
    @ApiOperation("手机号是否注册")
    @RequestMapping(value="/is_mobile_register",method =RequestMethod.POST)
    @ResponseBody
    public String isMobileRegister(String mobile) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号码不能为空");
            }
            int result = doctorInfoService.isMobileRegister(mobile);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 修改密码
     *
     * @param newPassword1 新密码1
     * @param newPassword2 新密码2
     * @param oldPassword  旧密码
     * @param doctorCode   医生code
     * @return
     */
    @ApiOperation("修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updatePassword(String newPassword1,
                                 String newPassword2,
                                 String oldPassword,
                                 String doctorCode) {
        try {
            rsaUtils.setBaseService(doctorInfoService);
            newPassword1 = rsaUtils.decryptString(newPassword1);
            newPassword2 = rsaUtils.decryptString(newPassword2);
            oldPassword = rsaUtils.decryptString(oldPassword);
            newPassword1 = StringUtils.reverse(newPassword1);
            newPassword2 = StringUtils.reverse(newPassword2);
            oldPassword = StringUtils.reverse(oldPassword);
            doctorInfoService.updatePassword(newPassword1, newPassword2, oldPassword, doctorCode);
            return write(200, "更新成功");
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 当前医生是否与居民签约
     *
     * @param patient
     * @return
     */
    @ApiOperation("当前医生是否与居民签约")
    @RequestMapping(value = "/is_patient_signed",method =RequestMethod.GET)
    @ResponseBody
    public String isPatientSign(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }
            boolean isSigned = doctorInfoService.isPatientSigned(patient, getUID());
            return write(200, "查询成功", "data", isSigned ? "1" : "0");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 心跳接口
     *
     * @return
     */
    @ApiOperation("心跳接口")
    @RequestMapping(value = "/islive",method =RequestMethod.POST)
    @ResponseBody
    public String islive() {
        try {
            return write(200, "成功");
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
//    /**
//     * 修改审方密码
//     * @param oldPassword
//     * @param newPassword
//     * @return
//     */
//    @ObserverRequired
//    @ResponseBody
//    @RequestMapping(value = "/updateCheckPassword", method = RequestMethod.POST)
//    public String updateCheckPassword(@RequestParam String oldPassword,@RequestParam String newPassword){
//
//        try {
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "修改审方密码失败!");
//            } else {
//                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(doctor.getCheckSalt()), oldPassword);
//                if (StringUtils.equals(doctor.getCheckPassword(), encodePWD)) {
////                    doctorInfoService.setCheckPassword(doctor,newPassword);
//                    return write(200, "密码设置成功");
//                } else {
//                    return error(-1, "修改失败:审方旧密码错误!");
//                }
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "修改失败!");
//        }
//    }
    //获取实名软证书的过期时间
    @ApiOperation("获取实名软证书的过期时间")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/getAuthenticationCAOvertime", method = RequestMethod.GET)
    public String getAuthenticationCAOvertime(){
        try {
//            Doctor doctor = doctorInfoService.findDoctorByCode(getRepUID());
            JSONObject data = doctorInfoService.getCAPastDue(getUID(),new JSONObject());
            return write(200, "获取信息成功!", "data", data);
        }catch (Exception e) {
            error(e);
            return error(-1, "获取信息失败!");
        }
    }
    //判断是否在线上安装证书
    @ObserverRequired
    @ApiOperation("判断是否在线上安装证书")
    @ResponseBody
    @RequestMapping(value = "/isAuthentication", method = RequestMethod.GET)
    public String isAuthentication(){
        try {
            //0de6a26a62dd11e69faffa163e8aee56
            JSONObject data = doctorInfoService.isAuthentication(getUID());
            return write(200, "获取信息成功!", "data", data);
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    //修改实名软证书调用保护口令
    @ApiOperation("修改实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/updateAuthenticationPassword", method = RequestMethod.POST)
    public String updateAuthenticationPassword(
            @RequestParam(value = "strOldCalledPasswd",required = true) String strOldCalledPasswd,
            @RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),strOldCalledPasswd,strNewCalledPasswd,getUID());//hxmD201703150222
            if(b){
                return write(200, "修改密码成功!", "data", b);
            }
            return error(-1, "修改密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 初始设置实名软证书调用保护口令
     */
    @ApiOperation("初始设置实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/installAuthenticationPassword", method = RequestMethod.POST)
    public String installAuthenticationPassword(@RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            String strOldCalledPasswd = StringUtils.isNotEmpty(doctor.getCheckPassword())?doctor.getCheckPassword():"11111111";
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),strOldCalledPasswd,strNewCalledPasswd,getUID());
            if(b){
                return write(200, "设置密码成功!", "data", b);
            }
            return error(-1, "设置密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 重置密码
     */
    @ApiOperation("重置实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/resetAuthenticationPassword", method = RequestMethod.POST)
    public String resetAuthenticationPassword(@RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),doctor.getCheckPassword(),strNewCalledPasswd,getUID());
            if(b){
                return write(200, "重置密码成功!", "data", b);
            }
            return error(-1, "重置密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 请求实名软证书并进行数字签名
     */
    @ApiOperation("请求实名软证书并进行数字签名")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/requestRealNameSoftCertAndSign", method = RequestMethod.POST)
    public String requestRealNameSoftCertAndSign(
            @ApiParam(required = true, name = "strRealNameSoftCertCalledPasswd", value = "证书被调用保护口令") @RequestParam(value = "strRealNameSoftCertCalledPasswd",required = true) String strRealNameSoftCertCalledPasswd,
            @ApiParam(required = true, name = "strOriginalData", value = "原文") @RequestParam(value = "strOriginalData",required = true) String strOriginalData,
            @ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode",required = true) String prescriptionCode){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            JSONObject obj = doctorInfoService.requestRealNameSoftCertAndSign(doctor.getIdcard(),strRealNameSoftCertCalledPasswd,strOriginalData,srcBusinessStreamNO);
            JSONObject jsonObject = doctorInfoService.requestRealNameSoftCertAndSign(doctor.getIdcard(),strRealNameSoftCertCalledPasswd,strOriginalData,prescriptionCode);
//            if(b){
            return write(200, "获取信息成功!", "data", jsonObject);
//            }
//            return error(-1, "认证失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 校验医师输入的CA证书是否正确
     * @return
     */
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/checkCertificate", method = RequestMethod.GET)
    @ApiOperation("校验医师输入的身份证是否正确")
    public String checkCertificate(
            @ApiParam(required = true, name = "certificateNum", value = "证书编号") @RequestParam(value = "certificateNum",required = true) String certificateNum){
        try {
            boolean b = doctorInfoService.checkCertificate(getUID(),certificateNum);
            return write(200, "获取信息成功!", "data", b);
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 验证签名( ( 带多服务器负载均衡) )
     */
    @ApiOperation("验证签名")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/verifySignOnMultiServer", method = RequestMethod.GET)
    public String verifySignOnMultiServer(
            @ApiParam(required = true, name = "strSignData", value = "签名值") @RequestParam(value = "strSignData",required = true) String strSignData,
            @ApiParam(required = true, name = "strCertData", value = "证书主体数据") @RequestParam(value = "strCertData",required = true) String strCertData,
            @ApiParam(required = true, name = "strOriginalData", value = "原文数据") @RequestParam(value = "strOriginalData",required = true) String strOriginalData){
            try {
                boolean bl = doctorInfoService.verifySignOnMultiServer(strSignData,strCertData,strOriginalData,getUID());
                return write(200, "获取信息成功!", "data", bl);
            }catch (Exception e) {
                error(e);
                return error(-1, e.getMessage());
            }
    }
    @ApiOperation("取消认证")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/cancelAuthentication", method = RequestMethod.GET)
    public String cancelAuthentication(){
        try {
            if(doctorInfoService.cancelAuthentication(getUID())){
                return write(200, "取消认证成功!");
            }else{
                return error(-1, "取消认证失败!");
            }
        }catch (Exception e) {
            error(e);
            return error(-1, "取消认证失败!");
        }
    }
}

+ 2 - 0
patient-co/patient-co-doctor-assistant/src/main/resources/application-dev.yml

@ -50,6 +50,8 @@ wechat:
   template_consult_reply: x7fIXWcd1YsXAnwhP-gmW1D__GtzD39j5KZLudoe0Y0
   #代办事项提醒
   template_schedule_remind: z32DERzD6X4ShOl86sI3YCOWl-lkr5Z9sKh1w_YG8Bs
   #服务待处理提醒
   template_service_remind:  v2iqCHvqNLiU0PBBMIEPkB40xi8eUtdpsjwyxw-euo4
yihu:
  yihu_OpenPlatform_url: http://ssotest.yihu.cn/OpenPlatform/cgiBin/1.0/

+ 2 - 0
patient-co/patient-co-doctor-assistant/src/main/resources/application-devtest.yml

@ -50,6 +50,8 @@ wechat:
   template_consult_reply: x7fIXWcd1YsXAnwhP-gmW1D__GtzD39j5KZLudoe0Y0
   #代办事项提醒
   template_schedule_remind: z32DERzD6X4ShOl86sI3YCOWl-lkr5Z9sKh1w_YG8Bs
   #服务待处理提醒
   template_service_remind:  v2iqCHvqNLiU0PBBMIEPkB40xi8eUtdpsjwyxw-euo4
yihu:

+ 2 - 0
patient-co/patient-co-doctor-assistant/src/main/resources/application-local.yml

@ -50,6 +50,8 @@ wechat:
   template_consult_reply: x7fIXWcd1YsXAnwhP-gmW1D__GtzD39j5KZLudoe0Y0
   #代办事项提醒
   template_schedule_remind: z32DERzD6X4ShOl86sI3YCOWl-lkr5Z9sKh1w_YG8Bs
   #服务待处理提醒
   template_service_remind:  v2iqCHvqNLiU0PBBMIEPkB40xi8eUtdpsjwyxw-euo4
yihu:

+ 2 - 0
patient-co/patient-co-doctor-assistant/src/main/resources/application-localtest.yml

@ -50,6 +50,8 @@ wechat:
   template_consult_reply: x7fIXWcd1YsXAnwhP-gmW1D__GtzD39j5KZLudoe0Y0
   #代办事项提醒
   template_schedule_remind: z32DERzD6X4ShOl86sI3YCOWl-lkr5Z9sKh1w_YG8Bs
   #服务待处理提醒
   template_service_remind:  v2iqCHvqNLiU0PBBMIEPkB40xi8eUtdpsjwyxw-euo4
yihu:

+ 2 - 0
patient-co/patient-co-doctor-assistant/src/main/resources/application-test.yml

@ -49,6 +49,8 @@ wechat:
   template_consult_reply: x7fIXWcd1YsXAnwhP-gmW1D__GtzD39j5KZLudoe0Y0
   #代办事项提醒
   template_schedule_remind: z32DERzD6X4ShOl86sI3YCOWl-lkr5Z9sKh1w_YG8Bs
   #服务待处理提醒
   template_service_remind:  v2iqCHvqNLiU0PBBMIEPkB40xi8eUtdpsjwyxw-euo4
yihu:
  yihu_OpenPlatform_url: http://ssotest.yihu.cn/OpenPlatform/cgiBin/1.0/

+ 3 - 1
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/Application.java

@ -1,8 +1,11 @@
package com.yihu.wlyy;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.web.ErrorPageFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@ -18,7 +21,6 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
        transactionManagerRef = "wlyyTransactionManager")
public class Application {
    public static ApplicationContext ctx = null;
    public static void main(String[] args) {
        ctx = SpringApplication.run(Application.class, args);
    }

+ 56 - 21
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java

@ -1,22 +1,22 @@
package com.yihu.wlyy.statistics.config;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 * Created by Administrator on 2016.10.20.
@ -61,22 +61,21 @@ public class DataSourceConfig {
    private String filters;
    @Value("${spring.datasource.primaryReadWrite.url}")
    private String primaryReadWriteUrl;
    @Value("${spring.datasource.primaryReadWrite.username}")
    private String primaryReadWriteUsername;
    @Value("${spring.datasource.primaryReadWrite.password}")
    private String primaryReadWritePassword;
    /**
     *  主数据源
     * 主数据源
     *
     * @return
     */
    @Bean(name = "primaryReadWrite")
    @Primary//主库 默认不写名字用这个
    public DataSource primaryReadWriteDataSource() throws SQLException {
    public DataSource primaryReadWriteDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadWriteUrl);
        datasource.setUsername(primaryReadWriteUsername);
@ -100,11 +99,16 @@ public class DataSourceConfig {
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    @Value("${spring.datasource.primaryRead.url}")
    private String primaryReadUrl;
    @Value("${spring.datasource.primaryRead.username}")
@ -113,7 +117,7 @@ public class DataSourceConfig {
    private String primaryReadPassword;
    @Bean(name = "primaryRead")
    public DataSource primaryReadDataSource() throws SQLException {
    public DataSource primaryReadDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadUrl);
        datasource.setUsername(pprimaryReadUsername);
@ -137,7 +141,12 @@ public class DataSourceConfig {
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
@ -148,8 +157,10 @@ public class DataSourceConfig {
    private String imUsername;
    @Value("${spring.datasource.im.password}")
    private String imPassword;
    @Bean(name = "imData")
    public DataSource imDataSource()throws SQLException  {DruidDataSource datasource = new DruidDataSource();
    public DataSource imDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(imUrl);
        datasource.setUsername(imUsername);
        datasource.setPassword(imPassword);
@ -172,35 +183,59 @@ public class DataSourceConfig {
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    private Properties properties() {
        Properties properties = new Properties();
        properties.put("druid.stat.mergeSql", "true");
        properties.put("slowSqlMillis", "1000");
        return properties;
    }
    //------------------------------------druid 监控----------------------------------------------
    @Bean
    public ServletRegistrationBean statViewServlet(){
    public ServletRegistrationBean statViewServlet() {
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //设置ip白名单
        //servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
       // servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        // servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername","jkzl");
        servletRegistrationBean.addInitParameter("loginPassword","jkzlehr");
        servletRegistrationBean.addInitParameter("loginUsername", "jkzl");
        servletRegistrationBean.addInitParameter("loginPassword", "jkzlehr");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable","false");
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean statFilter(){
    public FilterRegistrationBean filterRegistrationBean(WebStatFilter webStatFilter) {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
    @Bean
    public StatFilter statFilter() {
        return new StatFilter();
    }
    @Bean
    public WebStatFilter webStatFilter() {
        return new WebStatFilter();
    }
    //------------------------------------druid 监控----------------------------------------------
}

+ 3 - 4
patient-co/patient-co-statistics-es/src/main/resources/application.yml

@ -24,13 +24,12 @@ spring:
    testWhileIdle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    minEvictableIdleTimeMillis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    timeBetweenEvictionRunsMillis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
    poolPreparedStatements: false # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true # 打开PSCache,并且指定每个连接上PSCache的大小
    maxPoolPreparedStatementPerConnectionSize: 50
    removeAbandoned: false #超过时间限制是否回收
    removeAbandonedTimeout: 7200 #超时时间;单位为秒。180秒=3分钟
    logAbandoned: false #关闭abanded连接时输出错误日志
    #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
    filters: stat, wall, log4j
    filters: stat,wall,logback #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
    # REDIS
  redis:
    database: 0 # Database index used by the connection factory.
@ -65,7 +64,7 @@ logging:
hibernate:
  dialect: org.hibernate.dialect.MySQL5Dialect
  show_sql: false
  show_sql: true
  ejb:
    naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java

@ -66,7 +66,7 @@ public interface PatientDao extends PagingAndSortingRepository<Patient, Long> {
    @Query("select distinct p.openid from Patient p where p.openid is not null and p.openid <> '' ")
    List<String> findOpenids();
    @Query(value=" select p.* from wlyy_patient p  LEFT JOIN wlyy_sign_family s on s.patient = p.code  RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code WHERE sp.status = 1 and s.status > 0 and sp.label_type = 3 and (sp.label = 1 or sp.label = 2)  and s.admin_team_code = ?1 and (s.doctor = ?2 or s.doctor_health =?2))",nativeQuery = true)
    @Query(value=" select DISTINCT p.* from wlyy_patient p  LEFT JOIN wlyy_sign_family s on s.patient = p.code  RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code WHERE sp.status = 1 and s.status > 0 and sp.label_type = 3 and (sp.label = 1 or sp.label = 2)  and s.admin_team_code = ?1 and (s.doctor = ?2 or s.doctor_health =?2)",nativeQuery = true)
    List<Patient> findAllSignPatientTeamcode(String teamcode, String  doctorcode);
    @Query(value="SELECT DISTINCT t.* FROM wlyy_sign_family t1,wlyy_patient t WHERE t.`code`=t1.patient AND t1.STATUS>0 AND " +

+ 44 - 38
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java

@ -12,6 +12,7 @@ import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientAimSports;
import com.yihu.wlyy.entity.patient.PatientHealthStandard;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.vo.PatientVO;
import com.yihu.wlyy.health.repository.DevicePatientHealthIndexDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
@ -954,8 +955,13 @@ public class PatientHealthIndexService extends BaseService {
    public void handlePatientStandarStatus(DevicePatientHealthIndex obj) {
        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----START
        String patientCode = obj.getUser();
        //患者信息
        Patient patient = patientDao.findByCode(patientCode);
	    //患者信息
	    Patient p = patientDao.findByCode(patientCode);
	
	    PatientVO patient = new PatientVO();
	    String patientsql = "select group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 and (label = 1 or label = 2) and patient = '"+p.getCode()+"' GROUP BY patient";
	
	    String patientdisease = jdbcTemplate.queryForObject(patientsql,String.class);
        int bloodPressureBbnormalCount = 0;//血压异常次数
        int bloodSuggurBbnormalCount = 0;//血糖异常次数
@ -977,42 +983,42 @@ public class PatientHealthIndexService extends BaseService {
                bloodSuggurBbnormalCount++;
            }
        }
        //连续3次异常,修改用户为预警状态
        if ((bloodPressureBbnormalCount >= 3 || bloodSuggurBbnormalCount >= 3) && (patient.getStandardStatus() == null || 0 == patient.getStandardStatus())) {
            patient.setStandardStatus(1);
        } else {
            Date end = new Date();
            Date start = DateUtil.setDateTime(end, -7);
            //计算血糖或者血压一周内的异常记录数量
            int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start, end, 1, patientCode);
            if (errorCount >= 5) {//超过5次,记为预警状态
                patient.setStandardStatus(1);
            }
        }
        //连续5次正常,修改用户为非预警状态
        if (patient.getDisease() != null) {
            if (1 == patient.getDisease()) {
                if (0 == bloodPressureBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
                    patient.setStandardStatus(0);
                }
            } else if (2 == patient.getDisease()) {
                if (0 == bloodSuggurBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
                    patient.setStandardStatus(0);
                }
            } else if (3 == patient.getDisease()) {
                if (0 == bloodSuggurBbnormalCount && 0 == bloodPressureBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
                    patient.setStandardStatus(0);
                }
            }
        } else {
            patient.setStandardStatus(0);
        }
        patientDao.save(patient);
        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
	
	
	    //连续3次异常,修改用户为预警状态
	    if ((bloodPressureBbnormalCount >= 3 || bloodSuggurBbnormalCount >= 3) && (patient.getStandardStatus() == null || 0 == patient.getStandardStatus())) {
		    p.setStandardStatus(1);
	    } else {
		    Date end = new Date();
		    Date start = DateUtil.setDateTime(end, -7);
		    //计算血糖或者血压一周内的异常记录数量
		    int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start, end, 1, patientCode);
		    if (errorCount >= 5) {//超过5次,记为预警状态
			    p.setStandardStatus(1);
		    }
	    }
	
	    //连续5次正常,修改用户为非预警状态
	    if (StringUtils.isNotBlank(patientdisease)) {
		    if ("1".equals(patientdisease)) {
			    if (0 == bloodPressureBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
				    p.setStandardStatus(0);
			    }
		    } else if ("2".equals(patientdisease)) {
			    if (0 == bloodSuggurBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
				    p.setStandardStatus(0);
			    }
		    } else if ("1,2".equals(patientdisease) || "2,1".equals(patientdisease)) {
			    if (0 == bloodSuggurBbnormalCount && 0 == bloodPressureBbnormalCount && (patient.getStandardStatus() == null || 1 == patient.getStandardStatus())) {
				    p.setStandardStatus(0);
			    }
		    }
	    } else {
		    p.setStandardStatus(0);
	    }
	
	    patientDao.save(p);
	    //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
    }

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionExpressageService.java

@ -547,7 +547,7 @@ public class PrescriptionExpressageService extends BaseService {
            p.setDrugDeliveryOperatorName(d.getName());
            p.setDrugDeliveryReason(reason);
            p.setDrugDeliveryReasonCode(reasonCode);
            p.setDrugDeliveryOperatorName(reasonName);
            p.setDrugDeliveryReasonValue(reasonName);
            p.setDrugDeliveryTime(new Date());
            prescriptionDao.save(p);

+ 4 - 4
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionFollowupContentService.java

@ -299,7 +299,7 @@ public class PrescriptionFollowupContentService extends BaseService {
		Date imBloodSugarDate = new Date();
		
		int total = 0;
		String sql = "select sum(category_code) amount FROM wlyy_patient_device WHERE user='"+prescription.getPatient()+"'";
		String sql = "SELECT count(id) amount FROM wlyy_patient_device where  user='"+prescription.getPatient()+"' AND category_code = 1";
		List<Map<String,Object>> result =  jdbcTemplate.queryForList(sql);
		if (result != null && result.size() > 0) {
			if(result.get(0).get("amount") != null){
@ -307,7 +307,7 @@ public class PrescriptionFollowupContentService extends BaseService {
				total = (result.get(0).get("amount") != null ? amount.intValue() : 0);
			}
		}
		if(total != 1 && total !=3){
		if(total == 0){
			contentDoctor.put("deviceMsg","您未绑定血糖智能设备,请手动上传体征数据,绑定设备后系统将会自动将您的体征数据上报给医生");
		}
		
@ -489,7 +489,7 @@ public class PrescriptionFollowupContentService extends BaseService {
		org.json.JSONObject contentPatient = new org.json.JSONObject();
		
		int total = 0;
		String sql = "select sum(category_code) amount FROM wlyy_patient_device WHERE user='"+prescription.getPatient()+"'";
		String sql = "SELECT count(id) amount FROM wlyy_patient_device where  user='"+prescription.getPatient()+"' AND category_code = 2";
		List<Map<String,Object>> result =  jdbcTemplate.queryForList(sql);
		if (result != null && result.size() > 0) {
			if(result.get(0).get("amount") != null){
@ -497,7 +497,7 @@ public class PrescriptionFollowupContentService extends BaseService {
				total = (result.get(0).get("amount") != null ? amount.intValue() : 0);
			}
		}
		if(total != 2 && total !=3 ){
		if(total == 0){
			contentDoctor.put("deviceMsg","您未绑定血压智能设备,请手动上传体征数据,绑定设备后系统将会自动将您的体征数据上报给医生");
		}
		

+ 2 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java

@ -396,11 +396,10 @@ public class DoctorSchemeService {
//        List<Patient> patients = patientDao.findAllSignPatientTeamcode(teamCode,doctorcode);
        List<PatientVO> patients = new ArrayList<>();
        String patientsql = "select p.*,b.deviceType as deviceType,group_concat(sp.label) as disease from wlyy_patient p " +
        String patientsql = "select p.code,p.standard_status,p.disease_condition,group_concat(sp.label) as disease from wlyy_patient p " +
                "  LEFT JOIN wlyy_sign_family s on s.patient = p.code " +
                "  RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code and sp.label_type = 3 and (sp.label = 1 or sp.label = 2) and sp.status =1" +
                "  LEFT JOIN (select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user) b on p.code = b.user " +
                "WHERE s.status > 0 and s.admin_team_code ='"+teamCode+"' and (s.doctor = '"+doctorcode+"' or s.doctor_health ='"+doctorcode+"') GROUP BY p.code";
                " WHERE s.status > 0 and s.admin_team_code ='"+teamCode+"' and (s.doctor = '"+doctorcode+"' or s.doctor_health ='"+doctorcode+"') GROUP BY p.code";
        patients= jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));

+ 3 - 9
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/call/CustomerService.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.repository.call.CallServiceDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -151,14 +152,7 @@ public class CustomerService extends BaseService{
	}
	/**
	 *     private Integer dealReason; // 处理取消原因:0.没有号源、1.病人取消
	 private String orderHospital; //预约医院code
	 private String orderHospitalName; //预约医院
	 private String orderDept; //预约科室code
	 private String orderDeptName; //预约科室名称
	 private String orderDoctor; //预约医生code
	 private String orderDoctorName; //预约医生名称
	 private String orderTime; //预约时间段
	 *
	 * @param type
	 * @param orderHospital
     * @return
@ -176,7 +170,7 @@ public class CustomerService extends BaseService{
			cs.setOrderHospitalName(orderHospitalName);
			cs.setOrderTime(orderTime);
			cs.setDealTime(new Date());
			cs.setRegisterTime(new Date());
			cs.setRegisterTime(DateUtil.stringToDate(registerTime,"yyyy-MM-dd HH:mm:ss"));
			cs.setDealState(1);
		//预约失败
		}else{

+ 3 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/call/CallRecordController.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.web.doctor.call;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.service.call.CustomerService;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.web.BaseController;
@ -73,6 +74,7 @@ public class CallRecordController extends BaseController {
    @RequestMapping(value = "/dealConsultCallService", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "处理咨询协同服务")
    @ObserverRequired
    public String dealConsultCallService(@ApiParam(name="code",value="协同服务code(Mes中relationCode)")@RequestParam(required = true)String code,
                                         @ApiParam(name="dealType",value="处理方式:1.电话回复,2.客服回复")@RequestParam(required = true)Integer dealType,
                                         @ApiParam(name="dealState",value="处理结果:1.完成,2.无法联系居民")@RequestParam(required = true)Integer dealState,
@ -87,6 +89,7 @@ public class CallRecordController extends BaseController {
    @RequestMapping(value = "/dealAppointCallService", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "处理预约协同服务")
    @ObserverRequired
    public String dealAppointCallService(@ApiParam(name="type",value="1.预约成功,2.预约失败")@RequestParam(required = true)String type ,
                                         @ApiParam(name="code",value="协同服务code(Mes中relationCode)")@RequestParam(required = false)String code,
                                         @ApiParam(name="dealReason",value="预约失败原因code")@RequestParam(required = false)Integer dealReason,

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java

@ -845,7 +845,7 @@ public class SignPatientLabelInfoController extends BaseController {
            @ApiParam(name="startdate", value="体征数据开始时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "startdate",required = false,defaultValue = "2017-9-10 00:00:00")  String startdate,
            @ApiParam(name="enddate", value="体征数据结束时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "enddate",required = false,defaultValue = "2017-9-16 23:59:59")  String enddate){
        try {
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate,"zbqD201703150226");
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate,getUID());
            return write(200, "查询成功", "data", result);
        }catch (Exception e){
            //日志文件中记录异常信息

+ 6 - 3
patient-co/patient-co-wlyy/src/main/resources/config/fdfs_client.conf

@ -12,8 +12,11 @@ http.secret_key = FastDFS1234567890
#tracker_server = 172.19.103.54:22122
#-------------正式环境---------------#
tracker_server = 192.168.120.172:22122 #外网项目地址
#tracker_server = 59.61.92.90:9055  #网闸
#tracker_server = 10.95.22.139:22122  #内网项目地址
#外网项目地址
tracker_server = 192.168.120.172:22122
#网闸
#tracker_server = 59.61.92.90:9055
#内网项目地址
#tracker_server = 10.95.22.139:22122