Browse Source

Merge branch '2.0' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into 2.0

wangzhinan 1 year ago
parent
commit
1fd8c42aa8
29 changed files with 1835 additions and 1268 deletions
  1. 12 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceDataPushLogDao.java
  2. 9 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceInfoDao.java
  3. 5 1
      business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java
  4. 0 28
      business/base-service/src/main/java/com/yihu/jw/device/dao/HmTokenDao.java
  5. 0 309
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java
  6. 0 5
      business/base-service/src/main/java/com/yihu/jw/hospital/team/service/WlyyAdminTeamService.java
  7. 27 10
      business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java
  8. 2 2
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultTeamDao.java
  9. 8 5
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  10. 23 0
      common/common-entity/src/db/2023.sql
  11. 1 0
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/PostFilter.java
  12. 795 770
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java
  13. 3 3
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/service/IotDeviceService.java
  14. 0 1
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/SDKRunnerService.java
  15. 1 1
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java
  16. 2 1
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java
  17. 18 50
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java
  18. 0 17
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java
  19. 55 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceUploadController.java
  20. 3 15
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java
  21. 60 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/Result.java
  22. 34 11
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java
  23. 454 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceUploadService.java
  24. 10 6
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java
  25. 0 12
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DoctorRehabilitaionInfoController.java
  26. 2 21
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java
  27. 85 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/CountDistance.java
  28. 110 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceDataPushLogUtil.java
  29. 116 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceLostMessageUtil.java

+ 12 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceDataPushLogDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DeviceDataPushLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/9/2.
 */
public interface DeviceDataPushLogDao extends PagingAndSortingRepository<DeviceDataPushLog,Long>,
        JpaSpecificationExecutor<DeviceDataPushLog> {
}

+ 9 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceInfoDao.java

@ -0,0 +1,9 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DeviceInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface DeviceInfoDao extends CrudRepository<DeviceInfo, Long> {
}

+ 5 - 1
business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java

@ -22,7 +22,7 @@ public interface DevicePatientHealthIndexDao
	 * @param date
	 * @return
	 */
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate = ?3 and a.del = '1'")
	Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by a.recordDate order by a.recordDate asc")
@ -123,6 +123,10 @@ public interface DevicePatientHealthIndexDao
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1' and a.user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinute(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.value2=?7 and a.value3=?8 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinuteAllValue(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate,String value2,String value3);
}

+ 0 - 28
business/base-service/src/main/java/com/yihu/jw/device/dao/HmTokenDao.java

@ -1,28 +0,0 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.HmToken;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/***
 * @ClassName: HmTokenDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/4/14 18:57
 */
public interface HmTokenDao extends PagingAndSortingRepository<HmToken, Long>, JpaSpecificationExecutor<HmToken> {
    @Query("select accessToken from HmToken where patient = ?1")
    String selectToken(String patient);
    @Query(value = "select t.* from hm_token t where t.patient = ?1 order by t.id desc limit 1",nativeQuery = true)
    HmToken selectT(String patient);
    @Query("select a from HmToken a where a.accessToken is null")
    List<HmToken> findAllList();
}

+ 0 - 309
business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java

@ -1,309 +0,0 @@
package com.yihu.jw.hospital.team.dao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
public interface WlyySignFamilyDao extends JpaRepository<SignFamily, Integer>, JpaSpecificationExecutor<SignFamily> {
//    @Query("select count(*) from SignFamily  t where t.doctor=?1 and t.status=1")
//    Integer getCountByDoctorCode(String doctor);
//    @Query("select count(1) from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
//    int hasSingStatus(String idcard);
//    @Modifying
//    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1")
//    int updatePatientMobile(String patient, String mobile);
//    @Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
//    SignFamily findByPatientStatus(String idcard, int status);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and status = ?2 and a.type = 2")
//    SignFamily findByPatientCodeStatus(String patient, int status);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and status >= ?2 and a.type = 2")
//    SignFamily findByPatientCodeStatus2(String patient, int status);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
//    SignFamily findByPatientAndType(String patient, int type);
//
//    SignFamily findByCodeAndType(String code, Integer type);
//
//    SignFamily findByTeamCode(String TeamCode);
//
//    @Query("select a from SignFamily a where a.teamCode = ?1 and a.type = 2 and a.code=?2")
//    List<SignFamily> findByTeamCodeIsValid(String teamCode, String code);
//
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0")
//    SignFamily findByDoctorPatient(String doctor, String patient);
//
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and (a.type = 2 or a.type=1) and a.status >= 0")
//    List<SignFamily> findSSandFamilyByDoctorPatient(String doctor, String patient);
//
//    @Query("select a from SignFamily a where a.doctorHealth = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0 ")
//    SignFamily findByDoctorHealthPatient(String doctor, String patient);
//    @Query("select p from BasePatientDO p,SignFamily a where a.doctorHealth = ?1  and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
//    List<BasePatientDO> findByDoctorHealthPatient(String doctor, Long team);
//
//    @Query("select p from BasePatientDO p,SignFamily a where a.doctor = ?1 and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
//    List<BasePatientDO> findByDoctorPatient(String doctor, Long team);
//    @Query("select a from SignFamily a,DoctorTeamMember w " +
//            "where a.teamCode = w.team and w.del = '1' and w.memberCode = ?1 and a.patient = ?2 and a.status > 0 ")
//    List<SignFamily> findByDoctorAndPatient(String doctor, String patient);
//    @Query(value = "select a from SignFamily a where a.doctor =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
//    List<SignFamily> findByDoctorAndPatientIsValid(String doctor, String patient, String signYear);
//
//    @Query(value = "select a from SignFamily a where a.doctorHealth =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
//    List<SignFamily> findByDoctorHealthAndPatientIsValid(String doctorHealth, String patient, String signYear);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 2")
    SignFamily findByFamilyDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 1")
    SignFamily findBySanshiDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status > 0 and a.expensesStatus ='1'")
    SignFamily getExpensesSignByIdcard(String idcard);
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type =1 and a.status >= 0")
//    SignFamily findSSByIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 ")
//    List<SignFamily> findAllByIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.status >= 0")
//    List<SignFamily> findSSandJTByIdcard(String idcard);
//    // 拒绝解约
//    @Modifying
//    @Query("update SignFamily a set a.status = 1 where a.patient = ?1 and a.status = 2 and a.type = 2")
//    int refuseSurrender(String patient);
//
//    // 查询患者已生效的家庭签约
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status > 0")
//    SignFamily findSignByPatient(String patient);
//
//    @Modifying
//    @Query("update SignFamily a set a.openid = ?1 where a.patient = ?2")
//    int updateOpenidByPatient(String openid, String patient);
    // 查询已签约的总数
//    @Query("select count(1) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and (a.status = 1 or a.status = 2) and a.type = 2")
//    int countAmountSignedByDoctor(String doctor);
    // 查询待签约总数
//    @Query("select count(1) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and a.status = 0 and a.type = 2")
//    int countAmountUnsignByDoctor(String doctor);
    @Query("select a from SignFamily a where a.mobile = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByMobile(String mobile);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 1")
//    SignFamily findBySanshiPatient(String code);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 0")
//    SignFamily findBySsPatient(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 1")
    SignFamily findByjiatingPatient(String code);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status = 1")
//    SignFamily findByjiatingPatientYes(String code);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status = 1")
//    SignFamily findBySanshiPatientYes(String id);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status in (0,1,2,3)")
//    SignFamily findByPatientSanshiSignInfo(String idCard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status in (0,1,2,3)")
//    SignFamily findByPatientFamilySignInfo(String idCard);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >=0")
//    SignFamily findByjiatingPatientStatus0(String patient);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 1 and a.status in (0,1,2)")
//    SignFamily findSanshiSignByPatient(String patientCode);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status in (0,1,2)")
//    SignFamily findFamilySignByPatient(String patientCode);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status =-4 and a.signYear =?2")
//    SignFamily findFamilySignByPatientOverDue(String patientCode, String signYear);
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatients(String doctor);
//
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and p.name like ?2 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsLikeName(String doctor, String name);
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsBySignType(String doctor, int type);
//
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and p.name like ?3 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsByTypeName(String doctor, int type, String name);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 0")
    SignFamily findByPatient(String patient);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.signYear =?2 and a.status in (-4,1,2,3) order by a.id desc ")
//    List<SignFamily> findByPatientsLastYear(String patient, String signYear);
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status >= 0")
//    SignFamily findBySanshiIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status > 0")
//    SignFamily findSignByPatient(String patient, int type);
    SignFamily findByCode(String code);
//    @Query(" from SignFamily a where a.patient = ?1 and a.type = ?2 and (a.status=-3 or a.status=-4)  order by a.id desc")
//    List<SignFamily> findLastJySignByPatient(String patient, int type);
//    @Query(" from SignFamily a where  a.type =1 and unix_timestamp(a.czrq)=unix_timestamp( ?1 )  ")
//    List<SignFamily> findByDate(String s);
//    @Modifying
//    @Query("update SignFamily set expenses_type = ?1 where patient = ?2 and status > 0 and type = 2")
//    int updateExpensesType(String expensesType, String patient);
//
//    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 1")
//    int countPatientSsSign(String patient);
//
//    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 2")
//    int countPatientJtSign(String patient);
    // 查询患者已生效的家庭签约
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status = 0")
    SignFamily findSigningByPatient(String patient);
    //找出家庭签约中 团队是空的值
    @Query("select a from SignFamily a where a.type = 2 and a.status = 1 and a.adminTeamId is null")
    List<SignFamily> findBySignTypeAndTeamCode();
    //找出没有健康管理师的签约数据
    @Query("select a from SignFamily a where a.type = 2 and a.status >= 1 and a.doctorHealth is null and a.adminTeamId = ?1 order by a.czrq desc")
    List<SignFamily> findNoHealthSignFamilyNum(Long teamCode);
//
//    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 order by a.id")
//    Page<SignFamily> findByTypeAndSignSource(Integer type, String signSource, Pageable pageable);
//
//    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 and a.id >= ?3 and a.id <= ?4 order by a.id")
//    Page<SignFamily> findByTypeAndSignSourceAndId(Integer type, String signSource, Long start, Long end, Pageable pageable);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
//    List<SignFamily> findAllSignByPatient(String patient);
    /**
     * 获取所有有效的签约信息(不包含-1 -2)
     *
     * @param patient
     * @return
     */
//    @Query("select a from SignFamily a where a.patient = ?1 and a.status <> -1 and a.status <> -2 order by a.czrq")
//    List<SignFamily> findAllActiveSignByPatient(String patient);
//
//    @Query("select a.patient from SignFamily a where a.doctor = ?1 and a.type = 2 and a.status > 0 and a.doctorHealth is null")
//    List<String> findNohealthByDoctor(String doctor);
    /**
     * 获取团队中有效的患者
     *
     * @param teamCode
     * @param status
     * @return
     */
//    @Query("select count(f) from SignFamily f where f.adminTeamId = ?1 and f.status >= ?2 ")
//    int findByAdminTeamIdAndStatus(long teamCode, int status);
//
//    @Query("select f from SignFamily f where f.patient = ?1 and f.adminTeamId = ?2 and f.status > 0 and f.type = ?3")
//    SignFamily findByPatientAndAdminTeamId(String patient, Long teamCode, Integer type);
//
//    @Query(value = " select a.*  from wlyy_sign_family a where a.patient = ?1  and a.status = -4 order by a.apply_date desc limit 0,1", nativeQuery = true)
//    SignFamily findOutTimeSigningByPatient(String patient);
    //      完成缴费后更新签约开始时间begin 缴费状态expensesStatus 医保流水号medical_insurance_num  扣费时间expenses_time
//    @Modifying
//    @Query("update SignFamily a set a.begin = ?2 ,a.medicalInsuranceNum=?3,a.expensesStatus = ?4,a.expensesTime = ?2,a.signPaySource = ?5 where a.code = ?1 ")
//    int updatePatientBegin(String code, Date begin, String medicalInsuranceNum, String expensesStatus, int signPaySource );
//
//    //查询65岁以上一年内未体检且未系统提醒的签约居民
//    @Query(value = "SELECT DISTINCT t1.* FROM wlyy_sign_family t1 LEFT JOIN wlyy_physical_examination_records r ON r.patient_code=t1.patient WHERE r.patient_code IS NULL " +
//            " AND t1.STATUS>0 AND t1.hospital=?1 AND(YEAR(curdate())-IF(length(idcard)=18,substring(idcard,7,4),IF(length(idcard)=15,concat('19',substring(idcard,7,2)),NULL)))>=65 " +
//            " AND t1.idcard NOT IN(SELECT DISTINCT s.idcard FROM wlyy_sign_family s,wlyy_old_people_physical_examination o WHERE s.hospital=?1 AND s.`status`>0 AND s.idcard=o.id_card " +
//            " AND o.medical_time>?2 )ORDER BY t1.openid DESC,CONVERT(t1.NAME USING gbk) ",nativeQuery = true)
//    List<SignFamily> findExaminationByHospital(String hospital,Date examinationTime);
//
//    //查询wlyy_sign_family有续签却未同步到wlyy_sign_family_renew_log数据
//    @Query(value = "SELECT f.* FROM wlyy_sign_family f LEFT JOIN wlyy_sign_family_renew_log r ON f.`code` = r.sign_code WHERE r.sign_code IS NULL  " +
//            " AND f.renew_flag IN (1, 2) AND f.`status` IN (1, 2)  ",nativeQuery = true)
//    List<SignFamily> findRenew();
//
//    //根据身份证号查询最近的已到期签约数据
//    @Query(value = "SELECT f.* FROM wlyy_sign_family f WHERE f.idcard = ?1 and f.`status` = -4 ORDER BY sign_year desc LIMIT 0,1 ",nativeQuery = true)
//    SignFamily findLatelyRenew(String idcard);
//
//    //查询wlyy_sign_family有效签约且居民的医疗保险号为空的数据
//    @Query(value = "select a.idcard from wlyy_sign_family a left join wlyy_patient b on a.idcard = b.idcard where a.hospital = ?1 and (a.type = 2 or a.type = 1) " +
//            "and a.status = 1 and a.expenses_status = 1 and (b.medicare_number is null or b.medicare_number = '')", nativeQuery = true)
//    List<String> findIdcardByStatus(String hospital);
//
//    /**
//     * 判断是否已存在待处理签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status = 0")
//    SignFamily findByIdcardPre(String idcard);
//
//    /**
//     * 判断是否存在去年签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.signYear=?2 and a.type = 2 and (a.status= -4 or a.status>0) and a.expensesStatus = '1'")
//    SignFamily findOldSign(String idcard,String signYear);
//
//    /**
//     * 【临时】清洗
//     */
//    List<SignFamily> findByRenewFlag(String renewflag);
//
//    /**
//     * 【临时】清洗未扣费
//     */
//    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='0' and a.signYear='2017'")
//    List<SignFamily> findNoExpenses(Pageable pageable);
//
//    /**
//     * 【临时】退费
//     */
//    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='3' and a.signYear='2017'")
//    List<SignFamily> findReCharge();
//
//    /**
//     * 通过医生原有团队是否有签约
//     */
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.adminTeamId =?2 and a.status > 0")
//    List<SignFamily> findByDoctorAndAdminTeamCode(String doctor,Long adminTeamCode);
//
//    /**
//     * 判断是否三师签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status > 0")
//    SignFamily findSanshiByIdcard(String idcard);
}

+ 0 - 5
business/base-service/src/main/java/com/yihu/jw/hospital/team/service/WlyyAdminTeamService.java

@ -8,7 +8,6 @@ import com.yihu.jw.entity.hospital.team.WlyyAdminTeamMemberDO;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.team.dao.WlyyAdminTeamDao;
import com.yihu.jw.hospital.team.dao.WlyyAdminTeamMemberDao;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.apache.commons.lang3.StringUtils;
@ -30,8 +29,6 @@ public class WlyyAdminTeamService {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private WlyySignFamilyDao wlyySignFamilyDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseTownDao baseTownDao;
@ -99,8 +96,6 @@ public class WlyyAdminTeamService {
        }
        for (WlyyAdminTeamMemberDO wlyyAdminTeamMemberDO:list){
            /*Integer count = wlyySignFamilyDao.getCountByDoctorCode(wlyyAdminTeamMemberDO.getDoctorCode());
            wlyyAdminTeamMemberDO.setSignNum(count==null?0:count);*/
            WlyyAdminTeamDO wlyyAdminTeamDO = wlyyAdminTeamDao.findById(wlyyAdminTeamMemberDO.getTeamId().intValue()).orElse(null);
            if (wlyyAdminTeamDO != null) {
                if (wlyyAdminTeamDO.getLeaderCode().equalsIgnoreCase(wlyyAdminTeamMemberDO.getDoctorCode())) {

+ 27 - 10
business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java

@ -7333,7 +7333,7 @@ public class StatisticsEsService {
        //今天的
        String sql = "SELECT SUM(q.total)'todayFree' FROM(\n" +
                "	SELECT\n" +
                "	 IF(SUM(p.drug_fee) IS NULL,0,SUM(p.drug_fee))	 AS total \n" +
                "	 IF(SUM(p.drug_fee) IS NULL,'0',SUM(p.drug_fee))	 AS total \n" +
                "	FROM\n" +
                "		wlyy_prescription p\n" +
                "		INNER JOIN wlyy_outpatient o ON p.outpatient_id = o.id \n" +
@ -7343,7 +7343,7 @@ public class StatisticsEsService {
                "		AND p.create_time  >='" + qvo.getEndDate() + "'  AND p.create_time <='" + qvo.getEndDate() + " 23:59:59' \n" +
                "	UNION ALL\n" +
                "	SELECT\n" +
                "		COALESCE(ROUND(SUM(bop.pay_price),2), 0) AS total\n" +
                "		COALESCE(ROUND(SUM(bop.pay_price),2), '0.00') AS total\n" +
                "	FROM\n" +
                "		wlyy_outpatient o\n" +
                "		LEFT JOIN base_business_order_pay bop ON o.id = bop.relation_code \n" +
@ -7403,20 +7403,37 @@ public class StatisticsEsService {
        }
        allCount = prescriptionFee + checkFree;
        resultMap.put("checkFree", checkFree);//检查费
        resultMap.put("prescriptionFee", prescriptionFee);//处方费
        resultMap.put("allCount", allCount);//总费用
        if (checkFree == 0) {
            resultMap.put("checkFree", "0.00");//检查费
        } else {
            resultMap.put("checkFree", checkFree);//检查费
        }
        if (prescriptionFee == 0) {
            resultMap.put("prescriptionFee", "0.00");//处方费
        } else {
            resultMap.put("prescriptionFee", prescriptionFee);//处方费
        }
        if (allCount == 0) {
            resultMap.put("avgFree", 0);
            resultMap.put("allCount", "0.00");//总费用
        } else {
            resultMap.put("allCount", allCount);//总费用
        }
        if (allCount == 0) {
            resultMap.put("avgFree", "0.00");
        } else {
            resultMap.put("avgFree", allCount / 2.0);//平均费用
        }
        if (monthModel != null) {
        if (monthModel != null && monthModel.getResult2().longValue() != 0) {
            resultMap.put("monthFree", monthModel.getResult2().longValue());//本月新增
        } else {
            resultMap.put("monthFree", 0);
            resultMap.put("monthFree", "0.00");
        }
        if ("0".equals(todayFree)) {
            resultMap.put("todayFree", "0.00");
        } else {
            resultMap.put("todayFree", todayFree);//今日新增
        }
        resultMap.put("todayFree", todayFree);//今日新增
        System.out.println("结果===>"+JSON.toJSONString(resultMap));
        return resultMap;
    }
@ -7791,7 +7808,7 @@ public class StatisticsEsService {
     * 获取i健康的患者的健康指标数据
     */
    public JSONObject getHealthChart(ScreenQvo qvo) {
        String param = "?idcard=" + qvo.getIdcard() + "&type=" + qvo.getType() + "&gi_type="+qvo.getIndex() + "&time=" + qvo.getTime() + "&begin=" + qvo.getStartDate() + "&end=" + qvo.getEndDate();
        String param = "?idcard=" + qvo.getIdcard() + "&type=" + qvo.getType() + "&gi_type=" + qvo.getIndex() + "&time=" + qvo.getTime() + "&begin=" + qvo.getStartDate() + "&end=" + qvo.getEndDate();
        JSONObject re = wlyyHttpService.sendWlyyMesGet("chart", param);
        return re;
    }

+ 2 - 2
business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultTeamDao.java

@ -24,8 +24,8 @@ public interface ConsultTeamDao  extends JpaRepository<ConsultTeamDo, String>, J
//	@Query("update ConsultTeam a set a.status = 1 where a.consult = ?1")
//	int updateStatusByConsult(String consult);
//
//	@Query("select a from ConsultTeamDo a,ConsultTeamDoctor b where a.consult = b.consult and a.patient = ?1 and b.to = ?2 and a.del = '1' and a.type<>8 and a.status = 0")
//	List<ConsultTeamDo> findUnfinishedConsultType(String patient,String doctor);
	@Query("select a from ConsultTeamDo a where a.patient = ?1 and a.doctor = ?2 and a.del = '1' and a.type=?3 and a.status = 0")
	List<ConsultTeamDo> findUnfinishedConsultType(String patient,String doctor,Integer type);
	@Query("select count(id) from  ConsultTeamDo a where a.type = ?1 and a.doctor = ?2 and a.czrq >=?3 and a.czrq <=?4")
	Integer  countByTime(int type, String doctor, Date startTime, Date endTime);

+ 8 - 5
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -361,15 +361,18 @@ public class ImService {
        return consultCode;
    }
    public List<ConsultTeamDo> getUnfinishedConsult3(String patient, String doctor,int type) {
        return consultTeamDao.findUnfinishedConsultType(patient,doctor,type);
    }
    public String getUnfinishedConsult(String patient, String doctor,int type) {
        String totalSql = "SELECT a.consult as \"consultCode\" " +
                "FROM wlyy_consult_team a,wlyy_consult_team_doctor b " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" + patient + "' " +
                "AND b.to_doctor='" + doctor + "' " +
                "FROM wlyy_consult_team a " +
                "WHERE a.patient= '" + patient + "' " +
                "AND a.doctor='" + doctor + "' " +
                "AND a.del='1' " +
                "AND a.type=" +type+
                "AND a.status=0";
                " AND a.status=0";
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);
        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {

+ 23 - 0
common/common-entity/src/db/2023.sql

@ -453,3 +453,26 @@ CREATE TABLE `wlyy_patient_health_record_sports` (
     KEY `idx_wlyy_patient_health_record_sports_1` (`patient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='患者健康(运动)记录表';
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('registerToWlyy1', NULL, 'registerToWlyy', 'pushAddress', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '设备推送地址');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('registerToWlyy2', NULL, 'registerToWlyy', 'url', 'http://www.cityihealth.com:43210/deviceManage/register', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
CREATE TABLE `wlyy_patient_device_log` (
   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
   `device_id` int(11) DEFAULT NULL COMMENT 'dm_device表主键id',
   `patient` varchar(50) DEFAULT NULL COMMENT '患者id',
   `device_sn` varchar(50) DEFAULT NULL COMMENT '设备sn码',
   `device_name` varchar(50) DEFAULT NULL COMMENT '设备名称',
   `category_code` varchar(50) DEFAULT NULL COMMENT '设备类型(1血糖仪 2血压计)',
   `operator` varchar(50) DEFAULT NULL COMMENT '操作人code',
   `operator_name` varchar(50) DEFAULT NULL COMMENT '操作人姓名',
   `role` int(2) DEFAULT NULL COMMENT '医生或者患者(1医生2患者)',
   `operate_code` int(2) DEFAULT NULL COMMENT '操作动作(1绑定 2解绑)',
   `create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
   `is_del` int(2) DEFAULT '1' COMMENT '是否有效(0无效 1有效)',
   `agreement_photo` varchar(300) DEFAULT NULL COMMENT '上传协议图片地址',
   `hospital` varchar(50) DEFAULT NULL COMMENT '居民签约所在社区',
   `hospital_name` varchar(50) DEFAULT NULL COMMENT '居民签约居民社区名字',
   `check_doctor_name` varchar(50) DEFAULT NULL COMMENT '登记医生姓名',
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12773 DEFAULT CHARSET=utf8mb4;

+ 1 - 0
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/PostFilter.java

@ -137,6 +137,7 @@ public class PostFilter extends ZuulFilter {
                url.contains("/excelControl")||
                url.contains("/prescription/searchRecordWrite")||
                url.contains("/Funds/reconciliationExcel")||
//                url.contains("/open/statistics")||
                url.contains("/servicePackageSubItem/exportSubItemExcel")|| //导出

+ 795 - 770
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.security.oauth2.provider.endpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
@ -97,11 +98,9 @@ import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 *
 * Endpoint for default login verify and sso login token verify
 * will return the user's basic information and token certificate
 *
 *
 * @author Progr1mmer
 * @created on 2018/8/29
 */
@ -192,71 +191,72 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    private void init() {
        super.setTokenGranter(tokenGranter);
    }
    @RequestMapping(value = "/oauth/getGeetConfig", method = RequestMethod.GET)
    public  JSONObject getGeetConfig(String isPaitent){
    public JSONObject getGeetConfig(String isPaitent) {
        //患者端id
        String gt="d99d7ba0ce0ad944d02c11e2e00b184f";
        String gt = "d99d7ba0ce0ad944d02c11e2e00b184f";
        //医生端id
        String gtDoctor="65234b3ce5a6fed467ef64bcc4330605";
        String gtDoctor = "65234b3ce5a6fed467ef64bcc4330605";
        String url = "http://bypass.geetest.com/v1/bypass_status.php";
        String register="http://localhost:8088/register";
        String register = "http://localhost:8088/register";
        JSONObject result = new JSONObject();
        JSONObject returnResult = new JSONObject();
        List<WlyyHospitalSysDictDO> list = wlyyhospitalSysdictDao.findByDictName("geetConfig");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
            if ("type".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                result.put("type",wlyyHospitalSysDictDO.getDictValue());
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO : list) {
            if ("type".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())) {
                result.put("type", wlyyHospitalSysDictDO.getDictValue());
            }
            if ("register".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
            if ("register".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())) {
                register = wlyyHospitalSysDictDO.getDictValue();
            }
            if ("bypass".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
            if ("bypass".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())) {
                url = wlyyHospitalSysDictDO.getDictValue();
            }
        }
        if (!"1".equalsIgnoreCase(isPaitent)){
            gt=gtDoctor;
        if (!"1".equalsIgnoreCase(isPaitent)) {
            gt = gtDoctor;
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("gt",gt));
        params.add(new BasicNameValuePair("gt", gt));
        String res = httpClientUtil.post(url, params, "UTF-8");
        JSONObject statusObject = JSONObject.parseObject(res);
        if (statusObject!=null){
            result.put("offline",statusObject.getString("status"));
        if (statusObject != null) {
            result.put("offline", statusObject.getString("status"));
        }
        System.out.println(res);
        Long t= new Date().getTime();
        String registerRes= httpClientUtil.get(register+"?t="+t+"&isPatient="+isPaitent,"UTF-8");
        Long t = new Date().getTime();
        String registerRes = httpClientUtil.get(register + "?t=" + t + "&isPatient=" + isPaitent, "UTF-8");
        System.out.println(registerRes);
        JSONObject registerObject= JSONObject.parseObject(registerRes);
        if (registerObject!=null){
            result.put("challenge",registerObject.getString("challenge"));
            result.put("newCaptcha",registerObject.getString("new_captcha"));
        JSONObject registerObject = JSONObject.parseObject(registerRes);
        if (registerObject != null) {
            result.put("challenge", registerObject.getString("challenge"));
            result.put("newCaptcha", registerObject.getString("new_captcha"));
        }
        result.put("gt",gt);
        result.put("gt", gt);
        System.out.println(result.toJSONString());
        returnResult.put("status",200);
        returnResult.put("message","success");
        returnResult.put("obj",result);
        returnResult.put("status", 200);
        returnResult.put("message", "success");
        returnResult.put("obj", result);
        return returnResult;
    }
    public  JSONObject validateGeet( String geetestChallenge,String geetestValidate,String geetestSeccode,String isPatient){
    public JSONObject validateGeet(String geetestChallenge, String geetestValidate, String geetestSeccode, String isPatient) {
        String validateUrl = "http://localhost:8088/validate";
        List<WlyyHospitalSysDictDO> list = wlyyhospitalSysdictDao.findByDictName("geetConfig");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
            if ("validateUrl".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                validateUrl=wlyyHospitalSysDictDO.getDictValue();
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO : list) {
            if ("validateUrl".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())) {
                validateUrl = wlyyHospitalSysDictDO.getDictValue();
            }
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("geetest_challenge",geetestChallenge));
        params.add(new BasicNameValuePair("geetest_validate",geetestValidate));
        params.add(new BasicNameValuePair("geetest_seccode",geetestSeccode));
        params.add(new BasicNameValuePair("isPatient",isPatient));
        params.add(new BasicNameValuePair("geetest_challenge", geetestChallenge));
        params.add(new BasicNameValuePair("geetest_validate", geetestValidate));
        params.add(new BasicNameValuePair("geetest_seccode", geetestSeccode));
        params.add(new BasicNameValuePair("isPatient", isPatient));
        String res = httpClientUtil.post(validateUrl, params, "UTF-8");
        JSONObject statusObject = JSONObject.parseObject(res);
        System.out.println(statusObject.toJSONString());
@ -265,38 +265,38 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    @PostMapping(value = "/oauth/doctor/logOff")
    public JSONObject doctorLogOff(HttpServletRequest request){
    public JSONObject doctorLogOff(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        try {
            BaseLoginLogDO loginLogDO = getLoginLog();
            if(loginLogDO == null){
                jsonObject.put("msg","该操作没有权限");
                jsonObject.put("status",200);
            if (loginLogDO == null) {
                jsonObject.put("msg", "该操作没有权限");
                jsonObject.put("status", 200);
                return jsonObject;
            }
            userDetailsService.logOff(loginLogDO.getUserId());
            jsonObject.put("msg","注销成功");
            jsonObject.put("status",200);
            jsonObject.put("msg", "注销成功");
            jsonObject.put("status", 200);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("msg","注销失败!");
            jsonObject.put("status",500);
            jsonObject.put("msg", "注销失败!");
            jsonObject.put("status", 500);
            return jsonObject;
        }
    }
    public HttpServletRequest getRequest(){
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    private BaseLoginLogDO getLoginLog(){
    private BaseLoginLogDO getLoginLog() {
        String accessToken = this.extractToken(getRequest());
        String sql  = "SELECT a.* from base_login_log a WHERE a.token='"+accessToken+"' ORDER BY a.create_time desc LIMIT 1";
        String sql = "SELECT a.* from base_login_log a WHERE a.token='" + accessToken + "' ORDER BY a.create_time desc LIMIT 1";
        List<BaseLoginLogDO> baseLoginLogDOList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BaseLoginLogDO.class));
        //BaseLoginLogDO loginLogDO = baseLoginLogDao.findByToken(accessToken);
        return baseLoginLogDOList.size()>0?baseLoginLogDOList.get(0):null;
        return baseLoginLogDOList.size() > 0 ? baseLoginLogDOList.get(0) : null;
    }
    private String extractToken(HttpServletRequest request) {
@ -326,190 +326,199 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
     */
    @RequestMapping(value = "/oauth/login", method = RequestMethod.POST)
    public ResponseEntity<Oauth2Envelop<WlyyUserSimple>> login(@RequestParam Map<String, String> parameters, HttpSession httpSession) throws Exception {
            logger.info("login:登录进入1");
            //图形验证码验证
            String key = parameters.get("key");
            String text = parameters.get("text");
            if(org.apache.commons.lang3.StringUtils.isNotBlank(key)&& org.apache.commons.lang3.StringUtils.isNotBlank(text)){
                if(!verifyCaptcha(key,text)){
                    throw new ImgCaptchaException("验证码错误!");
                }
        System.out.println("参数内容 parameters==>" + JSON.toJSONString(parameters));
        System.out.println("httpSession.getId()==>" + httpSession.getId());
        logger.info("login:登录进入1");
        //图形验证码验证
        String key = parameters.get("key");
        String text = parameters.get("text");
        System.out.println("key==>" + key);
        System.out.println("text==>" + text);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(key) && org.apache.commons.lang3.StringUtils.isNotBlank(text)) {
            if (!verifyCaptcha(key, text)) {
                System.out.println("");
                throw new ImgCaptchaException("验证码错误!");
            }
            logger.info("login:登录进入2");
        }
        logger.info("login:登录进入2");
            String flag = parameters.get("flag");
        String flag = parameters.get("flag");
            String username = parameters.get("username");
            logger.info(username);
        String username = parameters.get("username");
        logger.info(username);
            if (StringUtils.isEmpty(username)&&StringUtils.isEmpty(flag)) {
                throw new InvalidRequestException("username");
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(flag)) {
            System.out.println("flag==>" + flag);
            System.out.println("username==>" + username);
            System.out.println("flag或者username为空");
            throw new InvalidRequestException("username");
        }
        String client_id = parameters.get("client_id");
        System.out.println("client_id==>" + client_id);
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id");
        }
        if ("alipay".equals(flag) || "family".equals(flag)) {
            //支付宝登录||家人登录
            parameters.put("grant_type", flag);
            String encdata = parameters.get("encdata");
            if ("alipay".equals(flag)) {
                encdata = AES.decrypt(encdata);
            } else {
                encdata = AesEncryptUtils.agDecrypt(encdata);
            }
            String data[] = encdata.split(":");
            username = data[1];
            parameters.put("username", username);
        } else if ("dingTalk".equals(flag)) {
            //钉钉免登录
            parameters.put("grant_type", "dingTalk");
            String authCode = parameters.get("authCode");
            if (org.apache.commons.lang3.StringUtils.isBlank(authCode)) {
                throw new InvalidRequestException("请求参数错误");
            }
            String registerRes = httpClientUtil.get("http://127.0.0.1:10301/doctor/dingtalk_app_user?authCode=" + authCode, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(registerRes);
            if (jsonObject.getInteger("status") == 200) {
                parameters.put("username", jsonObject.getString("message"));
            } else {
                HttpHeaders headers = new HttpHeaders();
                headers.set("Cache-Control", "no-store");
                headers.set("Pragma", "no-cache");
                Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>(jsonObject.getString("message"), -1, null);
                return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
            }
            String client_id = parameters.get("client_id");
            if (StringUtils.isEmpty(client_id)) {
                throw new InvalidRequestException("client_id");
            }
            if("alipay".equals(flag)||"family".equals(flag)){
                //支付宝登录||家人登录
                parameters.put("grant_type", flag);
                String encdata = parameters.get("encdata");
                if("alipay".equals(flag)){
                    encdata = AES.decrypt(encdata);
                }else{
                    encdata = AesEncryptUtils.agDecrypt(encdata);
                }
                String data[] = encdata.split(":");
                username = data[1];
                parameters.put("username", username);
            }else if("dingTalk".equals(flag)){
                //钉钉免登录
                parameters.put("grant_type", "dingTalk");
                String authCode = parameters.get("authCode");
                if(org.apache.commons.lang3.StringUtils.isBlank(authCode)){
                    throw new InvalidRequestException("请求参数错误");
                }
                String registerRes= httpClientUtil.get("http://127.0.0.1:10301/doctor/dingtalk_app_user?authCode="+authCode,"UTF-8");
                JSONObject jsonObject= JSONObject.parseObject(registerRes);
                if (jsonObject.getInteger("status") == 200){
                    parameters.put("username", jsonObject.getString("message"));
                }else{
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("Cache-Control", "no-store");
                    headers.set("Pragma", "no-cache");
                    Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>(jsonObject.getString("message"), -1, null);
                    return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
                }
            }else if("wxApplets".equals(flag)){
                //微信小程序登录
                parameters.put("grant_type", "dingTalk");
                String authCode = parameters.get("authCode");
                if(org.apache.commons.lang3.StringUtils.isBlank(authCode)){
                    throw new InvalidRequestException("请求参数错误");
                }
                String userPhone = wechatService.getUserPhoneByApplets(authCode);
                if (!StringUtils.isEmpty(userPhone)){
                    parameters.put("username", userPhone);
                }else{
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("Cache-Control", "no-store");
                    headers.set("Pragma", "no-cache");
                    Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>("获取用户手机号失败", -1, null);
                    return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
                }
            }else if (StringUtils.isEmpty(parameters.get("captcha"))) {
                parameters.put("grant_type", "password");
                //解密密码
                if (parameters.get("password") != null) {
                    KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                    String password = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("password"), keyPair);
                    parameters.put("password", password);
                } else {
                    //第三方同步账号模式登录
                    parameters.put("grant_type", "ihealthCode");
                }
        } else if ("wxApplets".equals(flag)) {
            //微信小程序登录
            parameters.put("grant_type", "dingTalk");
            String authCode = parameters.get("authCode");
            if (org.apache.commons.lang3.StringUtils.isBlank(authCode)) {
                throw new InvalidRequestException("请求参数错误");
            }
            String userPhone = wechatService.getUserPhoneByApplets(authCode);
            if (!StringUtils.isEmpty(userPhone)) {
                parameters.put("username", userPhone);
            } else {
                parameters.put("grant_type", "captcha");
                HttpHeaders headers = new HttpHeaders();
                headers.set("Cache-Control", "no-store");
                headers.set("Pragma", "no-cache");
                Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>("获取用户手机号失败", -1, null);
                return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
            }
            logger.info("login:登录进入3");
            ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
            if (null == authenticatedClient) {
                throw new InvalidRequestException("client_id");
        } else if (StringUtils.isEmpty(parameters.get("captcha"))) {
            parameters.put("grant_type", "password");
            //解密密码
            if (parameters.get("password") != null) {
                KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                System.out.println("keyPair==>" + JSON.toJSONString(keyPair));
                String password = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("password"), keyPair);
                System.out.println("password==>" + password);
                parameters.put("password", password);
            } else {
                //第三方同步账号模式登录
                parameters.put("grant_type", "ihealthCode");
            }
            logger.info("login:登录进入4"+authenticatedClient.getClientId());
        } else {
            parameters.put("grant_type", "captcha");
        }
        logger.info("login:登录进入3");
            TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
            oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
            OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
            if (token == null) {
                throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
            }
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
        if (null == authenticatedClient) {
            throw new InvalidRequestException("client_id");
        }
        logger.info("login:登录进入4" + authenticatedClient.getClientId());
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
        OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
        if (token == null) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }
        /*如果是移动端登陆则移除之前的token,
        在网关处通过HTTP状态码告知前端是过期(402)还是账号在别处登陆(403),
        实现同一账号只能在一处登陆*/
            if("1".equals(kickEachOther)){
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile")||request.getHeader("login-device").equalsIgnoreCase("pc"))) {
                    if (tokenStore.readAccessToken(token.getValue())!=null){
                        tokenStore.removeAccessToken(token.getValue());
                        tokenStore.removeRefreshToken(token.getRefreshToken().getValue());
                        token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
                    }
                }
                if (token == null) {
                    throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        if ("1".equals(kickEachOther)) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile") || request.getHeader("login-device").equalsIgnoreCase("pc"))) {
                if (tokenStore.readAccessToken(token.getValue()) != null) {
                    tokenStore.removeAccessToken(token.getValue());
                    tokenStore.removeRefreshToken(token.getRefreshToken().getValue());
                    token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
                }
            }
            WlyyUserSimple wlyyUserSimple = userDetailsService.authSuccess(parameters.get("username"));
            if ("pad".equals(parameters.get("clientType"))&&!("1".equals(wlyyUserSimple.getArchiveType())) ){//医养平板端登录限制
                throw new InvalidGrantException("不允许登录该平台");
            }
            logger.info("wlyyUserSimple::"+wlyyUserSimple);
            wlyyUserSimple.setAccessToken(token.getValue());
            wlyyUserSimple.setTokenType(token.getTokenType());
            wlyyUserSimple.setExpiresIn(token.getExpiresIn());
            wlyyUserSimple.setRefreshToken(token.getRefreshToken().getValue());
            wlyyUserSimple.setUser(parameters.get("username"));
            wlyyUserSimple.setState(parameters.get("state"));
            String loginType = parameters.get("login_type");
            String openid = parameters.get("openid");
            String wechatId = parameters.get("wechatId");
            logger.info("login:登录进入7");
            //更新患者openId
            BaseLoginLogDO baseLoginLogDO = new BaseLoginLogDO();
            logger.info("gengxin开始");
            if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("3".equals(loginType)||"4".equalsIgnoreCase(loginType))) {
                baseLoginLogDO.setOpenid(openid);
                logger.info("gengxin进入"+openid);
                userDetailsService.updateOpenId(openid, wlyyUserSimple.getId());
                if (!StringUtils.isEmpty(wechatId)&& !"undefined".equalsIgnoreCase(wechatId)){
                    logger.info("gengxin进入"+wechatId);
                    userDetailsService.updateOpenIdAndWechatId(openid,wlyyUserSimple.getId(),wechatId);
                }
                if (wxId.equalsIgnoreCase("xm_zsyy_wx")&&wechatId.equalsIgnoreCase("xm_ihealth_wx")){
                    userDetailsService.updateOpenIdAndWechatId(userDetailsService.getZsyyOpenid(wlyyUserSimple.getIdcard()),wlyyUserSimple.getId(),wxId);
                }
            }else if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("2".equals(loginType))) {
                if (wechatId.equalsIgnoreCase("xm_mlwyy_wx")){
                    logger.info("gengxin进入"+openid);
                    userDetailsService.updateDoctorOpenId(openid, wlyyUserSimple.getId());
                }
            if (token == null) {
                throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
            }
        }
            if (parameters.get("password") != null) {
                //使用密码登录成功后, 更新失败次数为 0
                userDetailsService.addFailureCount(username, 0);
        WlyyUserSimple wlyyUserSimple = userDetailsService.authSuccess(parameters.get("username"));
        if ("pad".equals(parameters.get("clientType")) && !("1".equals(wlyyUserSimple.getArchiveType()))) {//医养平板端登录限制
            throw new InvalidGrantException("不允许登录该平台");
        }
        logger.info("wlyyUserSimple::" + wlyyUserSimple);
        wlyyUserSimple.setAccessToken(token.getValue());
        wlyyUserSimple.setTokenType(token.getTokenType());
        wlyyUserSimple.setExpiresIn(token.getExpiresIn());
        wlyyUserSimple.setRefreshToken(token.getRefreshToken().getValue());
        wlyyUserSimple.setUser(parameters.get("username"));
        wlyyUserSimple.setState(parameters.get("state"));
        String loginType = parameters.get("login_type");
        String openid = parameters.get("openid");
        String wechatId = parameters.get("wechatId");
        logger.info("login:登录进入7");
        //更新患者openId
        BaseLoginLogDO baseLoginLogDO = new BaseLoginLogDO();
        logger.info("gengxin开始");
        if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("3".equals(loginType) || "4".equalsIgnoreCase(loginType))) {
            baseLoginLogDO.setOpenid(openid);
            logger.info("gengxin进入" + openid);
            userDetailsService.updateOpenId(openid, wlyyUserSimple.getId());
            if (!StringUtils.isEmpty(wechatId) && !"undefined".equalsIgnoreCase(wechatId)) {
                logger.info("gengxin进入" + wechatId);
                userDetailsService.updateOpenIdAndWechatId(openid, wlyyUserSimple.getId(), wechatId);
            }
            logger.info("login:登录进入8");
            wlyyUserSimple.setOpenid(openid);
            userDetailsService.setRolePhth(loginType, token, wlyyUserSimple.getId(), redisTemplate);
            if (wxId.equalsIgnoreCase("xm_zsyy_wx") && wechatId.equalsIgnoreCase("xm_ihealth_wx")) {
                userDetailsService.updateOpenIdAndWechatId(userDetailsService.getZsyyOpenid(wlyyUserSimple.getIdcard()), wlyyUserSimple.getId(), wxId);
            }
        } else if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("2".equals(loginType))) {
            if (wechatId.equalsIgnoreCase("xm_mlwyy_wx")) {
                logger.info("gengxin进入" + openid);
                userDetailsService.updateDoctorOpenId(openid, wlyyUserSimple.getId());
            }
        }
            logger.info("login:登录进入9");
            String clientType = parameters.get("clientType");
            baseLoginLogDO.setUserId(wlyyUserSimple.getId());
            baseLoginLogDO.setCreateTime(new Date());
            String userAgent = JSONObject.toJSONString(wlyyUserSimple);
            baseLoginLogDO.setUserAgent(userAgent);
            baseLoginLogDO.setLoginType(loginType);
            baseLoginLogDO.setName(wlyyUserSimple.getName());
            baseLoginLogDO.setClientType(clientType);
            baseLoginLogDO.setToken(token.getValue());
            baseLoginLogService.save(baseLoginLogDO);
            logger.info("login:登录进入10");
            //个推 clientId
            String clientId = parameters.get("getuiClientId");
            String getuiClientType = parameters.get("getuiClientType");
            String padImei = parameters.get("padImei");
            //客户端类型 app,wx,pad,pc
            userDetailsService.updateInfo(clientId,getuiClientType,padImei,loginType,wlyyUserSimple.getId(),baseLoginLogDO);
            return getResponse(wlyyUserSimple);
    }
        if (parameters.get("password") != null) {
            //使用密码登录成功后, 更新失败次数为 0
            userDetailsService.addFailureCount(username, 0);
        }
        logger.info("login:登录进入8");
        wlyyUserSimple.setOpenid(openid);
        userDetailsService.setRolePhth(loginType, token, wlyyUserSimple.getId(), redisTemplate);
        logger.info("login:登录进入9");
        String clientType = parameters.get("clientType");
        baseLoginLogDO.setUserId(wlyyUserSimple.getId());
        baseLoginLogDO.setCreateTime(new Date());
        String userAgent = JSONObject.toJSONString(wlyyUserSimple);
        baseLoginLogDO.setUserAgent(userAgent);
        baseLoginLogDO.setLoginType(loginType);
        baseLoginLogDO.setName(wlyyUserSimple.getName());
        baseLoginLogDO.setClientType(clientType);
        baseLoginLogDO.setToken(token.getValue());
        baseLoginLogService.save(baseLoginLogDO);
        logger.info("login:登录进入10");
        //个推 clientId
        String clientId = parameters.get("getuiClientId");
        String getuiClientType = parameters.get("getuiClientType");
        String padImei = parameters.get("padImei");
        //客户端类型 app,wx,pad,pc
        userDetailsService.updateInfo(clientId, getuiClientType, padImei, loginType, wlyyUserSimple.getId(), baseLoginLogDO);
        return getResponse(wlyyUserSimple);
    }
    /**
@ -594,9 +603,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        }
        //删除个推cid
        if(!StringUtils.isEmpty(token)){
        if (!StringUtils.isEmpty(token)) {
            BaseLoginLogDO loginLogDO = baseLoginLogService.findByToken(token);
            if(loginLogDO!=null){
            if (loginLogDO != null) {
                userDetailsService.deleteCidByUser(loginLogDO.getUserId());
            }
        }
@ -650,6 +659,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    @RequestMapping(value = "/oauth/getPublicKey", method = RequestMethod.GET)
    public ObjEnvelop<PublickeyVO> getPublicKey(HttpSession httpSession, HttpServletResponse httpServletResponse) {
        KeyPair keyPair = com.yihu.jw.security.utils.RSAUtils.getKey();
        System.out.println("httpSession.getId()==>" + httpSession.getId());
        httpSession.setAttribute("privateKey", keyPair);
        PublickeyVO pk = new PublickeyVO();
        pk.setPublicKey(com.yihu.jw.security.utils.RSAUtils.generateBase64PublicKey(keyPair));
@ -726,6 +736,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 中山医院短信接口
     *
     * @param parameters
     * @return
     * @throws Exception
@ -740,7 +751,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -748,7 +759,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -760,10 +771,10 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            int result =  zhongShanSMSService.ZhongShangSendSMS(username,"您好,你的手机登录短信验证码是:"+captcha+",5分钟内有效。");
            int result = zhongShanSMSService.ZhongShangSendSMS(username, "您好,你的手机登录短信验证码是:" + captcha + ",5分钟内有效。");
            if (0 == result) {
@ -784,6 +795,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 心脏医院短信接口
     *
     * @param parameters
     * @return
     * @throws Exception
@ -798,7 +810,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -806,7 +818,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -818,23 +830,23 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            JSONObject object = new JSONObject();
            object.put("operatetel","18788888888");
            object.put("interfaceid","jcpt");
            object.put("interfacepwd","jcpt");
            object.put("operator","xxgwxgzh");
            object.put("operateid","xxgwxgzh");
            object.put("operatetel", "18788888888");
            object.put("interfaceid", "jcpt");
            object.put("interfacepwd", "jcpt");
            object.put("operator", "xxgwxgzh");
            object.put("operateid", "xxgwxgzh");
            JSONArray array = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content","您好,你的手机登录短信验证码是:"+captcha+",5分钟内有效。");
            jsonObject.put("sendtel",username);
            jsonObject.put("sendtime",DateUtil.dateToStrLong(new Date()));
            jsonObject.put("content", "您好,你的手机登录短信验证码是:" + captcha + ",5分钟内有效。");
            jsonObject.put("sendtel", username);
            jsonObject.put("sendtime", DateUtil.dateToStrLong(new Date()));
            array.add(jsonObject);
            object.put("messageinfo",array);
            int result =  xzzxService.SendSms(object.toJSONString());
            object.put("messageinfo", array);
            int result = xzzxService.SendSms(object.toJSONString());
            if (0 == result) {
@ -855,6 +867,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 第三医院短信接口
     *
     * @param parameters
     * @return
     * @throws Exception
@ -869,7 +882,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -877,7 +890,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -889,11 +902,11 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            String content = "您好,你的手机登录短信验证码是:"+captcha+",5分钟内有效。";
            int result =  dsyyService.SendSms(username,content);
            String content = "您好,你的手机登录短信验证码是:" + captcha + ",5分钟内有效。";
            int result = dsyyService.SendSms(username, content);
            if (0 == result) {
@ -914,6 +927,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 福州健康之路短信接口
     *
     * @param parameters
     * @return
     * @throws Exception
@ -928,7 +942,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -936,7 +950,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -948,10 +962,10 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            int result =  zbSmsService.sendMessage(username,captcha);
            int result = zbSmsService.sendMessage(username, captcha);
            if (0 == result) {
                Captcha _captcha = new Captcha();
                _captcha.setCode(captcha);
@ -971,6 +985,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 腾讯云短信接口
     *
     * @param parameters
     * @return
     * @throws Exception
@ -985,7 +1000,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -993,7 +1008,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -1005,21 +1020,21 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            SmsDO smsDO = new SmsDO();
            smsDO.setCaptcha(captcha);
            smsDO.setClientId(client_id);
            smsDO.setContent("您好,你的手机登录短信验证码是:"+captcha+",5分钟内有效。");
            smsDO.setContent("您好,你的手机登录短信验证码是:" + captcha + ",5分钟内有效。");
            smsDO.setMobile(username);
            smsDO.setDeadline(DateUtil.getNextMin(new Date(),5));
            smsDO.setDeadline(DateUtil.getNextMin(new Date(), 5));
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            smsDO.setRequestIp(NetworkUtil.getIpAddress(request));
            smsDO.setCreateTime(new Date());
            baseSmsDao.save(smsDO);
            //
            String result =  txySmsService.sendMessage(username,captcha);
            String result = txySmsService.sendMessage(username, captcha);
            if ("Ok".equals(result)) {
                Captcha _captcha = new Captcha();
                _captcha.setCode(captcha);
@ -1046,7 +1061,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if (username.length()>12){
        if (username.length() > 12) {
            throw new InvalidRequestException("请输入正确的手机号!");
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -1054,7 +1069,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -1066,21 +1081,21 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
        } else {
            //发送短信获取验证码
            String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
            SmsDO smsDO = new SmsDO();
            smsDO.setCaptcha(captcha);
            smsDO.setClientId(client_id);
            smsDO.setContent("您好,你的手机登录短信验证码是:"+captcha+",5分钟内有效。");
            smsDO.setContent("您好,你的手机登录短信验证码是:" + captcha + ",5分钟内有效。");
            smsDO.setMobile(username);
            smsDO.setDeadline(DateUtil.getNextMin(new Date(),5));
            smsDO.setDeadline(DateUtil.getNextMin(new Date(), 5));
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            smsDO.setRequestIp(NetworkUtil.getIpAddress(request));
            smsDO.setCreateTime(new Date());
            baseSmsDao.save(smsDO);
            //
            String result =  txySmsService.sendMessage(username,captcha);
            String result = txySmsService.sendMessage(username, captcha);
            if ("Ok".equals(result)) {
                Captcha _captcha = new Captcha();
                _captcha.setCode(captcha);
@ -1102,24 +1117,24 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        String wxId = parameters.get("wxId");
        String key = parameters.get("key");
        String text = parameters.get("text");
        if(org.apache.commons.lang3.StringUtils.isNotBlank(key)&& org.apache.commons.lang3.StringUtils.isNotBlank(text)){
            if(!verifyCaptcha(key,text)){
        if (org.apache.commons.lang3.StringUtils.isNotBlank(key) && org.apache.commons.lang3.StringUtils.isNotBlank(text)) {
            if (!verifyCaptcha(key, text)) {
                throw new ImgCaptchaException("img_captcha error");
            }
        }
        if("xm_ykyy_wx".equals(wxId)){
           return sendYKCaptcha(parameters);
        }else if("xm_zsyy_wx".equals(wxId)){
           return sendZSCaptcha(parameters);
        }else if ("xm_xzzx_wx".equals(wxId)){
        if ("xm_ykyy_wx".equals(wxId)) {
            return sendYKCaptcha(parameters);
        } else if ("xm_zsyy_wx".equals(wxId)) {
            return sendZSCaptcha(parameters);
        } else if ("xm_xzzx_wx".equals(wxId)) {
            return sendXZCaptcha(parameters);
        }else if ("sd_tnzyy_wx".equals(wxId)){
        } else if ("sd_tnzyy_wx".equals(wxId)) {
            return sendZBCaptcha(parameters);
        }else if ("xm_dsyy_wx".equals(wxId)){
        } else if ("xm_dsyy_wx".equals(wxId)) {
            return sendDsyyCaptcha(parameters);
        }else if("hz_yyyzh_wx".equals(wxId)){
        } else if ("hz_yyyzh_wx".equals(wxId)) {
            return sendTXYCaptcha(parameters);
        }else if("xm_mlwyy_wx".equals(wxId)){
        } else if ("xm_mlwyy_wx".equals(wxId)) {
            return sendMlwCaptcha(parameters);
        }
        throw new IllegalStateException("验证码发送失败");
@ -1132,20 +1147,20 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        String username = parameters.get("username");
        String type = parameters.get("type");
        String isDoctor = parameters.get("isDoctor");
        String msg="";
        String msg = "";
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id");
        }
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            String geetestChallenge = parameters.get("geetestChallenge");
            String geetestValidate = parameters.get("geetestValidate");
            String geetestSeccode = parameters.get("geetestSeccode");
            JSONObject resResult =validateGeet(geetestChallenge,geetestValidate,geetestSeccode,"1".equalsIgnoreCase(isDoctor)?"2":"1");
            if (resResult==null||!resResult.getString("result").equalsIgnoreCase("success")){
                throw new  Exception("验证失败");
            JSONObject resResult = validateGeet(geetestChallenge, geetestValidate, geetestSeccode, "1".equalsIgnoreCase(isDoctor) ? "2" : "1");
            if (resResult == null || !resResult.getString("result").equalsIgnoreCase("success")) {
                throw new Exception("验证失败");
            }
        }
        //验证请求间隔超时,防止频繁获取验证码
@ -1153,7 +1168,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
        if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
        if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
            String captcha = wlyyHospitalSysDictDO.getDictValue();
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
@ -1165,14 +1180,14 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }else {
            if ("1".equalsIgnoreCase(isDoctor)){
                String res = ykyyService.getResetCode("4",username);
                String resltCode ="";
        } else {
            if ("1".equalsIgnoreCase(isDoctor)) {
                String res = ykyyService.getResetCode("4", username);
                String resltCode = "";
                String captcha = "";
                if (!StringUtils.isEmpty(res)){
                if (!StringUtils.isEmpty(res)) {
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    if ("10000".equalsIgnoreCase(jsonObject.getString("code"))){
                    if ("10000".equalsIgnoreCase(jsonObject.getString("code"))) {
                        captcha = jsonObject.getString("value");
                        resltCode = jsonObject.getString("code");
                        msg = "发送成功";
@ -1193,25 +1208,25 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                }
                throw new IllegalStateException("验证码发送失败!");
            }else {
            } else {
                //发送短信获取验证码
                String captcha = wlyyRedisVerifyCodeService.getCodeNumber();
                ResultMsg result= null;
                if(StringUtils.isEmpty(type)){
                    String  res = ykyyService.getShortMessage("1",username);
                    String resltCode ="";
                ResultMsg result = null;
                if (StringUtils.isEmpty(type)) {
                    String res = ykyyService.getShortMessage("1", username);
                    String resltCode = "";
                    String captcha1 = "";
                    if (!StringUtils.isEmpty(res)){
                    if (!StringUtils.isEmpty(res)) {
                        JSONObject jsonObject = JSONObject.parseObject(res);
                        if ("10000".equalsIgnoreCase(jsonObject.getString("code"))){
                        if ("10000".equalsIgnoreCase(jsonObject.getString("code"))) {
                            captcha1 = jsonObject.getString("value");
                            resltCode = jsonObject.getString("code");
                        }else if("199".equalsIgnoreCase(jsonObject.getString("code"))){
                        } else if ("199".equalsIgnoreCase(jsonObject.getString("code"))) {
                            msg = jsonObject.getString("msg");
                            Oauth2Envelop<Captcha> oauth2Envelop = new Oauth2Envelop<>(msg, 199);
                            return new ResponseEntity<>(oauth2Envelop, HttpStatus.OK);
                        }else {
                            msg="发送失败";
                        } else {
                            msg = "发送失败";
                            Oauth2Envelop<Captcha> oauth2Envelop = new Oauth2Envelop<>(msg, -1);
                            return new ResponseEntity<>(oauth2Envelop, HttpStatus.OK);
                        }
@ -1229,9 +1244,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                        headers.set("Pragma", "no-cache");
                        return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
                    }
                }else if("1".equals(type)){
                    result = ykyyINSMSService.ykyySendSMS(username,"您好,您的手机登录短信验证码是:"+captcha+",5分钟内有效。");
                }else if("2".equals(type)) {
                } else if ("1".equals(type)) {
                    result = ykyyINSMSService.ykyySendSMS(username, "您好,您的手机登录短信验证码是:" + captcha + ",5分钟内有效。");
                } else if ("2".equals(type)) {
                    result = ykyyINSMSService.ykyySendSMS(username, "您好,您正在进行找回密码操作,您的短信验证码是:" + captcha + ",请勿将验证码告诉他人,5分钟内有效。");
                }
                if (result.isSuccess()) {
@ -1351,7 +1366,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            在网关处通过HTTP状态码告知前端是过期 还是账号在别处登陆
            实现同一账号只能在一处登陆*/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile")||request.getHeader("login-device").equalsIgnoreCase("pc"))) {
            if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile") || request.getHeader("login-device").equalsIgnoreCase("pc"))) {
                tokenStore.removeAccessToken(token.getValue());
                tokenStore.removeRefreshToken(token.getRefreshToken().getValue());
                token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
@ -1437,7 +1452,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            return handleOAuth2Exception(new Oauth2Envelop("短信请求频率过快,请稍后再试!", -1), e);
        } else if (e instanceof IllegalStateException) {
            return handleOAuth2Exception(new Oauth2Envelop(e.getMessage(), -1), e);
        }else if (e instanceof ImgCaptchaException) {
        } else if (e instanceof ImgCaptchaException) {
            return handleOAuth2Exception(new Oauth2Envelop("图片验证码错误", ResultStatus.IMG_CAPTCHA), e);
        }
        return handleOAuth2Exception(new Oauth2Envelop("请求失败", -1), e);
@ -1466,10 +1481,10 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }
    @RequestMapping(value = "/oauth/getHwlyyPublicKey", method = RequestMethod.GET)
    public ObjEnvelop getHwlyyPublicKey(){
    public ObjEnvelop getHwlyyPublicKey() {
        OauthKeypairDO keypairDO = oauthKeypairDao.findByCode("hwlyyKey");
        if(keypairDO==null){
        if (keypairDO == null) {
            KeyPair keyPair = com.yihu.jw.security.utils.RSAUtils.getKey();
            byte[] bytekey = SerializeUtil.ObjTOSerialize(keyPair);
            OauthKeypairDO kpDO = new OauthKeypairDO();
@ -1477,60 +1492,60 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            kpDO.setKeyPair(bytekey);
            keypairDO = oauthKeypairDao.save(kpDO);
        }
        KeyPair key = (KeyPair)SerializeUtil.unSerialize(keypairDO.getKeyPair());
        KeyPair key = (KeyPair) SerializeUtil.unSerialize(keypairDO.getKeyPair());
        PublickeyVO pk = new PublickeyVO();
        pk.setPublicKey(com.yihu.jw.security.utils.RSAUtils.generateBase64PublicKey(key));
        return ObjEnvelop.getSuccess("success", pk);
    }
    @RequestMapping(value = "/oauth/getHwlyyDecrypt", method = RequestMethod.POST)
    public ObjEnvelop getHwlyyDecrypt(String openid,String idcard,String wechatId,String code){
        Map<String,Object> rs = new HashedMap();
        try{
    public ObjEnvelop getHwlyyDecrypt(String openid, String idcard, String wechatId, String code) {
        Map<String, Object> rs = new HashedMap();
        try {
            OauthKeypairDO keypairDO = oauthKeypairDao.findByCode("hwlyyKey");
            KeyPair keyPair = (KeyPair)SerializeUtil.unSerialize(keypairDO.getKeyPair());
            logger.info("keyPair : "+keyPair.getPublic().toString());
            KeyPair keyPair = (KeyPair) SerializeUtil.unSerialize(keypairDO.getKeyPair());
            logger.info("keyPair : " + keyPair.getPublic().toString());
            //解密idcard,中山医院id通过openid获取,i健康通过直接加密传输
            if(org.apache.commons.lang3.StringUtils.isNotBlank(idcard)){
                rs.put("idcard",com.yihu.jw.security.utils.RSAUtils.decryptBase64(idcard, keyPair));
            }else {
                rs.put("idcard",idcard);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(idcard)) {
                rs.put("idcard", com.yihu.jw.security.utils.RSAUtils.decryptBase64(idcard, keyPair));
            } else {
                rs.put("idcard", idcard);
            }
            logger.info("参数 code : "+code);
            logger.info("参数 code : " + code);
            //解析code
            if(org.apache.commons.lang3.StringUtils.isNotBlank(code)){
                logger.info("解析前code : "+code);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(code)) {
                logger.info("解析前code : " + code);
                String c = com.yihu.jw.security.utils.RSAUtils.decryptBase64(code, keyPair);
                logger.info("解析前code : "+c);
                rs.put("code",c);
            }else {
                rs.put("code",code);
                logger.info("解析前code : " + c);
                rs.put("code", c);
            } else {
                rs.put("code", code);
            }
            //解密wechatId
            if(org.apache.commons.lang3.StringUtils.isNotBlank(wechatId)){
                String wxid =com.yihu.jw.security.utils.RSAUtils.decryptBase64(wechatId, keyPair);
                rs.put("wechatId",wxid);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(wechatId)) {
                String wxid = com.yihu.jw.security.utils.RSAUtils.decryptBase64(wechatId, keyPair);
                rs.put("wechatId", wxid);
                //解密openid
                if(org.apache.commons.lang3.StringUtils.isNotBlank(openid)){
                if (org.apache.commons.lang3.StringUtils.isNotBlank(openid)) {
                    String opid = com.yihu.jw.security.utils.RSAUtils.decryptBase64(openid, keyPair);
                    rs.put("openid",opid);
                    if("xm_zsyy_wx".equals(wxid)){
                        JSONObject patient =  userDetailsService.getHLWyyUser(opid);
                        rs.put("idcard",patient.getString("idcard"));
                        rs.put("mobile",patient.getString("mobile"));
                    rs.put("openid", opid);
                    if ("xm_zsyy_wx".equals(wxid)) {
                        JSONObject patient = userDetailsService.getHLWyyUser(opid);
                        rs.put("idcard", patient.getString("idcard"));
                        rs.put("mobile", patient.getString("mobile"));
                    }
                }else {
                    rs.put("openid",openid);
                } else {
                    rs.put("openid", openid);
                }
            }else {
                rs.put("wechatId",wechatId);
            } else {
                rs.put("wechatId", wechatId);
            }
        }catch (Exception e){
        } catch (Exception e) {
            logger.error(e);
        }
        return ObjEnvelop.getSuccess("success", rs);
@ -1538,34 +1553,35 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 卫健委授权登录
     *
     * @param authCode
     * @param client_id
     * @return
     */
    @RequestMapping(value = "/oauth/wjwLogin", method = RequestMethod.POST)
    public ObjEnvelop getWjwDecrypt(String authCode,String client_id) {
    public ObjEnvelop getWjwDecrypt(String authCode, String client_id) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
        }
        try {
            logger.info("authCode :"+authCode);
            logger.info("authCode :" + authCode);
            String str = URLDecoder.decode(authCode,"UTF-8");
            logger.info("base64 :"+str);
            String str = URLDecoder.decode(authCode, "UTF-8");
            logger.info("base64 :" + str);
            String data = new String(Base64Utils.decode((str.getBytes())));
            //固定秘钥解密
            String key = "FEA5049E4CCD16A9";
            String result = AesEncryptUtils.decrypt(data,key);
          /*  String result = AES.decrypt(key,data);*/
            logger.info("wjwLogin :"+result);
            String result = AesEncryptUtils.decrypt(data, key);
            /*  String result = AES.decrypt(key,data);*/
            logger.info("wjwLogin :" + result);
            BasePatientDO patientDO = oauthWjwConfigService.savePatient(result);
            logger.info("授权进来1");
            if(patientDO == null){
            if (patientDO == null) {
                return ObjEnvelop.getError("授权登录失败!");
            }
@ -1575,7 +1591,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            logger.info("授权进来3");
            Map<String, String> parameters = new HashedMap();
            parameters.put("username",patientDO.getIdcard());
            parameters.put("username", patientDO.getIdcard());
            parameters.put("grant_type", "ihealthCode");
            TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -1605,9 +1621,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            baseLoginLogDO.setLoginType(loginType);
            baseLoginLogService.save(baseLoginLogDO);
            return ObjEnvelop.getSuccess("success",wlyyUserSimple);
            return ObjEnvelop.getSuccess("success", wlyyUserSimple);
        }catch (Exception e){
        } catch (Exception e) {
            logger.error(e);
        }
        return ObjEnvelop.getError("登录失败!");
@ -1616,28 +1632,29 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 医联康护授权登录
     *
     * @param authCode
     * @param client_id
     * @return
     */
    @RequestMapping(value = "/oauth/ylkhLogin", method = RequestMethod.POST)
    public ObjEnvelop getYlkhDecrypt(String authCode,String client_id) {
    public ObjEnvelop getYlkhDecrypt(String authCode, String client_id) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
        }
        try {
            logger.info("authCode :"+authCode);
            logger.info("authCode :" + authCode);
            //固定秘钥解密
            String key = "46A61629A19AE04C";
            String result = AesEncryptUtils.decrypt(authCode,key);
            logger.info("wjwLogin :"+result);
            String result = AesEncryptUtils.decrypt(authCode, key);
            logger.info("wjwLogin :" + result);
            BasePatientDO patientDO = oauthWjwConfigService.savePatient(result);
            if(patientDO == null){
            if (patientDO == null) {
                return ObjEnvelop.getError("授权登录失败!");
            }
@ -1645,9 +1662,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            Map<String, String> parameters = new HashedMap();
            parameters.put("username",patientDO.getIdcard());
            parameters.put("username", patientDO.getIdcard());
            parameters.put("grant_type", "ihealthCode");
            parameters.put("login_type","4");
            parameters.put("login_type", "4");
            TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
            if (authenticatedClient != null) {
@ -1676,9 +1693,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            baseLoginLogDO.setLoginType(loginType);
            baseLoginLogService.save(baseLoginLogDO);
            return ObjEnvelop.getSuccess("success",wlyyUserSimple);
            return ObjEnvelop.getSuccess("success", wlyyUserSimple);
        }catch (Exception e){
        } catch (Exception e) {
            logger.error(e);
        }
        return ObjEnvelop.getError("登录失败!");
@ -1695,20 +1712,20 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
//    }
    @RequestMapping(value = "/oauth/getCaQRCode", method = RequestMethod.GET)
    public ObjEnvelop getCaQRCode(HttpServletRequest request){
    public ObjEnvelop getCaQRCode(HttpServletRequest request) {
        logger.info("/oauth/getCaQRCode");
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
            String sys ="JKZLHLWYLJKGLPT";
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")) {
            String sys = "JKZLHLWYLJKGLPT";
            return ObjEnvelop.getSuccess("success", oauthCaConfigSerivce.getQRCode(sys));
        }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
        } else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")) {
            return ObjEnvelop.getSuccess("success", xzzxService.getQRCode());
        }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
        } else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
            return ObjEnvelop.getSuccess("success", ykyyService.getQRCode());
        }else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")){
        } else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")) {
            return ObjEnvelop.getSuccess("success", hcyyService.getQRCode(getIpAddress(request)));
        }else if (wechatId.equalsIgnoreCase("xm_dsyy_wx")){
        } else if (wechatId.equalsIgnoreCase("xm_dsyy_wx")) {
            return ObjEnvelop.getSuccess("success", dsyyService.getQRCode());
        }else {
        } else {
            return ObjEnvelop.getSuccess("success", null);
        }
@ -1716,88 +1733,89 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    /**
     * 医生二维码登录
     *
     * @param qrcode
     * @param client_id
     * @param login_type 2
     * @return
     */
    @RequestMapping(value = "/oauth/checkCaQRCodeLogin", method = RequestMethod.POST)
    public ObjEnvelop checkCaQRCodeLogin(String qrcode,String client_id,String login_type,HttpServletRequest request){
    public ObjEnvelop checkCaQRCodeLogin(String qrcode, String client_id, String login_type, HttpServletRequest request) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
        }
        String username = null;
        String openId= null;
        String openId = null;
        JSONObject rs = new JSONObject();
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")) {
            rs = oauthCaConfigSerivce.getQueryQRCode(qrcode);
            JSONObject data = rs.getJSONObject("data");
            String qrCodeStatus = data.getString("qrCodeStatus");
            if(!"LoginQrCodeBeenScan".equals(qrCodeStatus)){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"LoginQrCodeBeenScan".equals(qrCodeStatus)) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            username = data.getString("userIdCardNum");
        }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
        } else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")) {
            rs = xzzxService.getTokeninfo(qrcode);
            JSONObject jsonObject = rs.getJSONObject("data");
            logger.info("查询登录信息"+rs);
            logger.info("查询登录信息" + rs);
            String qrCodeStatus = rs.getString("status");
            if(!"0".equals(qrCodeStatus)){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"0".equals(qrCodeStatus)) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            username = jsonObject.getString("userIdcardNum");
            openId = jsonObject.getString("uniqueid");
            jsonObject.put("qrCodeStatus","LoginQrCodeBeenScan");
            rs.put("code",1000);
        }else if (wechatId.equalsIgnoreCase("xm_dsyy_wx")){
            jsonObject.put("qrCodeStatus", "LoginQrCodeBeenScan");
            rs.put("code", 1000);
        } else if (wechatId.equalsIgnoreCase("xm_dsyy_wx")) {
            rs = dsyyService.getTokeninfo(qrcode);
            JSONObject jsonObject = rs.getJSONObject("data");
            logger.info("查询登录信息"+rs);
            logger.info("查询登录信息" + rs);
            String qrCodeStatus = rs.getString("status");
            if(!"0".equals(qrCodeStatus)){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"0".equals(qrCodeStatus)) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            username = jsonObject.getString("userIdcardNum");
            openId = jsonObject.getString("openId");
            jsonObject.put("qrCodeStatus","LoginQrCodeBeenScan");
            rs.put("code",1000);
        }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
            jsonObject.put("qrCodeStatus", "LoginQrCodeBeenScan");
            rs.put("code", 1000);
        } else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
            rs = ykyyService.getTokeninfo(qrcode);
            JSONObject jsonObject = rs.getJSONObject("data");
            logger.info("查询登录信息"+rs);
            logger.info("查询登录信息" + rs);
            String qrCodeStatus = rs.getString("code");
            if(!"200".equalsIgnoreCase(qrCodeStatus)){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"200".equalsIgnoreCase(qrCodeStatus)) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            if(!"LoginQrCodeBeenScan".equalsIgnoreCase(jsonObject.getString("qrCodeStatus"))){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"LoginQrCodeBeenScan".equalsIgnoreCase(jsonObject.getString("qrCodeStatus"))) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            username = jsonObject.getString("userIdCardNum");
            openId = jsonObject.getString("userJobNum");
            jsonObject.put("qrCodeStatus",jsonObject.getString("qrCodeStatus"));
            rs.put("code",1000);
        }else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")){
            jsonObject.put("qrCodeStatus", jsonObject.getString("qrCodeStatus"));
            rs.put("code", 1000);
        } else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")) {
            String ip = getIpAddress(request);
            rs = hcyyService.getTokeninfo(qrcode,ip);
            if (rs.getString("data")==null||rs.getString("data")==""){
                return ObjEnvelop.getSuccess("error",rs);
            rs = hcyyService.getTokeninfo(qrcode, ip);
            if (rs.getString("data") == null || rs.getString("data") == "") {
                return ObjEnvelop.getSuccess("error", rs);
            }
            JSONObject jsonObject = rs.getJSONObject("data");
            logger.info("查询登录信息"+rs);
            logger.info("查询登录信息" + rs);
            String qrCodeStatus = rs.getString("code");
            if(!"10000".equalsIgnoreCase(qrCodeStatus)){
                return ObjEnvelop.getSuccess("error",rs);
            if (!"10000".equalsIgnoreCase(qrCodeStatus)) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            if (jsonObject==null){
                return ObjEnvelop.getSuccess("error",rs);
            if (jsonObject == null) {
                return ObjEnvelop.getSuccess("error", rs);
            }
            username = jsonObject.getString("idcard");
            jsonObject.put("qrCodeStatus","LoginQrCodeBeenScan");
            rs.put("code",1000);
            jsonObject.put("qrCodeStatus", "LoginQrCodeBeenScan");
            rs.put("code", 1000);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(username)){
        if (org.apache.commons.lang.StringUtils.isNotBlank(username)) {
            BaseDoctorDO doctorDO = doctorDao.findByIdcard(username);
            doctorDO.setOpenid(openId);
            doctorDO.setCaFlag(1);
@ -1807,8 +1825,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
        Map<String, String> parameters = new HashedMap();
        parameters.put("username",username);
        parameters.put("login_type","2");
        parameters.put("username", username);
        parameters.put("login_type", "2");
        parameters.put("grant_type", "ihealthDcotor");
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -1836,14 +1854,15 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        baseLoginLogDO.setUserAgent(userAgent);
        baseLoginLogDO.setLoginType(login_type);
        baseLoginLogService.save(baseLoginLogDO);
        rs.put("WlyyUserSimple",wlyyUserSimple);
        return ObjEnvelop.getSuccess("success",rs);
        rs.put("WlyyUserSimple", wlyyUserSimple);
        return ObjEnvelop.getSuccess("success", rs);
    }
    /**
     * 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串
     *
     * @param request
     * @return
     */
@ -1863,29 +1882,29 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            logger.info("ip="+ip);
            if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
            logger.info("ip=" + ip);
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
                ip = inet.getHostAddress();
            }
        }
        return ip;
    }
    @RequestMapping(value = "/oauth/getOauthQRCodeImg", method = RequestMethod.GET)
    public ObjEnvelop getOauthQRCodeImg(){
        try{
            logger.info("/oauth/getOauthQRCodeImg1:"+" startTime:"+ DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss:SSS"));
            Map<String,Object> rs = oauthYlzConfigService.getOauthQRCodeImg();
            logger.info("/oauth/getOauthQRCodeImg2:"+" endTime:"+ DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss:SSS") );
    public ObjEnvelop getOauthQRCodeImg() {
        try {
            logger.info("/oauth/getOauthQRCodeImg1:" + " startTime:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
            Map<String, Object> rs = oauthYlzConfigService.getOauthQRCodeImg();
            logger.info("/oauth/getOauthQRCodeImg2:" + " endTime:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
            return ObjEnvelop.getSuccess("success", rs);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("getOauthQRCodeImg error");
        }
@ -1895,22 +1914,22 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
     * 居民二维码登录
     */
    @RequestMapping(value = "/oauth/checkQRCodeLogin", method = RequestMethod.POST)
    public ObjEnvelop checkQRCodeLogin(String no,String client_id,String login_type){
    public ObjEnvelop checkQRCodeLogin(String no, String client_id, String login_type) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
        }
        Map<String,Object> map = oauthYlzConfigService.checkOauthQRCode(no);
        String sCode = (String)map.get("sCode");
        if(!"succ".equals(sCode)){
            return ObjEnvelop.getSuccess("error",map);
        Map<String, Object> map = oauthYlzConfigService.checkOauthQRCode(no);
        String sCode = (String) map.get("sCode");
        if (!"succ".equals(sCode)) {
            return ObjEnvelop.getSuccess("error", map);
        }
        BasePatientDO patient = (BasePatientDO)map.get("patient");
        BasePatientDO patient = (BasePatientDO) map.get("patient");
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
        Map<String, String> parameters = new HashedMap();
        parameters.put("username",patient.getIdcard());
        parameters.put("username", patient.getIdcard());
        parameters.put("grant_type", "ihealthCode");
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -1939,21 +1958,22 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        baseLoginLogDO.setUserAgent(userAgent);
        baseLoginLogDO.setLoginType(loginType);
        baseLoginLogService.save(baseLoginLogDO);
        map.put("WlyyUserSimple",wlyyUserSimple);
        map.put("WlyyUserSimple", wlyyUserSimple);
        map.remove("patient");
        return ObjEnvelop.getSuccess("success",map);
        return ObjEnvelop.getSuccess("success", map);
    }
    /**
     * I健康医生端授权登录
     * @param code 医生code
     *
     * @param code        医生code
     * @param client_id
     * @param login_type 3
     * @param login_type  3
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "/oauth/checkWlyyLogin", method = RequestMethod.POST)
    public ObjEnvelop checkQRCodeLogin(String code,String client_id,String login_type,HttpSession httpSession){
    public ObjEnvelop checkQRCodeLogin(String code, String client_id, String login_type, HttpSession httpSession) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
@ -1961,19 +1981,19 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(code)) {
            throw new InvalidRequestException("doctor is null");
        }
        logger.info("origin doctorCode :"+code);
        logger.info("origin doctorCode :" + code);
        KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
        String doctorCode = com.yihu.jw.security.utils.RSAUtils.decryptBase64(code, keyPair);
        logger.info("after doctorCode :"+doctorCode);
        logger.info("after doctorCode :" + doctorCode);
        JSONObject map = null;
        try{
            map= oauthWlyyConfigService.checkWlyyDoctor(doctorCode);
        }catch (Exception e){
        try {
            map = oauthWlyyConfigService.checkWlyyDoctor(doctorCode);
        } catch (Exception e) {
            logger.error(e);
            return ObjEnvelop.getError("授权失败");
        }
        String authCode = map.getString("authCode");
        if(!"1".equals(authCode)){
        if (!"1".equals(authCode)) {
            map.remove("doctor");
            return ObjEnvelop.getError("授权失败");
        }
@ -1982,8 +2002,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        JSONObject doctor = map.getJSONObject("doctor");
        Map<String, String> parameters = new HashedMap();
        parameters.put("login_type","2");
        parameters.put("username",doctor.getString("idcard"));
        parameters.put("login_type", "2");
        parameters.put("username", doctor.getString("idcard"));
        parameters.put("grant_type", "ihealthDcotor");
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -2012,22 +2032,23 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        baseLoginLogDO.setUserAgent(userAgent);
        baseLoginLogDO.setLoginType(loginType);
        baseLoginLogService.save(baseLoginLogDO);
        map.put("WlyyUserSimple",wlyyUserSimple);
        map.put("WlyyUserSimple", wlyyUserSimple);
        map.remove("doctor");
        return ObjEnvelop.getSuccess("success",map);
        return ObjEnvelop.getSuccess("success", map);
    }
    /**
     * I健康医生端授权登录
     * @param code 医生code
     *
     * @param code        医生code
     * @param client_id
     * @param login_type 3
     * @param login_type  3
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "/oauth/checkWlyyUserLogin", method = RequestMethod.POST)
    public ObjEnvelop checkQRUserCodeLogin(String code,String client_id,String login_type,HttpSession httpSession){
    public ObjEnvelop checkQRUserCodeLogin(String code, String client_id, String login_type, HttpSession httpSession) {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
@ -2035,19 +2056,19 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (StringUtils.isEmpty(code)) {
            throw new InvalidRequestException("doctor is null");
        }
        logger.info("origin doctorCode :"+code);
        logger.info("origin doctorCode :" + code);
        KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
        String doctorCode = com.yihu.jw.security.utils.RSAUtils.decryptBase64(code, keyPair);
        logger.info("after doctorCode :"+doctorCode);
        logger.info("after doctorCode :" + doctorCode);
        JSONObject map = null;
        try{
            map= oauthWlyyConfigService.checkWlyyUserDoctor(doctorCode);
        }catch (Exception e){
        try {
            map = oauthWlyyConfigService.checkWlyyUserDoctor(doctorCode);
        } catch (Exception e) {
            logger.error(e);
            return ObjEnvelop.getError("授权失败");
        }
        String authCode = map.getString("authCode");
        if(!"1".equals(authCode)){
        if (!"1".equals(authCode)) {
            map.remove("doctor");
            return ObjEnvelop.getError("授权失败");
        }
@ -2056,8 +2077,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        JSONObject doctor = map.getJSONObject("doctor");
        Map<String, String> parameters = new HashedMap();
        parameters.put("login_type","2");
        parameters.put("username",doctor.getString("idcard"));
        parameters.put("login_type", "2");
        parameters.put("username", doctor.getString("idcard"));
        parameters.put("grant_type", "ihealthCode");
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -2086,16 +2107,16 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        baseLoginLogDO.setUserAgent(userAgent);
        baseLoginLogDO.setLoginType(loginType);
        baseLoginLogService.save(baseLoginLogDO);
        map.put("WlyyUserSimple",wlyyUserSimple);
        map.put("WlyyUserSimple", wlyyUserSimple);
        map.remove("doctor");
        return ObjEnvelop.getSuccess("success",map);
        return ObjEnvelop.getSuccess("success", map);
    }
    @RequestMapping(value = "/oauth/imgCaptcha", method = RequestMethod.GET)
    @ApiOperation("生成验证码")
    public ObjEnvelop createCaptcha()throws Exception{
        return ObjEnvelop.getSuccess("success",generateCaptcha());
    public ObjEnvelop createCaptcha() throws Exception {
        return ObjEnvelop.getSuccess("success", generateCaptcha());
    }
    private Map<String, String> generateCaptcha() throws IOException {
@ -2106,7 +2127,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        properties.put("kaptcha.textproducer.font.size", "45");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        properties.put("kaptcha.textproducer.char.string","0123456789");
        properties.put("kaptcha.textproducer.char.string", "0123456789");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
        String captchaText = captchaProducer.createText();
@ -2114,7 +2135,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Img = new BASE64Encoder().encode(outputStream.toByteArray());
        base64Img = "data:image/jpeg;base64,"+base64Img.replaceAll("\n", "").replaceAll("\r", "");//格式化处理
        base64Img = "data:image/jpeg;base64," + base64Img.replaceAll("\n", "").replaceAll("\r", "");//格式化处理
        String key = "hwlyy:captcha:" + UUID.randomUUID().toString();
@ -2123,16 +2144,16 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        data.put("image", base64Img);
        data.put("format", "png");
        redisTemplate.opsForValue().set(key,captchaText.toLowerCase(),5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(key, captchaText.toLowerCase(), 5, TimeUnit.MINUTES);
        return data;
    }
    @RequestMapping(value = "/oauth/verifyCaptcha", method = RequestMethod.GET)
    @ApiOperation("验证图形验证码")
    public boolean verifyCaptcha(String key,String text){
    public boolean verifyCaptcha(String key, String text) {
        boolean pass = false;
        String captcha = redisTemplate.opsForValue().get(key);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(captcha)&& captcha.equals(text.toLowerCase())){
        if (org.apache.commons.lang3.StringUtils.isNotBlank(captcha) && captcha.equals(text.toLowerCase())) {
            pass = true;
            redisTemplate.delete(key);
        }
@ -2142,20 +2163,20 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    @RequestMapping(value = "/oauth/getSsoPublicKey", method = RequestMethod.GET)
    @ApiOperation("获取通用公钥")
    public ObjEnvelop getSsoPublicKey(String code,String appId)throws Exception{
        return ObjEnvelop.getSuccess("success",oauthSsoService.getSsoPublic(code,appId));
    public ObjEnvelop getSsoPublicKey(String code, String appId) throws Exception {
        return ObjEnvelop.getSuccess("success", oauthSsoService.getSsoPublic(code, appId));
    }
    @RequestMapping(value = "/oauth/test", method = RequestMethod.GET)
    @ApiOperation("test dd")
    public ObjEnvelop test()throws Exception{
        return ObjEnvelop.getSuccess("success",oauthSsoService.getAuthCode());
    public ObjEnvelop test() throws Exception {
        return ObjEnvelop.getSuccess("success", oauthSsoService.getAuthCode());
    }
    @RequestMapping(value = "/oauth/ssoPatientLogin", method = RequestMethod.POST)
    public ObjEnvelop ssoPatientLogin(String authCode,String client_id,String code,String appId,String login_type,String openId,String memberId){
    public ObjEnvelop ssoPatientLogin(String authCode, String client_id, String code, String appId, String login_type, String openId, String memberId) {
        if (!wechatId.equalsIgnoreCase("xm_hcyy_wx")){
        if (!wechatId.equalsIgnoreCase("xm_hcyy_wx")) {
            if (StringUtils.isEmpty(client_id)) {
                throw new InvalidRequestException("client_id is null");
            }
@ -2173,26 +2194,26 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        try {
            Map<String, String> parameters = new HashedMap();
            if (!wechatId.equalsIgnoreCase("xm_hcyy_wx")) {
                logger.info("authCode :"+authCode);
                logger.info("authCode :" + authCode);
                Map<String,Object> rs = oauthSsoService.savePatient(code,appId,authCode,wechatId);
                Map<String, Object> rs = oauthSsoService.savePatient(code, appId, authCode, wechatId);
                Integer c = (Integer) rs.get("code");
                if(c != 1){
                    return ObjEnvelop.getError(rs.get("mes")+"");
                if (c != 1) {
                    return ObjEnvelop.getError(rs.get("mes") + "");
                }
                BasePatientDO patientDO = (BasePatientDO)rs.get("patient");
                if(patientDO==null){
                BasePatientDO patientDO = (BasePatientDO) rs.get("patient");
                if (patientDO == null) {
                    return ObjEnvelop.getError("获取居民信息失败");
                }
                parameters.put("username",patientDO.getIdcard());
                parameters.put("username", patientDO.getIdcard());
                parameters.put("grant_type", "ihealthCode");
            }else {
                JSONObject patient = userDetailsService.getHcHLWyyUser(openId,memberId);
                if (patient==null){
            } else {
                JSONObject patient = userDetailsService.getHcHLWyyUser(openId, memberId);
                if (patient == null) {
                    return ObjEnvelop.getError("获取居民信息失败");
                }
                parameters.put("username",patient.getString("IdCardNo"));
                parameters.put("username", patient.getString("IdCardNo"));
                parameters.put("grant_type", "ihealthCode");
            }
            ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
@ -2224,9 +2245,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            baseLoginLogDO.setLoginType(loginType);
            baseLoginLogService.save(baseLoginLogDO);
            return ObjEnvelop.getSuccess("success",wlyyUserSimple);
            return ObjEnvelop.getSuccess("success", wlyyUserSimple);
        }catch (Exception e){
        } catch (Exception e) {
            logger.error(e);
        }
        return ObjEnvelop.getError("登录失败!");
@ -2303,8 +2324,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }*/
    @RequestMapping(value = "/oauth/registerPatientAndLogin", method = RequestMethod.POST)
    public ObjEnvelop registerPatientAndLogin(String name, String mobile, String idcard, String ssc, String pw,
                                              String client_id,String login_type,String captcha,String openid,String wxId
    ,String geetestChallenge,String geetestValidate,String geetestSeccode )throws Exception{
                                              String client_id, String login_type, String captcha, String openid, String wxId
            , String geetestChallenge, String geetestValidate, String geetestSeccode) throws Exception {
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
@ -2319,30 +2340,30 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (resResult==null||!resResult.getString("result").equalsIgnoreCase("success")){
            return ObjEnvelop.getError("验证失败!");
        }*/
        if("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            try {
                List<BasePatientDO> basePatientDOS =basePatientDao.findByMobileAndDel(mobile,"1");
                List<BasePatientDO> basePatientDOS = basePatientDao.findByMobileAndDel(mobile, "1");
                boolean localFlag = false;
                boolean ykFlag = false;
                String msg = "";
                if (null!=basePatientDOS&&basePatientDOS.size()>0){
                if (null != basePatientDOS && basePatientDOS.size() > 0) {
                    localFlag = true;
                }
                BasePatientDO basePatientDO = new BasePatientDO();
                String r =ykyyService.getRegisterUser(mobile,pw,captcha,"a01522","xmijk","xmijk");
                if (!StringUtils.isEmpty(r)){
                String r = ykyyService.getRegisterUser(mobile, pw, captcha, "a01522", "xmijk", "xmijk");
                if (!StringUtils.isEmpty(r)) {
                    JSONObject jsonObject = JSONObject.parseObject(r);
                    if (null!=jsonObject.get("code")&&"200".equalsIgnoreCase(jsonObject.get("code").toString())){
                    if (null != jsonObject.get("code") && "200".equalsIgnoreCase(jsonObject.get("code").toString())) {
                        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
                        basePatientDO.setUserId(jsonObject1.getString("ID"));
                    }else if (null!=jsonObject.get("code")&&"199".equalsIgnoreCase(jsonObject.get("code").toString())){
                    } else if (null != jsonObject.get("code") && "199".equalsIgnoreCase(jsonObject.get("code").toString())) {
                        msg = jsonObject.getString("msg");
                        ykFlag = true;
                    }
                }
                basePatientDO.setMobile(mobile);
                String salt = UUID.randomUUID().toString().substring(0,5);
                String salt = UUID.randomUUID().toString().substring(0, 5);
                basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                basePatientDO.setSalt(salt);
                basePatientDO.setDel("1");
@ -2353,7 +2374,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                basePatientDO.setUpdateTime(new Date());
                BasePatientDO patientDO = basePatientDao.save(basePatientDO);
                if (localFlag&&ykFlag){
                if (localFlag && ykFlag) {
                    return ObjEnvelop.getError("该手机号已经注册过");
                }
@ -2361,7 +2382,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                Map<String, String> parameters = new HashedMap();
                parameters.put("username",patientDO.getMobile());
                parameters.put("username", patientDO.getMobile());
                parameters.put("grant_type", "ihealthCode");
                TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -2391,31 +2412,31 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                baseLoginLogDO.setLoginType(loginType);
                baseLoginLogService.save(baseLoginLogDO);
                return ObjEnvelop.getSuccess("success",wlyyUserSimple);
                return ObjEnvelop.getSuccess("success", wlyyUserSimple);
            }catch (Exception e){
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
        } else {
            try {
                Map<String,Object> rs = registerService.registerPatient(mobile,pw,name,idcard,ssc,openid);
                Map<String, Object> rs = registerService.registerPatient(mobile, pw, name, idcard, ssc, openid);
                String code = rs.get("code").toString();
                if(!"1".equals(code)){
                if (!"1".equals(code)) {
                    ObjEnvelop objEnvelop = new ObjEnvelop();
                    objEnvelop.setObj(rs);
                    objEnvelop.setStatus(-1);
                    objEnvelop.setMessage(rs.get("mes")+"");
                    objEnvelop.setMessage(rs.get("mes") + "");
                    return objEnvelop;
                }
                BasePatientDO patientDO = (BasePatientDO)rs.get("patient");
                BasePatientDO patientDO = (BasePatientDO) rs.get("patient");
                ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
                Map<String, String> parameters = new HashedMap();
                parameters.put("username",patientDO.getMobile());
                parameters.put("username", patientDO.getMobile());
                parameters.put("grant_type", "ihealthCode");
                TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
@ -2445,9 +2466,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                baseLoginLogDO.setLoginType(loginType);
                baseLoginLogService.save(baseLoginLogDO);
                return ObjEnvelop.getSuccess("success",wlyyUserSimple);
                return ObjEnvelop.getSuccess("success", wlyyUserSimple);
            }catch (Exception e){
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
@ -2456,37 +2477,37 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }
    @RequestMapping(value = "/oauth/findPatientPw", method = RequestMethod.POST)
    public Envelop findPatientPw(String mobile,String client_id,String login_type,String captcha
            ,String pw,String key,String idcard,String text){
    public Envelop findPatientPw(String mobile, String client_id, String login_type, String captcha
            , String pw, String key, String idcard, String text) {
        try {
            if(StringUtils.isEmpty(idcard)){
            if (StringUtils.isEmpty(idcard)) {
                return ObjEnvelop.getError("手机号码不能为空!");
            }
            if(StringUtils.isEmpty(mobile)){
            if (StringUtils.isEmpty(mobile)) {
                return ObjEnvelop.getError("手机号码不能为空!");
            }
            if(StringUtils.isEmpty(key)||StringUtils.isEmpty(text)){
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(text)) {
                return ObjEnvelop.getError("图形验证码不能为空!");
            }
            if(!verifyCaptcha(key,text)){
            if (!verifyCaptcha(key, text)) {
                throw new ImgCaptchaException("图形验证码错误!");
            }
            Integer re = registerService.checkeMobileAndIdcard(mobile,idcard);
            if(re == -1){
            Integer re = registerService.checkeMobileAndIdcard(mobile, idcard);
            if (re == -1) {
                return ObjEnvelop.getError("居民不存在!");
            }else if(re == -2){
            } else if (re == -2) {
                return ObjEnvelop.getError("身份证和手机号码不匹配!");
            }
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
            if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
            if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())) {
                }else {
                } else {
                    return ObjEnvelop.getError("短信验证码错误!");
                }
            }else {
            } else {
                if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
                    //验证码正确
                } else {
@ -2495,129 +2516,131 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            }
            String rs = registerService.updatePatientPw(pw,mobile);
            if("ok".equals(rs)){
            String rs = registerService.updatePatientPw(pw, mobile);
            if ("ok".equals(rs)) {
                return ObjEnvelop.getSuccess("修改成功!");
            }
            return ObjEnvelop.getError("手机号未注册!");
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Envelop.getError("系统繁忙,请稍后在试");
    }
    @RequestMapping(value = "/oauth/findDoctorPw", method = RequestMethod.POST)
    public Envelop findDoctorPw(String mobile,String client_id,String captcha,String pw) throws Exception{
        if("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
           String response =  ykyyService.ResetPwd(mobile,pw,captcha);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(response)){
    public Envelop findDoctorPw(String mobile, String client_id, String captcha, String pw) throws Exception {
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            String response = ykyyService.ResetPwd(mobile, pw, captcha);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(response)) {
                JSONObject object = JSONObject.parseObject(response);
                if (object.getString("code").equalsIgnoreCase("10000")){
                if (object.getString("code").equalsIgnoreCase("10000")) {
                    return ObjEnvelop.getSuccess("修改成功!");
                }else {
                } else {
                    return ObjEnvelop.getError("修改失败!");
                }
            }else {
            } else {
                return ObjEnvelop.getError("修改失败!");
            }
        }else if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
        } else if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)) {
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
            if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
            if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())) {
                }else {
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }else {
            } else {
                if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
                    //验证码正确
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }
            String rs = registerService.updateDoctorPw(mobile,pw,wechatId);
            if("ok".equals(rs)){
            String rs = registerService.updateDoctorPw(mobile, pw, wechatId);
            if ("ok".equals(rs)) {
                return ObjEnvelop.getSuccess("修改成功!");
            }
            return ObjEnvelop.getError("手机号未注册!");
        }else if ("sd_tnzyy_wx".equalsIgnoreCase(wechatId)){
        } else if ("sd_tnzyy_wx".equalsIgnoreCase(wechatId)) {
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
            if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
            if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())) {
                }else {
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }else {
            } else {
                if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
                    //验证码正确
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }
            String rs = registerService.updateDoctorPw(mobile,pw,wechatId);
            if("ok".equals(rs)){
            String rs = registerService.updateDoctorPw(mobile, pw, wechatId);
            if ("ok".equals(rs)) {
                return ObjEnvelop.getSuccess("修改成功!");
            }
            return ObjEnvelop.getError("手机号未注册!");
        }else if ("xm_xzzx_wx".equalsIgnoreCase(wechatId)){
        } else if ("xm_xzzx_wx".equalsIgnoreCase(wechatId)) {
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
            if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
            if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())) {
                }else {
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }else {
            } else {
                if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
                    //验证码正确
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }
            String rs = registerService.updateDoctorPw(mobile,pw,wechatId);
            if("ok".equals(rs)){
            String rs = registerService.updateDoctorPw(mobile, pw, wechatId);
            if ("ok".equals(rs)) {
                return ObjEnvelop.getSuccess("修改成功!");
            }
            return ObjEnvelop.getError("手机号未注册!");
        }else if ("hz_yyyzh_wx".equalsIgnoreCase(wechatId)){
        } else if ("hz_yyyzh_wx".equalsIgnoreCase(wechatId)) {
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedSMS");
            if (wlyyHospitalSysDictDO!=null&&!StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())){
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
            if (wlyyHospitalSysDictDO != null && !StringUtils.isEmpty(wlyyHospitalSysDictDO.getDictValue())) {
                if (captcha.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())) {
                }else {
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }else {
            } else {
                if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
                    //验证码正确
                } else {
                    return ObjEnvelop.getError("验证码错误!");
                }
            }
            String rs = registerService.updateDoctorPw(mobile,pw,wechatId);
            if("ok".equals(rs)){
            String rs = registerService.updateDoctorPw(mobile, pw, wechatId);
            if ("ok".equals(rs)) {
                return ObjEnvelop.getSuccess("修改成功!");
            }
            return ObjEnvelop.getError("手机号未注册!");
        }else {
        } else {
            return ObjEnvelop.getError("暂未开放");
        }
    }
    @RequestMapping(value = "/oauth/updateDoctorMoble", method = RequestMethod.POST)
    public Envelop updateDoctorMoble(String id,String mobile,String client_id,String captcha){
    public Envelop updateDoctorMoble(String id, String mobile, String client_id, String captcha) {
        if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
            //验证码正确
        } else {
            return ObjEnvelop.getError("验证码错误!");
        }
        String rs = registerService.updateDoctorMoble(id,mobile);
        if("ok".equals(rs)){
        String rs = registerService.updateDoctorMoble(id, mobile);
        if ("ok".equals(rs)) {
            return ObjEnvelop.getSuccess("修改成功!");
        }
@ -2626,7 +2649,6 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }
    /**
     * 眼科通登陆
     *
@ -2651,19 +2673,19 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        String captcha = parameters.get("captcha");
        String loginType = parameters.get("login_type");
        String appletCode = parameters.get("appletCode");
        String isNeedGeet= "0";//1需要 0不需要
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO= wlyyhospitalSysdictDao.findDictById("isNeedGeet");
        if (wlyyHospitalSysDictDO!=null){
            isNeedGeet=wlyyHospitalSysDictDO.getDictValue();
        String isNeedGeet = "0";//1需要 0不需要
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedGeet");
        if (wlyyHospitalSysDictDO != null) {
            isNeedGeet = wlyyHospitalSysDictDO.getDictValue();
        }
        if (parameters.get("mobile")==null){
            if ("1".equalsIgnoreCase(isNeedGeet)){
        if (parameters.get("mobile") == null) {
            if ("1".equalsIgnoreCase(isNeedGeet)) {
                String geetestChallenge = parameters.get("geetestChallenge");
                String geetestValidate = parameters.get("geetestValidate");
                String geetestSeccode = parameters.get("geetestSeccode");
                JSONObject resResult =validateGeet(geetestChallenge,geetestValidate,geetestSeccode,"1");
                if (resResult==null||!resResult.getString("result").equalsIgnoreCase("success")){
                    throw new  Exception("验证失败");
                JSONObject resResult = validateGeet(geetestChallenge, geetestValidate, geetestSeccode, "1");
                if (resResult == null || !resResult.getString("result").equalsIgnoreCase("success")) {
                    throw new Exception("验证失败");
                }
            }
        }
@ -2672,8 +2694,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        //图形验证码验证
        String key = parameters.get("key");
        String text = parameters.get("text");
        if(org.apache.commons.lang3.StringUtils.isNotBlank(key)&& org.apache.commons.lang3.StringUtils.isNotBlank(text)){
            if(!verifyCaptcha(key,text)){
        if (org.apache.commons.lang3.StringUtils.isNotBlank(key) && org.apache.commons.lang3.StringUtils.isNotBlank(text)) {
            if (!verifyCaptcha(key, text)) {
                throw new ImgCaptchaException("img_captcha error");
            }
        }
@ -2692,31 +2714,31 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            if (parameters.get("password") != null) {
                KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                String password = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("password"), keyPair);
                String response = ykyyService.yktLogin(parameters.get("username"),password);
                if (!StringUtils.isEmpty(response)){
                String response = ykyyService.yktLogin(parameters.get("username"), password);
                if (!StringUtils.isEmpty(response)) {
                    JSONObject object = JSONObject.parseObject(response);
                    if (!object.getString("code").equalsIgnoreCase("200")){
                    if (!object.getString("code").equalsIgnoreCase("200")) {
                        WlyyUserSimple userSimple = new WlyyUserSimple();
                        return getFailedResponse(object.getString("msg"),-1,userSimple);
                    }else {
                        return getFailedResponse(object.getString("msg"), -1, userSimple);
                    } else {
                        JSONObject jsonObject = object.getJSONObject("data");
                        if (jsonObject!=null){
                            String userId= jsonObject.getString("ID");
                        if (jsonObject != null) {
                            String userId = jsonObject.getString("ID");
                            String tel = jsonObject.getString("LOGINID");
                            List<BasePatientDO> basePatientDOS = basePatientDao.findByMobile(tel);
                            if (basePatientDOS==null||basePatientDOS.size()==0){
                            if (basePatientDOS == null || basePatientDOS.size() == 0) {
                                BasePatientDO basePatientDO = new BasePatientDO();
                                String familyList = ykyyService.getFamilyList(null,userId);
                                String familyList = ykyyService.getFamilyList(null, userId);
                                JSONObject familyJson = JSONObject.parseObject(familyList);
                                if (familyJson.getString("code").equalsIgnoreCase("200")){
                                if (familyJson.getString("code").equalsIgnoreCase("200")) {
                                    JSONObject object1 = familyJson.getJSONObject("data");
                                    JSONArray list = object1.getJSONArray("list");
                                    List<String> iliness = new ArrayList<>();
                                    if (list!=null&&list.size()!=0){
                                        for (int i=0;i<list.size();i++){
                                    if (list != null && list.size() != 0) {
                                        for (int i = 0; i < list.size(); i++) {
                                            JSONObject family = list.getJSONObject(i);
                                            iliness.add(family.getString("ILLNESS"));
                                            if (family.getString("ILLNESS").equalsIgnoreCase("本人")&&tel.equalsIgnoreCase(family.getString("TEL"))){
                                            if (family.getString("ILLNESS").equalsIgnoreCase("本人") && tel.equalsIgnoreCase(family.getString("TEL"))) {
                                                basePatientDO.setDel("1");
                                                basePatientDO.setName(family.getString("NAME"));
                                                basePatientDO.setCreateTime(new Date());
@ -2728,19 +2750,20 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                                                String sex = IdCardUtil.getSexForIdcard_new(idcard);
                                                Integer sexx = null;
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(sex)){
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(sex)) {
                                                    sexx = Integer.parseInt(sex);
                                                }
                                                String birthDay = family.getString("BIRTHDAY");
                                                Date birthday = null;
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(birthDay)){
                                                    birthday = DateUtil.strToDate(birthDay+" 00:00:00");;
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(birthDay)) {
                                                    birthday = DateUtil.strToDate(birthDay + " 00:00:00");
                                                    ;
                                                }
                                                basePatientDO.setBirthday(birthday);
                                                basePatientDO.setSex(sexx);
                                                basePatientDO.setMobile(tel);
                                                String salt = UUID.randomUUID().toString().substring(0,5);
                                                String pw = idcard.substring(idcard.length()-6,idcard.length());
                                                String salt = UUID.randomUUID().toString().substring(0, 5);
                                                String pw = idcard.substring(idcard.length() - 6, idcard.length());
                                                basePatientDO.setIdcard(idcard);
                                                basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                                basePatientDO.setSalt(salt);
@ -2749,13 +2772,13 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                                basePatientDO.setVerifyCode(jsonObject.getString("TOKEN"));
                                                basePatientDO.setPatientStatus("1");
                                                basePatientDao.save(basePatientDO);
                                            }else {
                                            } else {
                                                List<BasePatientDO> basePatientDOList = basePatientDao.findByMobile(tel);
                                                if(basePatientDOList==null||basePatientDOList.size()==0){
                                                if (basePatientDOList == null || basePatientDOList.size() == 0) {
                                                    basePatientDO.setDel("1");
                                                    if (jsonObject.getString("USERNAME").length()>=2){
                                                    if (jsonObject.getString("USERNAME").length() >= 2) {
                                                        basePatientDO.setName(jsonObject.getString("USERNAME"));
                                                    }else {
                                                    } else {
                                                        basePatientDO.setName(tel);
                                                    }
                                                    basePatientDO.setCreateTime(new Date());
@ -2763,8 +2786,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                                    basePatientDO.setYktId(jsonObject.getString("ID"));
                                                    basePatientDO.setUserId(userId);
                                                    basePatientDO.setMobile(tel);
                                                    String salt = UUID.randomUUID().toString().substring(0,5);
                                                    String pw = tel.substring(tel.length()-6,tel.length());
                                                    String salt = UUID.randomUUID().toString().substring(0, 5);
                                                    String pw = tel.substring(tel.length() - 6, tel.length());
                                                    basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                                    basePatientDO.setSalt(salt);
                                                    basePatientDO.setLocked(0);
@ -2774,11 +2797,11 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                                }
                                            }
                                        }
                                    }else {
                                    } else {
                                        if (jsonObject.getString("USERNAME").length()>=2){
                                        if (jsonObject.getString("USERNAME").length() >= 2) {
                                            basePatientDO.setName(jsonObject.getString("USERNAME"));
                                        }else {
                                        } else {
                                            basePatientDO.setName(tel);
                                        }
                                        basePatientDO.setDel("1");
@ -2786,8 +2809,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                        basePatientDO.setUpdateTime(new Date());
                                        basePatientDO.setUserId(userId);
                                        basePatientDO.setMobile(tel);
                                        String salt = UUID.randomUUID().toString().substring(0,5);
                                        String pw = tel.substring(tel.length()-6,tel.length());
                                        String salt = UUID.randomUUID().toString().substring(0, 5);
                                        String pw = tel.substring(tel.length() - 6, tel.length());
                                        basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                        basePatientDO.setSalt(salt);
                                        basePatientDO.setLocked(0);
@ -2806,14 +2829,14 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                        ykyyService.addFamily(basePatientDO.getUserId(),basePatientDO.getIdcard(),basePatientDO.getName(),sex+"",birdth,age+"",basePatientDO.getMobile());
                                    }*/
                                }
                            }else {
                                logger.info("======"+jsonObject.getString("USERNAME")+"======");
                                logger.info("tel"+jsonObject.getString("USERNAME"));
                            } else {
                                logger.info("======" + jsonObject.getString("USERNAME") + "======");
                                logger.info("tel" + jsonObject.getString("USERNAME"));
                                BasePatientDO basePatientDO1 = basePatientDOS.get(0);
                                if (basePatientDO1.getName()==null||basePatientDO1.getName()==""){
                                    if (jsonObject.getString("USERNAME").length()>=2){
                                if (basePatientDO1.getName() == null || basePatientDO1.getName() == "") {
                                    if (jsonObject.getString("USERNAME").length() >= 2) {
                                        basePatientDO1.setName(jsonObject.getString("USERNAME"));
                                    }else {
                                    } else {
                                        basePatientDO1.setName(tel);
                                    }
                                }
@ -2853,123 +2876,124 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                    }
                }
                parameters.remove("password");
            }else if (parameters.get("mobile") != null) {
            } else if (parameters.get("mobile") != null) {
                KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                String mobile = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("mobile"), keyPair);
                logger.info("mobile:"+mobile);
                logger.info("mobile:" + mobile);
                String password = null;
                String res = ykyyService.getPatientPhone(mobile);
                if (res!=null&&res!=""){
                if (res != null && res != "") {
                    JSONObject object = JSONObject.parseObject(res);
                    if (object.getString("code").equalsIgnoreCase("200")){
                    if (object.getString("code").equalsIgnoreCase("200")) {
                        password = object.getString("data");
                    }else {
                    } else {
                        WlyyUserSimple userSimple = new WlyyUserSimple();
                        return getFailedResponse(object.getString("msg"),-1,userSimple);
                        return getFailedResponse(object.getString("msg"), -1, userSimple);
                    }
                }
                    String response = ykyyService.yktLogin(parameters.get("username"),password);
                    if (!StringUtils.isEmpty(response)){
                        JSONObject object = JSONObject.parseObject(response);
                        if (!object.getString("code").equalsIgnoreCase("200")){
                            throw new Exception(object.getString("msg"));
                        }else {
                            JSONObject jsonObject = object.getJSONObject("data");
                            if (jsonObject!=null){
                                String userId= jsonObject.getString("ID");
                                String tel = jsonObject.getString("LOGINID");
                                List<BasePatientDO> basePatientDOS = basePatientDao.findByMobile(tel);
                                if (basePatientDOS==null||basePatientDOS.size()==0){
                                    BasePatientDO basePatientDO = new BasePatientDO();
                                    String familyList = ykyyService.getFamilyList(null,userId);
                                    JSONObject familyJson = JSONObject.parseObject(familyList);
                                    if (familyJson.getString("code").equalsIgnoreCase("200")){
                                        JSONObject object1 = familyJson.getJSONObject("data");
                                        JSONArray list = object1.getJSONArray("list");
                                        List<String> iliness = new ArrayList<>();
                                        if (list!=null&&list.size()!=0){
                                            for (int i=0;i<list.size();i++){
                                                JSONObject family = list.getJSONObject(i);
                                                iliness.add(family.getString("ILLNESS"));
                                                if (family.getString("ILLNESS").equalsIgnoreCase("本人")&&tel.equalsIgnoreCase(family.getString("TEL"))){
                String response = ykyyService.yktLogin(parameters.get("username"), password);
                if (!StringUtils.isEmpty(response)) {
                    JSONObject object = JSONObject.parseObject(response);
                    if (!object.getString("code").equalsIgnoreCase("200")) {
                        throw new Exception(object.getString("msg"));
                    } else {
                        JSONObject jsonObject = object.getJSONObject("data");
                        if (jsonObject != null) {
                            String userId = jsonObject.getString("ID");
                            String tel = jsonObject.getString("LOGINID");
                            List<BasePatientDO> basePatientDOS = basePatientDao.findByMobile(tel);
                            if (basePatientDOS == null || basePatientDOS.size() == 0) {
                                BasePatientDO basePatientDO = new BasePatientDO();
                                String familyList = ykyyService.getFamilyList(null, userId);
                                JSONObject familyJson = JSONObject.parseObject(familyList);
                                if (familyJson.getString("code").equalsIgnoreCase("200")) {
                                    JSONObject object1 = familyJson.getJSONObject("data");
                                    JSONArray list = object1.getJSONArray("list");
                                    List<String> iliness = new ArrayList<>();
                                    if (list != null && list.size() != 0) {
                                        for (int i = 0; i < list.size(); i++) {
                                            JSONObject family = list.getJSONObject(i);
                                            iliness.add(family.getString("ILLNESS"));
                                            if (family.getString("ILLNESS").equalsIgnoreCase("本人") && tel.equalsIgnoreCase(family.getString("TEL"))) {
                                                basePatientDO.setDel("1");
                                                basePatientDO.setName(family.getString("NAME"));
                                                basePatientDO.setCreateTime(new Date());
                                                basePatientDO.setUpdateTime(new Date());
                                                basePatientDO.setYktId(family.getString("ID"));
                                                basePatientDO.setUserId(userId);
                                                basePatientDO.setIdcard(family.getString("IDCARD"));
                                                String idcard = family.getString("IDCARD");
                                                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                                                String sex = IdCardUtil.getSexForIdcard_new(idcard);
                                                Integer sexx = null;
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(sex)) {
                                                    sexx = Integer.parseInt(sex);
                                                }
                                                String birthDay = family.getString("BIRTHDAY");
                                                Date birthday = null;
                                                if (org.apache.commons.lang3.StringUtils.isNoneBlank(birthDay)) {
                                                    birthday = DateUtil.strToDate(birthDay + " 00:00:00");
                                                    ;
                                                }
                                                basePatientDO.setBirthday(birthday);
                                                basePatientDO.setSex(sexx);
                                                basePatientDO.setMobile(tel);
                                                String salt = UUID.randomUUID().toString().substring(0, 5);
                                                String pw = idcard.substring(idcard.length() - 6, idcard.length());
                                                basePatientDO.setIdcard(idcard);
                                                basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                                basePatientDO.setSalt(salt);
                                                basePatientDO.setLocked(0);
                                                basePatientDO.setEnabled(1);
                                                basePatientDO.setVerifyCode(jsonObject.getString("TOKEN"));
                                                basePatientDO.setPatientStatus("1");
                                                basePatientDao.save(basePatientDO);
                                            } else {
                                                List<BasePatientDO> basePatientDOList = basePatientDao.findByMobile(tel);
                                                if (basePatientDOList == null || basePatientDOList.size() == 0) {
                                                    basePatientDO.setDel("1");
                                                    basePatientDO.setName(family.getString("NAME"));
                                                    if (jsonObject.getString("USERNAME").length() >= 2) {
                                                        basePatientDO.setName(jsonObject.getString("USERNAME"));
                                                    } else {
                                                        basePatientDO.setName(tel);
                                                    }
                                                    basePatientDO.setCreateTime(new Date());
                                                    basePatientDO.setUpdateTime(new Date());
                                                    basePatientDO.setYktId(family.getString("ID"));
                                                    basePatientDO.setYktId(jsonObject.getString("ID"));
                                                    basePatientDO.setUserId(userId);
                                                    basePatientDO.setIdcard(family.getString("IDCARD"));
                                                    String idcard = family.getString("IDCARD");
                                                    Integer age = IdCardUtil.getAgeForIdcard(idcard);
                                                    String sex = IdCardUtil.getSexForIdcard_new(idcard);
                                                    Integer sexx = null;
                                                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(sex)){
                                                        sexx = Integer.parseInt(sex);
                                                    }
                                                    String birthDay = family.getString("BIRTHDAY");
                                                    Date birthday = null;
                                                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(birthDay)){
                                                        birthday = DateUtil.strToDate(birthDay+" 00:00:00");;
                                                    }
                                                    basePatientDO.setBirthday(birthday);
                                                    basePatientDO.setSex(sexx);
                                                    basePatientDO.setMobile(tel);
                                                    String salt = UUID.randomUUID().toString().substring(0,5);
                                                    String pw = idcard.substring(idcard.length()-6,idcard.length());
                                                    basePatientDO.setIdcard(idcard);
                                                    String salt = UUID.randomUUID().toString().substring(0, 5);
                                                    String pw = tel.substring(tel.length() - 6, tel.length());
                                                    basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                                    basePatientDO.setSalt(salt);
                                                    basePatientDO.setLocked(0);
                                                    basePatientDO.setEnabled(1);
                                                    basePatientDO.setVerifyCode(jsonObject.getString("TOKEN"));
                                                    basePatientDO.setPatientStatus("1");
                                                    basePatientDao.save(basePatientDO);
                                                }else {
                                                    List<BasePatientDO> basePatientDOList = basePatientDao.findByMobile(tel);
                                                    if(basePatientDOList==null||basePatientDOList.size()==0){
                                                        basePatientDO.setDel("1");
                                                        if (jsonObject.getString("USERNAME").length()>=2){
                                                            basePatientDO.setName(jsonObject.getString("USERNAME"));
                                                        }else {
                                                            basePatientDO.setName(tel);
                                                        }
                                                        basePatientDO.setCreateTime(new Date());
                                                        basePatientDO.setUpdateTime(new Date());
                                                        basePatientDO.setYktId(jsonObject.getString("ID"));
                                                        basePatientDO.setUserId(userId);
                                                        basePatientDO.setMobile(tel);
                                                        String salt = UUID.randomUUID().toString().substring(0,5);
                                                        String pw = tel.substring(tel.length()-6,tel.length());
                                                        basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                                        basePatientDO.setSalt(salt);
                                                        basePatientDO.setLocked(0);
                                                        basePatientDO.setEnabled(1);
                                                        basePatientDO.setPatientStatus("1");
                                                        basePatientDao.save(basePatientDO);
                                                    }
                                                }
                                            }
                                        }else {
                                        }
                                    } else {
                                            if (jsonObject.getString("USERNAME").length()>=2){
                                                basePatientDO.setName(jsonObject.getString("USERNAME"));
                                            }else {
                                                basePatientDO.setName(tel);
                                            }
                                            basePatientDO.setDel("1");
                                            basePatientDO.setCreateTime(new Date());
                                            basePatientDO.setUpdateTime(new Date());
                                            basePatientDO.setUserId(userId);
                                            basePatientDO.setMobile(tel);
                                            String salt = UUID.randomUUID().toString().substring(0,5);
                                            String pw = tel.substring(tel.length()-6,tel.length());
                                            basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                            basePatientDO.setSalt(salt);
                                            basePatientDO.setLocked(0);
                                            basePatientDO.setEnabled(1);
                                            basePatientDO.setPatientStatus("1");
                                            basePatientDao.save(basePatientDO);
                                        if (jsonObject.getString("USERNAME").length() >= 2) {
                                            basePatientDO.setName(jsonObject.getString("USERNAME"));
                                        } else {
                                            basePatientDO.setName(tel);
                                        }
                                        basePatientDO.setDel("1");
                                        basePatientDO.setCreateTime(new Date());
                                        basePatientDO.setUpdateTime(new Date());
                                        basePatientDO.setUserId(userId);
                                        basePatientDO.setMobile(tel);
                                        String salt = UUID.randomUUID().toString().substring(0, 5);
                                        String pw = tel.substring(tel.length() - 6, tel.length());
                                        basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                        basePatientDO.setSalt(salt);
                                        basePatientDO.setLocked(0);
                                        basePatientDO.setEnabled(1);
                                        basePatientDO.setPatientStatus("1");
                                        basePatientDao.save(basePatientDO);
                                    }
                                    /*String birdth = com.yihu.jw.util.idcard.IdCardUtil.getBirthdayForIdcardStr(basePatientDO.getIdcard());
                                    Integer age = com.yihu.jw.util.idcard.IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
                                    Integer sex = basePatientDO.getSex()!=null?basePatientDO.getSex():0;
@ -2980,21 +3004,21 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                    }else {
                                        ykyyService.addFamily(basePatientDO.getUserId(),basePatientDO.getIdcard(),basePatientDO.getName(),sex+"",birdth,age+"",basePatientDO.getMobile());
                                    }*/
                                }
                            } else {
                                logger.info("======" + jsonObject.getString("USERNAME") + "======");
                                logger.info("tel" + jsonObject.getString("USERNAME"));
                                BasePatientDO basePatientDO1 = basePatientDOS.get(0);
                                if (basePatientDO1.getName() == null || basePatientDO1.getName() == "") {
                                    if (jsonObject.getString("USERNAME").length() >= 2) {
                                        basePatientDO1.setName(jsonObject.getString("USERNAME"));
                                    } else {
                                        basePatientDO1.setName(tel);
                                    }
                                }else {
                                    logger.info("======"+jsonObject.getString("USERNAME")+"======");
                                    logger.info("tel"+jsonObject.getString("USERNAME"));
                                    BasePatientDO basePatientDO1 = basePatientDOS.get(0);
                                    if (basePatientDO1.getName()==null||basePatientDO1.getName()==""){
                                        if (jsonObject.getString("USERNAME").length()>=2){
                                            basePatientDO1.setName(jsonObject.getString("USERNAME"));
                                        }else {
                                            basePatientDO1.setName(tel);
                                        }
                                    }
                                    basePatientDO1.setVerifyCode(jsonObject.getString("TOKEN"));
                                    basePatientDO1.setUserId(userId);
                                    basePatientDao.save(basePatientDO1);
                                }
                                basePatientDO1.setVerifyCode(jsonObject.getString("TOKEN"));
                                basePatientDO1.setUserId(userId);
                                basePatientDao.save(basePatientDO1);
                                /*String familyList = ykyyService.getFamilyList(null,userId);
                                JSONObject familyJson = JSONObject.parseObject(familyList);
                                if (familyJson.getString("code").equalsIgnoreCase("200")){
@ -3023,12 +3047,12 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                                    }
                                }*/
                                }
                            }
                        }
                    }
                    parameters.remove("password");
                } else if (!StringUtils.isEmpty(loginType)&&"3".equalsIgnoreCase(loginType)){
                }
                parameters.remove("password");
            } else if (!StringUtils.isEmpty(loginType) && "3".equalsIgnoreCase(loginType)) {
                if (wlyyRedisVerifyCodeService.verification(client_id, username, captcha)) {
                    //验证码正确
                }
@ -3057,7 +3081,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        在网关处通过HTTP状态码告知前端是过期(402)还是账号在别处登陆(403),
        实现同一账号只能在一处登陆*/
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile")||request.getHeader("login-device").equalsIgnoreCase("pc"))) {
        if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile") || request.getHeader("login-device").equalsIgnoreCase("pc"))) {
            tokenStore.removeAccessToken(token.getValue());
            tokenStore.removeRefreshToken(token.getRefreshToken().getValue());
            token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
@ -3081,8 +3105,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && "3".equals(loginType)) {
            baseLoginLogDO.setOpenid(openid);
            /*userDetailsService.updateOpenId(openid, wlyyUserSimple.getId());*/
            if (!StringUtils.isEmpty(wechatId)&& !"undefined".equalsIgnoreCase(wechatId)){
                userDetailsService.updateOpenIdAndWechatId(openid,wlyyUserSimple.getId(),wechatId);
            if (!StringUtils.isEmpty(wechatId) && !"undefined".equalsIgnoreCase(wechatId)) {
                userDetailsService.updateOpenIdAndWechatId(openid, wlyyUserSimple.getId(), wechatId);
            }
        }
        if (parameters.get("password") != null) {
@ -3092,9 +3116,9 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        WxWechatDO wxWechatDO = wechatDao.findByIdAndStatus(wechatId);
        String appletOpenid = null;
        if (!StringUtils.isEmpty(appletCode)){
            Map<String,Object> objectMap = checkApplets(appletCode,wxWechatDO.getApplets(),wxWechatDO.getAppletsSecret());
            if (objectMap!=null){
        if (!StringUtils.isEmpty(appletCode)) {
            Map<String, Object> objectMap = checkApplets(appletCode, wxWechatDO.getApplets(), wxWechatDO.getAppletsSecret());
            if (objectMap != null) {
                appletOpenid = objectMap.get("openid").toString();
                userDetailsService.updateOpenId(appletOpenid, wlyyUserSimple.getId());
            }
@ -3112,7 +3136,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }
    public Map<String, Object> checkApplets(String code,String appid,String appSecret) throws Exception {
    public Map<String, Object> checkApplets(String code, String appid, String appSecret) throws Exception {
        HttpUtils httpUtils = new HttpUtils();
        Map<String, Object> param = new HashedMap();
        param.put("appid", appid);
@ -3123,8 +3147,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        HttpResponse response = httpUtils.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        JSONObject rs = JSONObject.parseObject(response.getContent());
        Map<String, Object> res = new HashedMap();
        logger.info("checkApplets:"+response.getContent());
        if (rs.containsKey("openid")){
        logger.info("checkApplets:" + response.getContent());
        if (rs.containsKey("openid")) {
            res.put("openid", rs.getString("openid"));
            res.put("sessionKey", rs.getString("session_key"));
        }
@ -3133,37 +3157,38 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    @RequestMapping(value = "/oauth/findYktPatientPw", method = RequestMethod.POST)
    public Envelop findYktPatientPw(String mobile,String client_id,String login_type,String captcha,String pw)throws Exception {
    public Envelop findYktPatientPw(String mobile, String client_id, String login_type, String captcha, String pw) throws Exception {
        if (wlyyRedisVerifyCodeService.verification(client_id, mobile, captcha)) {
            //验证码正确
        } else {
            return ObjEnvelop.getError("验证码错误!");
        }
        String response = ykyyService.forgetPassword(mobile,pw,captcha);
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(response)){
        String response = ykyyService.forgetPassword(mobile, pw, captcha);
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(response)) {
            JSONObject object = JSONObject.parseObject(response);
            if (object.getString("code").equalsIgnoreCase("10000")){
            if (object.getString("code").equalsIgnoreCase("10000")) {
                return ObjEnvelop.getSuccess("修改成功!");
            }else {
            } else {
                return ObjEnvelop.getSuccess("修改失败!");
            }
        }
        String rs = registerService.updatePatientPw(pw,mobile);
        if("ok".equals(rs)){
        String rs = registerService.updatePatientPw(pw, mobile);
        if ("ok".equals(rs)) {
            return ObjEnvelop.getSuccess("修改成功!");
        }
        return ObjEnvelop.getError("手机号未注册!");
    }
    /*
     *眼科通修改密码发送的验证码
     */
    @RequestMapping(value = "/oauth/yktGetResetCode", method = RequestMethod.POST)
    public ObjEnvelop yktGetResetCode(@ApiParam(name = "loginid", value = "注册的电话号码", required = true)
                                      @RequestParam(value = "loginid",required = true)String loginid,
                                      @RequestParam(value = "loginid", required = true) String loginid,
                                      @ApiParam(name = "type", value = "验证码类型 1、患者注册 2、患者找回密码 3、医生注册 4、医生找回密码", required = true)
                                      @RequestParam(value = "type",required = false)String type){
                                      @RequestParam(value = "type", required = false) String type) {
        try {
            return ObjEnvelop.getSuccess("ok",ykyyService.getResetCode(type,loginid));
            return ObjEnvelop.getSuccess("ok", ykyyService.getResetCode(type, loginid));
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
@ -3191,34 +3216,34 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        /*//图形验证码验证
        String key = parameters.get("key");
        String text = parameters.get("text");*/
        String isNeedGeet= "0";//1需要 0不需要
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO1= wlyyhospitalSysdictDao.findDictById("isNeedGeet");
        if (wlyyHospitalSysDictDO1!=null){
            isNeedGeet=wlyyHospitalSysDictDO1.getDictValue();
        String isNeedGeet = "0";//1需要 0不需要
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO1 = wlyyhospitalSysdictDao.findDictById("isNeedGeet");
        if (wlyyHospitalSysDictDO1 != null) {
            isNeedGeet = wlyyHospitalSysDictDO1.getDictValue();
        }
        if (parameters.get("mobile")==null){
            if("1".equalsIgnoreCase(isNeedGeet)){
        if (parameters.get("mobile") == null) {
            if ("1".equalsIgnoreCase(isNeedGeet)) {
                String geetestChallenge = parameters.get("geetestChallenge");
                String geetestValidate = parameters.get("geetestValidate");
                String geetestSeccode = parameters.get("geetestSeccode");
                JSONObject resResult =validateGeet(geetestChallenge,geetestValidate,geetestSeccode,"2");
                if (resResult==null||!resResult.getString("result").equalsIgnoreCase("success")){
                    throw new  Exception("验证失败");
                JSONObject resResult = validateGeet(geetestChallenge, geetestValidate, geetestSeccode, "2");
                if (resResult == null || !resResult.getString("result").equalsIgnoreCase("success")) {
                    throw new Exception("验证失败");
                }
            }
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyhospitalSysdictDao.findDictById("isNeedPictureCode");
        String isNeedPictureCode = "1";
        if (wlyyHospitalSysDictDO!=null){
        if (wlyyHospitalSysDictDO != null) {
            isNeedPictureCode = wlyyHospitalSysDictDO.getDictValue();
        }
        logger.info("isNeedPictureCode:"+isNeedPictureCode);
        if ("1".equalsIgnoreCase(isNeedPictureCode)){
        logger.info("isNeedPictureCode:" + isNeedPictureCode);
        if ("1".equalsIgnoreCase(isNeedPictureCode)) {
            //图形验证码验证
            String key = parameters.get("key");
            String text = parameters.get("text");
            if(org.apache.commons.lang3.StringUtils.isNotBlank(key)&& org.apache.commons.lang3.StringUtils.isNotBlank(text)){
                if(!verifyCaptcha(key,text)){
            if (org.apache.commons.lang3.StringUtils.isNotBlank(key) && org.apache.commons.lang3.StringUtils.isNotBlank(text)) {
                if (!verifyCaptcha(key, text)) {
                    throw new ImgCaptchaException("img_captcha error");
                }
            }
@ -3239,34 +3264,34 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            if (parameters.get("password") != null) {
                KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                String password = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("password"), keyPair);
                logger.info("password:"+password);
                String response = ykyyService.DoctorLogin(parameters.get("username"),password);
                if (!StringUtils.isEmpty(response)){
                logger.info("password:" + password);
                String response = ykyyService.DoctorLogin(parameters.get("username"), password);
                if (!StringUtils.isEmpty(response)) {
                    JSONObject object = JSONObject.parseObject(response);
                    logger.info("眼科通登陆返回参数:"+object);
                    if (!object.getString("code").equalsIgnoreCase("10000")){
                    logger.info("眼科通登陆返回参数:" + object);
                    if (!object.getString("code").equalsIgnoreCase("10000")) {
                        WlyyUserSimple userSimple = new WlyyUserSimple();
                        return getFailedResponse(object.getString("msg"),-1,userSimple);
                    }else {
                        return getFailedResponse(object.getString("msg"), -1, userSimple);
                    } else {
                        JSONObject jsonObject = object.getJSONObject("value");
                        if (jsonObject!=null) {
                        if (jsonObject != null) {
                            String idCard = jsonObject.getString("idCard");
                            String verifyCode = jsonObject.getString("verifyCode");
                            String yktDoctorId= jsonObject.getString("id");
                            String yktDoctorId = jsonObject.getString("id");
                            BaseDoctorDO doctorDOs = doctorDao.findByIdcard(idCard);
                            if (doctorDOs!=null){
                            if (doctorDOs != null) {
                                doctorDOs.setVerifyCode(verifyCode);
                                doctorDOs.setYktDoctorId(yktDoctorId);
                                /*doctorDOs.setYktCode();*/
                                doctorDao.save(doctorDOs);
                            }else {
                            } else {
                                WlyyUserSimple userSimple = new WlyyUserSimple();
                                return getFailedResponse("您的账号未认证,请联系互联网医院工作人员,联系电话0592-2108763。",-1,userSimple);
                                return getFailedResponse("您的账号未认证,请联系互联网医院工作人员,联系电话0592-2108763。", -1, userSimple);
                            }
                            if (idCard==null||idCard==""){
                            if (idCard == null || idCard == "") {
                                logger.info("身份证为空");
                            }else {
                                ykyyService.updateYkyyDoctor(idCard,verifyCode,yktDoctorId);
                            } else {
                                ykyyService.updateYkyyDoctor(idCard, verifyCode, yktDoctorId);
                            }
                        }
                    }
@ -3275,51 +3300,51 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            } else if (parameters.get("mobile") != null) {
                KeyPair keyPair = (KeyPair) httpSession.getAttribute("privateKey");
                String mobile = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("mobile"), keyPair);
                logger.info("mobile:"+mobile);
                logger.info("mobile:" + mobile);
                String password = null;
                String res = ykyyService.getDoctorPhone(mobile);
                if (res!=null&&res!=""){
                if (res != null && res != "") {
                    JSONObject object = JSONObject.parseObject(res);
                    if (object.getString("code").equalsIgnoreCase("200")){
                    if (object.getString("code").equalsIgnoreCase("200")) {
                        password = object.getString("data");
                    }else {
                    } else {
                        WlyyUserSimple userSimple = new WlyyUserSimple();
                        return getFailedResponse(object.getString("msg"),-1,userSimple);
                        return getFailedResponse(object.getString("msg"), -1, userSimple);
                    }
                }
                String response = ykyyService.DoctorLogin(parameters.get("username"),password);
                if (!StringUtils.isEmpty(response)){
                String response = ykyyService.DoctorLogin(parameters.get("username"), password);
                if (!StringUtils.isEmpty(response)) {
                    JSONObject object = JSONObject.parseObject(response);
                    logger.info("眼科通登陆返回参数:"+object);
                    if (!object.getString("code").equalsIgnoreCase("10000")){
                    logger.info("眼科通登陆返回参数:" + object);
                    if (!object.getString("code").equalsIgnoreCase("10000")) {
                        WlyyUserSimple userSimple = new WlyyUserSimple();
                        return getFailedResponse(object.getString("message"),-1,userSimple);
                    }else {
                        return getFailedResponse(object.getString("message"), -1, userSimple);
                    } else {
                        JSONObject jsonObject = object.getJSONObject("value");
                        if (jsonObject!=null) {
                        if (jsonObject != null) {
                            String idCard = jsonObject.getString("idCard");
                            String verifyCode = jsonObject.getString("verifyCode");
                            String yktDoctorId= jsonObject.getString("id");
                            String yktDoctorId = jsonObject.getString("id");
                            BaseDoctorDO doctorDOs = doctorDao.findByIdcard(idCard);
                            if (doctorDOs!=null){
                            if (doctorDOs != null) {
                                doctorDOs.setVerifyCode(verifyCode);
                                doctorDOs.setYktDoctorId(yktDoctorId);
                                /*doctorDOs.setYktCode();*/
                                doctorDao.save(doctorDOs);
                            }else {
                            } else {
                                WlyyUserSimple userSimple = new WlyyUserSimple();
                                return getFailedResponse("您的账号未认证,请联系互联网医院工作人员,联系电话0592-2108763。",-1,userSimple);
                                return getFailedResponse("您的账号未认证,请联系互联网医院工作人员,联系电话0592-2108763。", -1, userSimple);
                            }
                            if (idCard==null||idCard==""){
                            if (idCard == null || idCard == "") {
                                logger.info("身份证为空");
                            }else {
                                ykyyService.updateYkyyDoctor(idCard,verifyCode,yktDoctorId);
                            } else {
                                ykyyService.updateYkyyDoctor(idCard, verifyCode, yktDoctorId);
                            }
                        }
                    }
                }
                parameters.remove("password");
            }else {
            } else {
                //第三方同步账号模式登录
                parameters.put("grant_type", "ihealthDcotor");
            }
@ -3332,7 +3357,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        if (null == authenticatedClient) {
            throw new InvalidRequestException("client_id");
        }
        logger.info("login:登录进入4"+authenticatedClient.getClientId());
        logger.info("login:登录进入4" + authenticatedClient.getClientId());
        TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
@ -3344,7 +3369,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        在网关处通过HTTP状态码告知前端是过期(402)还是账号在别处登陆(403),
        实现同一账号只能在一处登陆*/
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile")||request.getHeader("login-device").equalsIgnoreCase("pc"))) {
        if (request.getHeader("login-device") != null && (request.getHeader("login-device").equalsIgnoreCase("mobile") || request.getHeader("login-device").equalsIgnoreCase("pc"))) {
            tokenStore.removeAccessToken(token.getValue());
            tokenStore.removeRefreshToken(token.getRefreshToken().getValue());
            token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
@ -3366,13 +3391,13 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        //更新患者openId
        BaseLoginLogDO baseLoginLogDO = new BaseLoginLogDO();
        logger.info("gengxin开始");
        if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("3".equals(loginType)||"4".equalsIgnoreCase(loginType))) {
        if (!StringUtils.isEmpty(openid) && !"undefined".equalsIgnoreCase(openid) && ("3".equals(loginType) || "4".equalsIgnoreCase(loginType))) {
            baseLoginLogDO.setOpenid(openid);
            logger.info("gengxin进入"+openid);
            logger.info("gengxin进入" + openid);
            userDetailsService.updateOpenId(openid, wlyyUserSimple.getId());
            if (!StringUtils.isEmpty(wechatId)&& !"undefined".equalsIgnoreCase(wechatId)){
                logger.info("gengxin进入"+wechatId);
                userDetailsService.updateOpenIdAndWechatId(openid,wlyyUserSimple.getId(),wechatId);
            if (!StringUtils.isEmpty(wechatId) && !"undefined".equalsIgnoreCase(wechatId)) {
                logger.info("gengxin进入" + wechatId);
                userDetailsService.updateOpenIdAndWechatId(openid, wlyyUserSimple.getId(), wechatId);
            }
        }
        if (parameters.get("password") != null) {

+ 3 - 3
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/service/IotDeviceService.java

@ -66,7 +66,7 @@ public class IotDeviceService {
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceInfo","设备状态信息上传",params,header,true,true);
        return response;
    }
@ -77,7 +77,7 @@ public class IotDeviceService {
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceData","设备业务数据信息上传",params,header,true,true);
        return response;
    }
@ -88,7 +88,7 @@ public class IotDeviceService {
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/deviceRegistration","设备相关基础信息注册",params,header,true,true);
        return response;
    }

+ 0 - 1
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/SDKRunnerService.java

@ -71,7 +71,6 @@ public class SDKRunnerService {
//                    new RequestValue("msgBody", "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT></ROOT>", true, openCrypto)
                // new RequestValue("idCard", "123", true, openCrypto)
                //实体参数请求示例
//                    new RequestValue("{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}")
                for(String key :params.keySet())
                {
                    RequestValue obj = new RequestValue(key,params.get(key),urlEncode,openCrypto);

+ 1 - 1
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -659,7 +659,7 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
		if ("xm_zsyy_wx".equalsIgnoreCase(wxId)){
		//结束时医生未开处方则发送模板消息结算
		ConsultDo cons = consultDao.findById(consult).orElse(null);
		if (org.apache.commons.lang3.StringUtils.isNoneBlank(cons.getRelationCode())){
		if (org.apache.commons.lang3.StringUtils.isNoneBlank(cons.getRelationCode())&&cons.getType()!=28){
			WlyyOutpatientDO outpatientDO = outpatientDao.findById(cons.getRelationCode()).orElse(null);
			List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutpatientId(outpatientDO.getId());
			if (wlyyPrescriptionDOS==null||wlyyPrescriptionDOS.size()==0){

+ 2 - 1
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java

@ -29,7 +29,8 @@ import java.util.Map;
 * Created by wangzhinan on 2019/12/3.
 */
@RestController
@RequestMapping(value = BaseHospitalRequestMapping.Statistics.PREFIX)
//@RequestMapping(value = BaseHospitalRequestMapping.Statistics.PREFIX)
@RequestMapping("/open/statistics")
@Api(value = "统计分析", description = "统计分析", tags = {"统计分析"})
public class EsStatisticsEndpoint extends EnvelopRestEndpoint {

+ 18 - 50
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java

@ -12,6 +12,7 @@ import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.im.util.ImageCompress;
import com.yihu.jw.message.service.MessageService;
@ -58,7 +59,8 @@ public class ConsultController extends EnvelopRestEndpoint {
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private ImService imService;
    @Autowired
    private BaseDoctorInfoService doctorService;
@ -96,39 +98,6 @@ public class ConsultController extends EnvelopRestEndpoint {
    @Value("${im.data_base_name}")
    private String im;
//    //    @Value("${doctorAssistant.api}")
//    private String doctorAssistant;
//
//    //    @Value("${doctorAssistant.target_url}")
//    private String targetUrl;
//    @Value("${spring.profiles}")
//    private String springProfile;
//    @Autowired
//    private RedisTemplate redisTemplate;
//    @Autowired
//    private PushMsgTask pushMsgTask;
//    @Autowired
//    private PrescriptionDao prescriptionDao;
//    @Autowired
//    private DoctorCommentService doctorCommentService;
//    @Autowired
//    private DoctorStatisticsService doctorStatisticsService;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PrescriptionDiagnosisService prescriptionDiagnosisService;
//    @Autowired
//    private ExaminationDao examinationDao;
//    @Autowired
//    private WlyyDynamicMessagesDao dynamicMessagesDao;
    /**
     * 获取未完成咨询
     *
@ -153,22 +122,21 @@ public class ConsultController extends EnvelopRestEndpoint {
     * @param doctor 医生
     * @return
     */
//    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
//    @ApiOperation("查询居民与某个医生是否存在未结束的咨询")
//    public String isExistsUnfinishedConsult(@RequestParam(required = true) String doctor) {
//        try {
//            List<ConsultTeamDo> consults = consultTeamService.getUnfinishedConsult(getRepUID(), doctor);
//
//            if (consults != null && consults.size() > 0) {
//                return write(200, "查询成功", "data", consults.get(0).getConsult());
//            } else {
//                return write(200, "查询成功", "data", "");
//            }
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("查询居民与某个医生是否存在未结束的咨询")
    public String isExistsUnfinishedConsult(@RequestParam(required = true) String doctor,@RequestParam(required = true) Integer type) {
        try {
            String consults = imService.getUnfinishedConsult(getRepUID(), doctor,type);
            if (StringUtils.isNotBlank(consults)) {
                return write(200, "查询成功", "data", consults);
            } else {
                return write(200, "查询成功", "data", "");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    /**

+ 0 - 17
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java

@ -1,16 +1,12 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.device.dao.HmTokenDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
import com.yihu.jw.entity.care.device.HmToken;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceService;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
@ -27,9 +23,6 @@ public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private HmTokenDao hmTokenDao;
    @ApiOperation("获取设备分类")
    @RequestMapping(value = "DeviceCategory", method = {RequestMethod.POST, RequestMethod.GET})
@ -64,16 +57,6 @@ public class DeviceController extends BaseController {
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            if(device!=null&&"11".equals(device.getCategoryCode())){
                //华米手表返回 授权到期时间
                HmToken hmToken = hmTokenDao.selectT(getRepUID());
                String authorizationTime = null;
                if(hmToken!=null&& StringUtils.isNotBlank(hmToken.getExpiresIn())){
                    authorizationTime = DateUtil.dateAddByType(hmToken.getCreateTime(),"1",Long.parseLong(hmToken.getExpiresIn()));
                    device.setAuthorizationTime(authorizationTime);
                }
            }
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());

+ 55 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceUploadController.java

@ -0,0 +1,55 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.hospital.module.health.service.DeviceUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import javax.servlet.http.HttpServletRequest;
/**
 * Created by Bing on 2021/7/7.
 */
@RestController
@Api(description = "第三放设备数据推送接口")
@RequestMapping(value = "/deviceData")
public class DeviceUploadController {
    //设备需要注册后才能推送至注册时地址,否则统一推送至默认地址
    //注册地址(post): http://www.cityihealth.com:43210/deviceManage/register?deviceSN=设备SN码&pushAddress=设备推送地址完整地址
    //
    private static Logger logger = LoggerFactory.getLogger(DeviceUploadController.class);
    @Autowired
    private DeviceUploadService deviceUploadService;
    @ApiOperation("设备数据接收接口(标准协议)")
    @RequestMapping(value = "/open/excelControl/upload", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Result uploadDevicesData(
            @ApiParam(value="推送类型(44代表体征推送)",defaultValue = "44")
            @RequestParam(value = "typeId", required = false)  Integer typeId ,
            @ApiParam(value="体征数据",defaultValue =
                    "{\"button\":\"1\",\"data\":\"1.81\",\"deviceSn\":\"16C000337\",\"deviceType\":2,\"id\":2377," +
                            "\"manufacturerCode\":\"threeNod\",\"manufacturerName\":\"三诺\",\"sendTime\":\"2017-03-13 13:47:42\"," +
                            "\"state\":0,\"unit\":\"mmol/L\",\"uploadTime\":\"2017-03-13 13:46:59\"}")
            @RequestParam(value = "data", required = true)  String data, HttpServletRequest request)
    {
        try{
            logger.info("typeId="+typeId+";data="+data);
            return deviceUploadService.uploadDevicesData(data,request);
        }
        catch (Exception ex)
        {
            return Result.error("Device data incoming failure!"+ex.getMessage());
        }
    }
}

+ 3 - 15
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java

@ -168,11 +168,11 @@ public class PatientDeviceController extends BaseController {
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3 06
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"06B52305030267\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
@ -203,18 +203,6 @@ public class PatientDeviceController extends BaseController {
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            String flagStr ="";
            if ("1".equals(device.getCategoryCode())){
                flagStr="GLU_BIND";
            }else if ("2".equals(device.getCategoryCode())){
                flagStr="BP_BIND";
            }
            //活动的活跃度
            if (flag){
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("patientId",patient.getId());
                jsonObject.put("taskCode",flagStr);
            }
            if(!"11".equals(device.getCategoryCode())){
                try {
                    String openId = patient.getOpenid();
@ -246,7 +234,7 @@ public class PatientDeviceController extends BaseController {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
            return error(-1, "设备保存失败");
        }
    }

+ 60 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/Result.java

@ -0,0 +1,60 @@
package com.yihu.jw.hospital.module.health.controller;
import java.util.Map;
public class Result {
    protected boolean successFlg = true;
    protected String message;
    protected Map<String, Object> objectMap;
    public boolean isSuccessFlg() {
        return successFlg;
    }
    public void setSuccessFlg(boolean successFlg) {
        this.successFlg = successFlg;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Map<String, Object> getObjectMap() {
        return objectMap;
    }
    public void setObjectMap(Map<String, Object> objectMap) {
        this.objectMap = objectMap;
    }
    /**
     * 错误消息
     */
    public static Result error(String message) {
        Result re= new Result();
        re.successFlg = false;
        re.message = message;
        return re;
    }
    /**
     * 成功消息
     */
    public static Result success(String message) {
        Result re= new Result();
        re.successFlg = true;
        re.message = message;
        return re;
    }
    public static Result authError(String message) {
        Result re= new Result();
        re.successFlg = false;
        re.message = message;
        return re;
    }
}

+ 34 - 11
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java

@ -11,14 +11,20 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -42,7 +48,10 @@ public class DeviceDetailService {
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private HttpClientUtil httpClientUtil;
	@Autowired
	private WlyyHospitalSysDictDao hospitalSysDictDao;
	/**
	 * 绑定时更新设备表中的信息
@ -54,8 +63,6 @@ public class DeviceDetailService {
	@Transactional
	public void updateAfterBinding(DevicePatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
//		SignFamily signFamily = signFamilyDao.findByIdcard(patientDevice.getUserIdcard());
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
@ -66,19 +73,12 @@ public class DeviceDetailService {
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
//		if (signFamily!=null){
//			adminTeam = signFamily.getAdminTeamId();
//			hospital = signFamily.getHospital();
//			hospitalName = signFamily.getHospitalName();
//			doctorCode = signFamily.getDoctor();
//			doctorName = signFamily.getDoctorName();
//		}
		//设备表没有数据则插入一条数据
		if (deviceDetail==null){
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital,"",doctorCode,doctorName,1);
			deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		}
		int bind = deviceDetail.getIsBinding();
		isFirstBind = deviceDetail.getBindingCount();
		if (StringUtils.isNotBlank(isFirstBind)){
			JSONObject jsonObject = JSON.parseObject(isFirstBind);
@ -186,4 +186,27 @@ public class DeviceDetailService {
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
	/**
	 * 注册设备,通过iot项目进行数据推送
	 * @return
	 */
	public void registerToWlyy(DevicePatientDevice device){
		//判断设备类型
		Device deviceDO = deviceDao.findById(device.getDeviceId()).orElse(null);
		if (StringUtils.isNotBlank(deviceDO.getNeedRegister())){
			// 设备注册至iot后 通过iot将设备数据转发
//			String url = "http://www.cityihealth.com:43210/deviceManage/register";
			WlyyHospitalSysDictDO dictDO1 = hospitalSysDictDao.findOneByDictNameAndDictCode("registerToWlyy","pushAddress");
			WlyyHospitalSysDictDO dictDO2 = hospitalSysDictDao.findOneByDictNameAndDictCode("registerToWlyy","url");
			String pushAddress = dictDO1.getDictValue();
			String url = dictDO2.getDictValue();
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("deviceSN", device.getDeviceSn()));
			params.add(new BasicNameValuePair("pushAddress", pushAddress));
			String response = httpClientUtil.post(url, params,"UTF-8");
			System.out.println("注册结果:"+response);
		}
	}
}

+ 454 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceUploadService.java

@ -0,0 +1,454 @@
package com.yihu.jw.hospital.module.health.service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.DeviceInfoDao;
import com.yihu.jw.device.dao.DevicePatientHealthIndexDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DeviceInfo;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.health.controller.Result;
import com.yihu.jw.hospital.utils.CountDistance;
import com.yihu.jw.hospital.utils.DeviceDataPushLogUtil;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.GpsUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.healthIndex.HealthIndexUtil;
import com.yihu.jw.utils.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Bing on 2021/7/7.
 */
@Service
public class DeviceUploadService {
    private static Logger logger = LoggerFactory.getLogger(DeviceUploadService.class);
    @Autowired
    private DeviceInfoDao deviceInfoDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private HealthIndexUtil healthIndexUtil;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private CountDistance countDistance;
    @Autowired
    private GpsUtil gpsUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DeviceDataPushLogUtil dataPushLogUtil;
    public Result uploadDevicesData(String dataJson, HttpServletRequest request)throws Exception {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(dataJson, Map.class);
            String deviceSn = map.get("deviceSn").toString();//设备唯一码
            Integer deviceType = Integer.parseInt(map.get("deviceType").toString());//设备类型1:血压 2:血糖
            String data = map.get("data").toString();//体征值(血糖:data=血糖值   血压:data=收缩压,舒张压,脉搏)
            String uploadTime = map.get("uploadTime").toString();//体征上传时间yyyy-MM-dd HH:mm:ss
            String manufacturerCode = map.get("manufacturerCode").toString();//厂商代码
            String manufacturerName = map.get("manufacturerName").toString();//厂商名称
            String unit = map.get("unit").toString();//单位mmol/L,mmHg
            String sendTime = map.get("sendTime").toString();//发送时间yyyy-MM-dd HH:mm:ss
            String userType = map.get("button").toString();//按键号 即 userType
            String measurementType=null==map.get("measurementType")?"":map.get("measurementType").toString(); //单个设备的测量类型,deviceType=4智能手表:1心率,2血压
            String paraString = JSON.toJSONString(request.getParameterMap());
            JSONObject json = new JSONObject();
            json.put("deviceSn", deviceSn);
            json.put("deviceType", deviceType);
            json.put("data", data);
            json.put("uploadTime", uploadTime);//三诺的上传时间
            json.put("manufacturerCode", manufacturerCode);
            json.put("manufacturerName", manufacturerName);
            json.put("unit", unit);
            json.put("sendTime", sendTime);//三诺的测量时间
            json.put("userType", userType);
            json.put("measurementType", measurementType);
            String type = deviceType + "";
            if (1 == deviceType) {
                type = "2";
            } else if (2 == deviceType) {
                type = "1";
                userType = "-1";
            }
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceData(dataJson);
            deviceInfo.setDeviceType(type);
            deviceInfo.setPushDate(DateUtil.getNowTimestamp());
            deviceInfo.setStatus("1");
            deviceInfoDao.save(deviceInfo);
            DevicePatientHealthIndex result = null;
            if(type.equalsIgnoreCase("1")){
                if (Double.parseDouble(data)>=1){
                    result = savePatientDeviceData(deviceSn, type, data, uploadTime, userType, json,measurementType);
                }else {
                    logger.info("This blood device data below 1.0:====="+dataJson);
                    throw new Exception("This blood device data below 1.0 ");
                }
            }else {
                result = savePatientDeviceData(deviceSn, type, data, uploadTime, userType, json,measurementType);
            }
            if (result == null) {
                logger.info("This device is not relate patient!:====="+dataJson);
                throw new Exception("This device is not relate patient!");
            }
            dataPushLogUtil.savePushLog(deviceSn,paraString,"体征数据接收");
            dataPushLogUtil.updContactStatus(deviceSn,1,false);
            //保存消息
            BasePatientDO patientDO = patientDao.findById(result.getUser()).orElse(null);
            if (null != patientDO){
                SystemMessageDO messageDO = new SystemMessageDO();
                String typeName = null;
                switch (type){
                    case "1":
                        typeName = "您有新的血糖测量记录:血糖浓度:"+result.getValue1()+"mmol/L";
                        break;
                    case "2":
                        typeName = "您有新的血压测量记录:收缩压:"+result.getValue1()+"mmHg,舒张压:"
                                +result.getValue2()+"mmHg,脉搏:"+result.getValue3()+"次/min";
                        break;
                }
                if (StringUtils.isNotBlank(typeName)){
/*                    String adminSql = "SELECT py_code FROM wlyy_hospital_sys_dict WHERE dict_name = 'pushOnOff' AND dict_code ='"+6+"' ";
                    String onOff= jdbcTemplate.queryForObject(adminSql,String.class);
                    Boolean kg = Boolean.parseBoolean(onOff);
                    String patientOnOffSql = "select on_off from base_patient_pad_pushonoff where patient = '" + patientDO.getId() + "' and type = 3";
                    Integer integer = jdbcTemplate.queryForObject(patientOnOffSql,Integer.class);
                    if (kg&&integer==0?false:true) {
                        messageDO.setTitle(typeName);
                        messageDO.setType("42");//42体征设备测量
                        messageDO.setSender("system");
                        messageDO.setSenderName("养护助手");
                        messageDO.setRelationCode(result.getId() + "");
                        messageDO.setReceiver(patientDO.getId());
                        messageDO.setReceiverName(patientDO.getName());
//                        messageDO.setUserType(1);
                        messageDO.setOver("1");
                        messageDO.setCode(type);//与体征类型对应
                        JSONArray errorIndex = healthIndexUtil.verifyHealthIndex(Integer.parseInt(type), result.getValue1(), result.getValue2(),
                                result.getValue3(), result.getValue4(), result.getValue5(), result.getValue6(),
                                result.getValue7());
                        messageDO.setData(JSON.toJSONString(errorIndex, SerializerFeature.WriteNullStringAsEmpty));
                        messageDO.setDel("1");
                        messageDO.setCreateTime(new Date());
                        //推送socket
                        com.alibaba.fastjson.JSONObject message = new com.alibaba.fastjson.JSONObject();
                        message.put("title", typeName);
                        message.put("code", messageDO.getCode());
                        message.put("content", messageDO.getData());
                        message.put("relation_code", messageDO.getRelationCode());
                        message.put("content_type", 42);
                        message.put("content_notice", "");
//                        message.put("audioUrl", url);
                        String content_notice = "";
                        for (int i = 0; i < errorIndex.size(); i++) {
                            com.alibaba.fastjson.JSONObject tmp = errorIndex.getJSONObject(i);
                            if (0 != tmp.getInteger("error")) {
                                result.setStatus(1);
                            }
                            if (1 == tmp.getInteger("error")) {
                                content_notice += tmp.getString("indexName") + "、";
                            }
                        }
                        if (StringUtils.isNotBlank(content_notice)) {
                            content_notice = content_notice.substring(0, content_notice.length() - 1);
                            message.put("content_notice", "您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1", content_notice));
                            messageDO.setContent("您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1", content_notice));
                            dataPushLogUtil.updContactStatus(deviceSn, 1, true);
                        } else {
                            dataPushLogUtil.updContactStatus(deviceSn, 1, false);
                        }
                        patientHealthIndexDao.save(result);
                        systemMessageDao.save(messageDO);
                        imUtil.sendPatientSystemMessage(messageDO.getReceiver(), JSON.toJSONString(message, SerializerFeature.WriteMapNullValue));
                    }*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return Result.success("Device data incoming success");
    }
    /**
     * 保存设备数据
     * @param type 设备类型 4 智能手表
     * @param userType 用户身份:-1 单用户
     * @param measurementType 单设备多功能类型 type=4时,measurementType=1心率,measurementType=2血压
     */
    public DevicePatientHealthIndex savePatientDeviceData(String deviceSn, String type, String data, String uploadTime, String userType, JSONObject json, String measurementType) throws Exception {
        Date currentTime = DateUtil.getNowTimestamp();
        Date time = currentTime;
        if (!StringUtil.isEmpty(uploadTime)) {
            //设备重新开机启动会有默认时间,相隔很远.
            time = DateUtil.toTimestamp(uploadTime, DateUtil.YYYY_MM_DD_HH_MM_SS);
            Date monthTime = DateUtil.getNextMonthReturnDate( currentTime,-12);
            if (DateUtil.compareDate(time, monthTime) < 0) {
                time = currentTime;
            }
        }
        if (StringUtil.isStrEmpty(userType)) {
            userType = "-1";
        }
        DevicePatientDevice device = null;
        DeviceDetail deviceDetail = null;
        List<DeviceDetail> deviceDetails = deviceDetailDao.findByDeviceCode(deviceSn);
        if (deviceDetails != null || deviceDetails.size()!=0){
            deviceDetail = deviceDetails.get(0);
            if (deviceDetail.getGrantOrgCode() != null&& deviceDetail.getGrantOrgCode().equals("3502050300")){//
                List<DevicePatientDevice> patientDeviceList =  patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
                if (patientDeviceList != null&&patientDeviceList.size()==1) {
                    device = patientDeviceList.get(0);
                }else if(patientDeviceList != null&&patientDeviceList.size()==2){
                    for (int i=0;i<patientDeviceList.size();i++){
                        if(userType.equals(patientDeviceList.get(i).getUserType())){
                            device = patientDeviceList.get(i);
                            break;
                        }
                    }
                }
            }else {
//                device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
                List<DevicePatientDevice> devices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
                if (devices.size()>0){
                    device = devices.get(0);
                }else {
                    device=null;
                }
            }
        }
        if (device != null) {
        /*//根据设备获取患者(设备只绑定一个人的时候,不判断按键)
        if (device!=null) {*/
            /************设备数据重复推送处理 start**********************/
            String value1 = data;
            String value2="";
            String value3="";
            if("2".equals(type)){
                String[] value = data.split(",");
                if (value.length > 0) {
                    value1 = value[0];     //收缩压
                    value2 = value[1];
                    value3 = value[2];
                }
            }else if("4".equals(type)){
                if(StringUtils.isNotBlank(measurementType)&&"2".equals(measurementType)){
                    type="2";
                    String[] value = data.split(",");
                    if (value.length > 0) {
                        value1 = value[0];     //收缩压
                        value2 = value[1];
                        /* value3 = value[2];*/
                    }
                }else {
                    //心率
                    type="5";
                }
            }
            if (value1.equals(value2) && value2.equals(value3)){
                return null;
            }
//            List<PatientHealthIndex> list = patientHealthIndexDao.findByType(device.getUser(),deviceSn,value1,Integer.parseInt(type),time);
            /*long maxtime = time.getTime()+30*1000;
            long mintime = time.getTime()-30*1000;*/
            Date minDate = DateUtil.getPreDays(time,-3);
            Date maxDate = DateUtil.getPreDays(time,3);
            List<DevicePatientHealthIndex> list = ioTfindByType(device.getUser(),deviceSn,value1,value2,value3,Integer.parseInt(type),time,minDate,maxDate);
            if(list!=null&&list.size()>0){
                return null;
            }
            /************设备数据重复推送处理 end**********************/
            DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            obj.setCzrq(sdf.parse(json.getString("sendTime")));//创建时间取三诺的测量时间记录
            obj.setDeviceSn(deviceSn);
            obj.setDel("1");
            obj.setRecordDate(sdf.parse(json.getString("uploadTime")));    //记录时间取上传时间
            obj.setSortDate(time);      //排序时间
//            obj.setManageResult(0);//默认数据是医生未干预状态
            String user = device.getUser();
            obj.setUser(user);
//            obj.setButton(userType);
            obj.setIdcard(device.getUserIdcard());
            obj.setStatus(0);
            //  1血糖 2血压 3体重 4腰围,5心率
            switch (type) {
                case "1":
                    obj.setType(1);
                    obj.setValue1(data);     //血糖值
                    obj.setValue2(formatBloodSuger(user,deviceSn,DateUtil.dateToStr(time, DateUtil.YYYY_MM_DD_HH_MM_SS)));
                    break;
                case "2":
                    obj.setType(2);
                    String[] value = data.split(",");
                    if (value.length > 0) {
                        obj.setValue1(value[0]);     //收缩压
                    }
                    if (value.length > 1) {
                        obj.setValue2(value[1]);     //舒张压
                    }
                    if (value.length > 2) {
                        obj.setValue3(value[2]);     //脉搏
                    }
                    if (value.length > 3) {
                        obj.setValue4(value[3]);     //有无心率不齐
                    }
                    break;
                case "3":
                    obj.setType(3);
                    obj.setValue1(data); //体重
                    break;
                case "4":
                    obj.setType(4);
                    obj.setValue1(data);  //腰围
                    break;
                case "5":
                    obj.setType(5);
                    obj.setValue1(data);  //心率
                    break;
                default:
                    throw new Exception("Can not support the metric!");
            }
            //新增字段处理
            BasePatientDO patient = patientDao.findById(user).orElse(null);
            if(patient!=null){
                obj.setName(patient.getName());
            }
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
            obj = patientHealthIndexDao.save(obj);
//            if ("1".equals(type)||"2".equals(type)){
//                dataPushLogUtil.savePatientMonitorData(deviceSn,Integer.parseInt(type),JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue),obj.getId()+"");
//            }
            return obj;
        }
        return null;
    }
    /**
     * 查找重复数据
     * @param user
     * @param deviceSn
     * @param value1
     * @param type
     * @param time
     * @return
     */
    public List<DevicePatientHealthIndex> ioTfindByType(String user,String deviceSn,String value1,String value2,String value3,Integer type,Date time,Date timeMin,Date timeMax){
       List<DevicePatientHealthIndex> list = new ArrayList<>();
       if (type==1){
           list =  patientHealthIndexDao.findByTypeInHalfMinute(user,deviceSn,value1,type,timeMin,timeMax);
       }else if (type==2){
           list = patientHealthIndexDao.findByTypeInHalfMinuteAllValue(user,deviceSn,value1,type,timeMin,timeMax,value2,value3);
       }
       return list;
    }
    /**
     * 血糖测量时间段
     * @param user
     * @param deviceSN
     * @param dateTime
     * @return
     */
    private String formatBloodSuger(String user,String deviceSN,String dateTime) {
        String fastingStart = "00:00:00";
        String fastingEnd = "07:59:59";
        String afterBreakFastStart = "08:00:00";
        String afterBreakFastEnd = "09:59:59";
        String beforeLunchStart = "10:00:00";
        String beforeLunchEnd = "11:59:59";
        String afterLunchStart = "12:00:00";
        String afterLunchEnd = "13:59:59";
        String beforeDinnerStart = "14:00:00";
        String beforeDinnerEnd = "17:59:59";
        String afterDinnerStart = "18:00:00";
        String afterDinnerEnd = "19:59:59";
        String beforeSleepStart = "20:00:00";
        String beforeSleepEnd = "23:59:59";
        if (isInArea(dateTime, fastingStart,fastingEnd)) {
            return "1";//"空腹血糖"
        }
        if (isInArea(dateTime, afterBreakFastStart,afterBreakFastEnd)) {
            return "2";//"早餐后血糖"
        }
        if (isInArea(dateTime, beforeLunchStart,beforeLunchEnd)) {
            return "3";//"午餐前血糖"
        }
        if (isInArea(dateTime, afterLunchStart,afterLunchEnd)) {
            return "4";//"午餐后血糖"
        }
        if (isInArea(dateTime, beforeDinnerStart,beforeDinnerEnd)) {
            return "5";//"晚餐前血糖"
        }
        if (isInArea(dateTime, afterDinnerStart,afterDinnerEnd)) {
            return "6";//"晚餐后血糖"
        }
        if (isInArea(dateTime, beforeSleepStart,beforeSleepEnd)) {
            return "7";//"睡前血糖"
        }
        return "1";//"空腹血糖"
    }
    // 判断时间是否在对应时间段
    private Boolean isInArea(String time,String begin,String end) {
        String date = DateUtil.getDateFromDateTime(time);
        Long beginTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + begin ));
        Long endTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + end ));
        if (beginTime > 0 && endTime < 0) {
            return true;
        } else {
            return false;
        }
    }
}

+ 10 - 6
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java

@ -58,6 +58,8 @@ public class PatientDeviceService  {
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    @Autowired
    private DeviceDetailService deviceDetailService;
    /**
@ -109,6 +111,7 @@ public class PatientDeviceService  {
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new ServiceException("sn码" + sn + "已被使用!");
            }
            deviceDetailService.registerToWlyy(patientDevice);
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
@ -116,12 +119,13 @@ public class PatientDeviceService  {
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            savePatientDevice(patientDevice);
        }else {
            String message = "设备不存在";
            throw new ServiceException(message);
        }
        savePatientDevice(patientDevice);
//        if(checkDeviceSn(sn)){
//            savePatientDevice(patientDevice);
//        }else {
//            String message = "设备不存在";
//            throw new ServiceException(message);
//        }
        return true;
    }

+ 0 - 12
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DoctorRehabilitaionInfoController.java

@ -386,18 +386,6 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
        }
    }
    @RequestMapping(value = "ttt", method = RequestMethod.GET)
    @ApiOperation("添加编辑住院病历")
    public String ttt() {
        try {
            return write(200, "添加成功", "data", rehabilitationInfoService.findByCode("2c53ebdec84747d48526abc40702c395"));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "添加失败");
        }
    }
    @RequestMapping(value = "createMedicalRecords", method = RequestMethod.POST)
    @ApiOperation("添加编辑住院病历")
    public String createMedicalRecords(

+ 2 - 21
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java

@ -5,7 +5,6 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.rehabilitation.PatientDischargeDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
@ -18,14 +17,11 @@ import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationPatientInfoD
import com.yihu.jw.hospital.module.specialist.dao.PatientMedicalRecordsRehabilitationDao;
import com.yihu.jw.hospital.module.system.dao.SystemDictDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -56,18 +52,12 @@ public class RehabilitationInfoService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BasePatientService patientService;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private WlyySignFamilyDao signFamilyDao;
    @Autowired
    private RehabilitationAdviceDao adviceDao;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao patientMedicalRecordsDao;
@ -277,17 +267,8 @@ public class RehabilitationInfoService {
            Integer age = IdCardUtil.getAgeForIdcard(idcard);
            jsonObject.put("sex", sex);
            jsonObject.put("age", age);
            SignFamily signFamily = signFamilyDao.getExpensesSignByIdcard(idcard);
            if (signFamily != null) {
                jsonObject.put("doctorName", signFamily.getDoctorName() + "(全科医生)");
                if (StringUtils.isNotBlank(signFamily.getDoctorHealthName())) {
                    jsonObject.put("doctorHealthName", signFamily.getDoctorHealthName() + "(健管师)");
                }
                jsonObject.put("hospitalName", signFamily.getHospitalName());
                signList.add(jsonObject);
            } else {
                nosignList.add(jsonObject);
            }
            nosignList.add(jsonObject);
        }
        result.put("noSignArray", nosignList);
        result.put("signArray", signList);

+ 85 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/CountDistance.java

@ -0,0 +1,85 @@
package com.yihu.jw.hospital.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
@Component
public class CountDistance {
    private static double EARTH_RADIUS = 6378.137;// 6378.137赤道半径6378137
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
    /**
     * 通过经纬度计算两点之间的距离(单位:千米)
     * @param latone
     * @param lngone
     * @param lattwo
     * @param lngtwo
     * @return
     */
    public double getDistance(double latone, double lngone, double lattwo, double lngtwo) {
        double radlatone = rad(latone);
        double radlattwo = rad(lattwo);
        double a = radlatone - radlattwo;
        double b = rad(lngone) - rad(lngtwo);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radlatone) * Math.cos(radlattwo)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s;
        return s;
    }
    /**
     * 判断坐标是否在多边形区域内
     * @param pointLon
     * @param pointLat
     * @param rangePositions 多边形坐标 [{"lon":118.19302036660137,"lat":24.494515439791996},{"lon":118.19401849369201,"lat":24.49606682685256}]
     * @return
     */
    public boolean isInPolygon(double pointLon, double pointLat, JSONArray rangePositions) {
        // 将要判断的横纵坐标组成一个点
        double[] lon =  rangePositions.stream().mapToDouble(item->((JSONObject)item).getDouble("lon")).toArray();
        double[] lat =  rangePositions.stream().mapToDouble(item->((JSONObject)item).getDouble("lat")).toArray();;
        Point2D.Double point = new Point2D.Double(pointLon, pointLat);
        // 将区域各顶点的横纵坐标放到一个点集合里面
        List<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
        double polygonPoint_x = 0.0, polygonPoint_y = 0.0;
        for (int i = 0; i < lon.length; i++) {
            polygonPoint_x = lon[i];
            polygonPoint_y = lat[i];
            Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x, polygonPoint_y);
            pointList.add(polygonPoint);
        }
        return check(point, pointList);
    }
    private static boolean check(Point2D.Double point, List<Point2D.Double> polygon) {
        java.awt.geom.GeneralPath peneralPath = new java.awt.geom.GeneralPath();
        Point2D.Double first = polygon.get(0);
        // 通过移动到指定坐标(以双精度指定),将一个点添加到路径中
        peneralPath.moveTo(first.x, first.y);
        polygon.remove(0);
        for (Point2D.Double d : polygon) {
            // 通过绘制一条从当前坐标到新指定坐标(以双精度指定)的直线,将一个点添加到路径中。
            peneralPath.lineTo(d.x, d.y);
        }
        // 将几何多边形封闭
        peneralPath.lineTo(first.x, first.y);
        peneralPath.closePath();
        // 测试指定的 Point2D 是否在 Shape 的边界内。
        return peneralPath.contains(point);
    }
}

+ 110 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceDataPushLogUtil.java

@ -0,0 +1,110 @@
package com.yihu.jw.hospital.utils;
import com.yihu.jw.device.dao.DeviceDataPushLogDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDataPushLog;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by Bing on 2021/9/2.
 * 设备数据推送日志保存
 */
@Component
public class DeviceDataPushLogUtil {
    @Autowired
    private DeviceDataPushLogDao deviceDataPushLogDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceLostMessageUtil deviceLostMessageUtil;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void savePushLog(String sn,String data,String apiName){
        try {
            DeviceDataPushLog pushLog = new DeviceDataPushLog();
            pushLog.setDeviceSn(sn);
            pushLog.setData(data);
            pushLog.setApiName(apiName);
            pushLog.setCreateTime(new Date());
            List<DevicePatientDevice> devices= patientDeviceDao.findByDeviceSn(sn);
            if (devices.size()>0){
                DevicePatientDevice tmp = devices.get(0);
                BasePatientDO patientDO = patientDao.findById(tmp.getUser()).orElse(null);
                if (null!=patientDO){
                    pushLog.setPatient(tmp.getUser());
                    pushLog.setPatientName(patientDO.getName());
                }
                pushLog.setDeviceName(tmp.getDeviceName());
                pushLog.setDeviceCategory(tmp.getCategoryCode());
            }
            deviceDataPushLogDao.save(pushLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 更新在线状态 及次数
     * @param sn
     * @param status
     * @param flag 状态 true 异常 false 正常 null其他
     */
    @Transactional
    public void updContactStatus(String sn,Integer status,Boolean flag){
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(sn);
        if(deviceDetail!=null){
            deviceDetail.setContactStatus(status);
            if(0==status){
                List<String> sns =  new ArrayList<String>();
                sns.add(sn);
                deviceLostMessageUtil.deviceLostMessage(sns);
            }
            else if(1==status){
                //设备在线清除原有的离线消息
                List<String> sns = new ArrayList<String>();
                sns.add(sn);
                systemMessageDao.delMessageByRelationCode(sns);
            }
            deviceDetail.setContactStatusTime(new Date());
            if(deviceDetail.getCollectNum()==null){
                deviceDetail.setCollectNum(0L);
            }
            if(deviceDetail.getAbnormalNum()==null){
                deviceDetail.setAbnormalNum(0L);
            }
            if(flag!=null){
                deviceDetail.setCollectNum(deviceDetail.getCollectNum()+1L);
                if(flag){
                    deviceDetail.setAbnormalNum(deviceDetail.getAbnormalNum()+1L);
                }
            }
            deviceDetailDao.save(deviceDetail);
        }
    }
}

+ 116 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceLostMessageUtil.java

@ -0,0 +1,116 @@
package com.yihu.jw.hospital.utils;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Bing on 2021/9/13.
 */
@Component
public class DeviceLostMessageUtil {
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * 设备离线通知
     * @param devices
     */
    public void deviceLostMessage(List<String> devices){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        for (String id:devices){
            List<SystemMessageDO> sendMessageBefore = systemMessageDao.queryByRelationCodeAndTypeIn(id,new String[]{"43"});
            if (sendMessageBefore.size()>0){//删除之前的离线消息
                systemMessageDao.deleteAll(sendMessageBefore);
            }
            List<DevicePatientDevice> pds =  patientDeviceDao.findByDeviceSn(id);
            if (pds.size()>0){
                DevicePatientDevice deviceDO = pds.get(0);
                String sql = "SELECT DISTINCT d.id,d.name from base_service_package_sign_record sr,base_service_package_record r,base_team_member m,base_doctor d  " +
                        "               WHERE sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id and m.doctor_code = d.id " +
                        "               and m.del = '1' and sr.patient = '"+deviceDO.getUser()+"' " ;
                List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
                // 家属
                sql = " select  t2.id,t2.name from  base_patient_family_member t1,  base_patient t2 where  " +
                        "t2.id in (select family_member from base_patient_family_member where patient = '"+deviceDO.getUser()+"' )  " +
                        " and t1.patient = '"+deviceDO.getUser()+"'  and t1.family_member = t2.id  " +
                        " and t2.archive_type=3 GROUP BY t2.id " ;
                List<Map<String,Object>> relatives = jdbcTemplate.queryForList(sql);
                doctors.addAll(relatives);
                String deviceName="";
                for (Map<String,Object> docTmp:doctors){
                    switch (deviceDO.getCategoryCode()){
                        case "1":
                            deviceName="血糖仪离线";
                            break;
                        case "2":
                            deviceName="血压计离线";
                            break;
                        case "4":
                            deviceName="智能手表离线";
                            break;
                        case "7":
                            deviceName="居家安全报警器离线";
                            break;
                        case "12":
                            deviceName="监控器离线";
                            break;
                        case "13":
                            deviceName="睡眠带离线";
                            break;
                        case "14":
                            deviceName="气感报警器离线";
                            break;
                        case "15":
                            deviceName="烟感报警器离线";
                            break;
                        case "16":
                            deviceName="智能拐杖离线";
                            break;
                        case "17":
                            deviceName="随身WiFi离线";
                            break;
                    }
                    BasePatientDO patientDO = patientDao.findById(deviceDO.getUser()).orElse(null);
                    SystemMessageDO messageDO = new SystemMessageDO();
                    messageDO.setTitle("设备离线通知");
                    messageDO.setType("43");
                    messageDO.setIsRead("0");
                    messageDO.setSender(deviceDO.getUser());
                    messageDO.setSenderName(patientDO.getName());
                    messageDO.setRelationCode(id);
                    messageDO.setReceiver(docTmp.get("id").toString());
                    messageDO.setReceiverName(docTmp.get("name").toString());
                    messageDO.setOver("1");
                    messageDO.setData(deviceName);
                    messageDO.setDel("1");
                    messageDO.setCreateTime(new Date());
                    messageDO.setSenderPhoto(patientDO.getPhoto());
                    messageDOS.add(messageDO);
                }
            }
        }
        if (messageDOS.size()>0){
            systemMessageDao.saveAll(messageDOS);
        }
    }
}