Browse Source

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

hzp 8 years ago
parent
commit
edd078ac2b
100 changed files with 12120 additions and 0 deletions
  1. BIN
      patient-co-statistics-es/doc/业务文档/统计指标流程.docx
  2. BIN
      patient-co-statistics-es/doc/部署文档/正式库/后台/tomcat部署.docx
  3. 448 0
      patient-co-statistics-es/pom.xml
  4. 18 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/Application.java
  5. 49 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/AsyncConfig.java
  6. 42 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java
  7. 62 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/SwaggerConfig.java
  8. 40 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/WebSecurityConfig.java
  9. 25 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/quartz/JobFactory.java
  10. 52 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/quartz/SchedulerConfig.java
  11. 15 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java
  12. 464 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/BaseController.java
  13. 64 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/DataProcessController.java
  14. 431 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java
  15. 19 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/CityDao.java
  16. 119 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/ConsultTeamDao.java
  17. 24 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorAdminTeamDao.java
  18. 115 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorDao.java
  19. 111 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorPatientGroupInfoDao.java
  20. 29 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorTeamDao.java
  21. 60 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorTeamMemberDao.java
  22. 23 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkTimeDao.java
  23. 40 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkWeekDao.java
  24. 25 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/HospitalDao.java
  25. 17 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/JobConfigDao.java
  26. 50 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/MessageDao.java
  27. 56 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientDao.java
  28. 59 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientDiseaseDao.java
  29. 54 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientHealthGuidanceDao.java
  30. 27 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java
  31. 11 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobLogDao.java
  32. 11 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuotaDao.java
  33. 47 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignFamilyDao.java
  34. 55 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignPatientLabelDao.java
  35. 68 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignPatientLabelInfoDao.java
  36. 24 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/TownDao.java
  37. 17 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/WlyyDimensionQuotaDao.java
  38. 24 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/WlyyQuotaResultDao.java
  39. 63 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/data/DataHandingService.java
  40. 34 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/data/DataHandlingController.java
  41. 28 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/cache/Cache.java
  42. 189 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/compute/ComputeHelper.java
  43. 15 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/Convert.java
  44. 48 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/ConvertHelper.java
  45. 51 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/AgeConvert.java
  46. 34 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/ConsultTimeConvert.java
  47. 36 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/SexConvert.java
  48. 33 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/SimpleConvert.java
  49. 84 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/ExtractHelper.java
  50. 67 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/db/DBExtract.java
  51. 155 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/db/DBPageExtract.java
  52. 47 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/filter/FilterHelper.java
  53. 34 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/filter/filter/NotNullFilter.java
  54. 25 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/SaveHelper.java
  55. 44 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/es/ElasticFactory.java
  56. 56 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/es/ElastricSearchSave.java
  57. 323 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentMysqlToEsQuotaJob.java
  58. 309 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/MysqlToEsQuotaJob.java
  59. 95 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/check/CheckSignJob.java
  60. 101 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/FollowupPlanJob.java
  61. 150 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/HealthMessageJob.java
  62. 221 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/NoticeJob.java
  63. 38 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/IdEntity.java
  64. 230 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/consult/ConsultTeam.java
  65. 221 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/consult/ConsultTeamDto.java
  66. 115 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/dimension/WlyyDimension.java
  67. 69 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/dimension/WlyyDimensionQuota.java
  68. 362 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/Doctor.java
  69. 71 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/DoctorPatientGroup.java
  70. 128 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/DoctorPatientGroupInfo.java
  71. 116 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkTime.java
  72. 70 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkWeek.java
  73. 156 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/hosptial/Hospital.java
  74. 170 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/QuartzJobConfig.java
  75. 104 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/QuartzJobLog.java
  76. 117 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/WlyyQuota.java
  77. 229 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/WlyyQuotaResult.java
  78. 96 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/label/SignPatientLabel.java
  79. 79 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/label/SignPatientLabelInfo.java
  80. 321 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/Patient.java
  81. 67 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientDisease.java
  82. 96 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientHealthGuidance.java
  83. 322 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientReservation.java
  84. 256 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/Message.java
  85. 454 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamily.java
  86. 539 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamilyRenew.java
  87. 57 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/system/City.java
  88. 78 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/system/Town.java
  89. 107 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/AdminTeam.java
  90. 68 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/DoctorTeam.java
  91. 130 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/DoctorTeamMember.java
  92. 306 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/DoctorWorkTimeService.java
  93. 446 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java
  94. 96 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PatientDiseaseToLabel.java
  95. 156 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PatientGroupToLabelRunnable.java
  96. 151 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PushMsgTask.java
  97. 200 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/SignTeamAndGroupRunnable.java
  98. 142 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/Contant.java
  99. 720 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/DateUtil.java
  100. 0 0
      patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/HttpClientUtil.java

BIN
patient-co-statistics-es/doc/业务文档/统计指标流程.docx


BIN
patient-co-statistics-es/doc/部署文档/正式库/后台/tomcat部署.docx


+ 448 - 0
patient-co-statistics-es/pom.xml

@ -0,0 +1,448 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <groupId>com.yihu</groupId>
    <artifactId>patient-co-statistics-es</artifactId>
    <version>1.0.0</version>
    <modelVersion>4.0.0</modelVersion>
    <!--打成war包需要的配置-->
    <packaging>war</packaging>
    <!--<packaging>jar</packaging>-->
    <name>patient-co-statistics-es</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>${version.spring-framework}</spring.version>
        <version.commons-bean-utils>1.9.2</version.commons-bean-utils>
        <version.commons-codec>1.9</version.commons-codec>
        <version.commons-collections>3.2.1</version.commons-collections>
        <version.commons-compress>1.9</version.commons-compress>
        <version.commons-dbcp2>2.1.1</version.commons-dbcp2>
        <version.commons-dbutils>1.6</version.commons-dbutils>
        <version.commons-io>2.4</version.commons-io>
        <version.commons-lang3>3.2.1</version.commons-lang3>
        <version.commons-pool2>2.4.2</version.commons-pool2>
        <version.hibernate>4.3.11.Final</version.hibernate>
        <version.hibernate-annotations>4.0.5.Final</version.hibernate-annotations>
        <version.hibernate-jpa-api>1.0.0.Final</version.hibernate-jpa-api>
        <version.http-client>4.5.1</version.http-client>
        <version.http-core>4.4.3</version.http-core>
        <version.java>1.8</version.java>
        <version.jackson>2.6.6</version.jackson>
        <version.jedis>2.9.0</version.jedis>
        <version.jcl-over-slf4j>1.7.19</version.jcl-over-slf4j>
        <version.jul-over-slf4j>1.7.21</version.jul-over-slf4j>
        <version.joda-time>2.8.2</version.joda-time>
        <version.junit>4.12</version.junit>
        <version.log4j2>2.4.1</version.log4j2>
        <version.logback>1.1.7</version.logback>
        <version.mysql>5.1.38</version.mysql>
        <version.quartz>2.2.3</version.quartz>
        <version.servlet-api>3.1.0</version.servlet-api>
        <version.slf4j>1.7.21</version.slf4j>
        <version.spring-boot>1.3.5.RELEASE</version.spring-boot>
        <version.spring-framework>4.2.5.RELEASE</version.spring-framework>
        <version.spring-session>1.2.0.RELEASE</version.spring-session>
        <version.swagger>2.4.0</version.swagger>
        <version.swagger-ui>2.4.0</version.swagger-ui>
        <version.tomcat-embed>8.0.28</version.tomcat-embed>
        <version.elasticsearch>2.4.4</version.elasticsearch>
        <version.jest>2.4.0</version.jest>
    </properties>
    <dependencies>
        <!--Jackson library-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <!--elasticsearch start-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${version.elasticsearch}</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>${version.jest}</version>
        </dependency>
        <!--elasticsearch end-->
        <!--Apache commons library-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${version.commons-lang3}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>${version.http-core}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${version.http-client}</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>${version.commons-bean-utils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${version.commons-pool2}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>${version.commons-dbutils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${version.commons-dbcp2}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>${version.commons-collections}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>${version.commons-compress}</version>
        </dependency>
        <!--Hibernate framework-->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>${version.hibernate-jpa-api}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${version.hibernate}</version>
        </dependency>
        <!--Miscellaneous-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${version.servlet-api}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${version.swagger}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${version.swagger-ui}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${version.mysql}</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${version.joda-time}</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${version.jedis}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>${version.commons-codec}</version>
        </dependency>
        <!--Log framework-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <!--Log framework to SLF4J bridge: x-over-slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${version.jcl-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-jdk14</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${version.jul-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--SLF4J api-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <!--The single log BACKEND-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${version.logback}</version>
        </dependency>
        <!--Spring framework family-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <!--Spring session family-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>${version.spring-session}</version>
        </dependency>
        <!--Spring integration family-->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jmx</artifactId>
            <version>${version.spring-framework}</version>
        </dependency>
        <!--Spring batch family-->
        <!--Spring boot family-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-devtools</artifactId>-->
        <!--<version>${version.spring-boot}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${version.spring-boot}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <version>${version.spring-boot}</version>
            <!--<scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20151123</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!--打成war包需要的配置-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <version>3.1</version>
            </plugin>
        </plugins>
    </build>
</project>

+ 18 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/Application.java

@ -0,0 +1,18 @@
package com.yihu.wlyy.statistics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
/**
 * Created by Administrator on 2016.10.12.
 */
@SpringBootApplication
public class Application {
    public static ApplicationContext ctx = null;
    public static void main(String[] args) {
        ctx = SpringApplication.run(Application.class, args);
    }
}

+ 49 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/AsyncConfig.java

@ -0,0 +1,49 @@
package com.yihu.wlyy.statistics.config;
import java.util.concurrent.Executor;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * Created by Administrator on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig  {
    /** 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程 */
    private int corePoolSize = 5;
    /** 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity. */
    private int maxPoolSize = 20;
    /** 缓冲队列. */
    private int queueCapacity = 10;
    @Bean
    public Executor dbExtractExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Bean
    public Executor dbStorageExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

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

@ -0,0 +1,42 @@
package com.yihu.wlyy.statistics.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
 * Created by Administrator on 2016.10.20.
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
    /**
     *  主数据源
     * @return
     */
    @Bean(name = "primaryReadWrite")
    @Primary//主库 默认不写名字用这个
    @ConfigurationProperties(prefix="spring.datasource.primaryReadWrite")
    public DataSource primaryReadWriteDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "primaryRead")
    @ConfigurationProperties(prefix="spring.datasource.primaryRead")
    public DataSource primaryReadDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "imData")
    @ConfigurationProperties(prefix="spring.datasource.im")
    public DataSource imDataSource() {
        return DataSourceBuilder.create().build();
    }
}

+ 62 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/SwaggerConfig.java

@ -0,0 +1,62 @@
package com.yihu.wlyy.statistics.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    private static final String PUBLIC_API = "Default";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Bean
    public Docket publicAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(PUBLIC_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(
                        regex("/job/.*")
                ))
                .build()
                .apiInfo(publicApiInfo());
    }
    private ApiInfo publicApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台统计分析API",
                "统计分析接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
}

+ 40 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/WebSecurityConfig.java

@ -0,0 +1,40 @@
package com.yihu.wlyy.statistics.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * Created by Administrator on 2016.10.17.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${security.basic.username}")
    String username;
    @Value("${security.basic.password}")
    String password;
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().defaultSuccessUrl("/swagger-ui.html").failureUrl("/login") //登录成功之后的跳转
                .permitAll()
                .and()
                .logout().logoutSuccessUrl("/login")
                .permitAll();
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser(username).password(password).roles("USER");
    }
}

+ 25 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/quartz/JobFactory.java

@ -0,0 +1,25 @@
package com.yihu.wlyy.statistics.config.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * Created by Administrator on 2016.10.12.
 * 為了讓quartz種可以使用Spring的注入
 */
@Component("jobFactory")
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
       // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

+ 52 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/quartz/SchedulerConfig.java

@ -0,0 +1,52 @@
package com.yihu.wlyy.statistics.config.quartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
public class SchedulerConfig {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JobFactory jobFactory;
    @Autowired
    private DataSource dataSource;
    @Bean
    SchedulerFactoryBean schedulerFactoryBean_cwd() throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setJobFactory(jobFactory);
        bean.setApplicationContext(this.applicationContext);
        bean.setOverwriteExistingJobs(true);
        bean.setStartupDelay(20);// 延时启动
        bean.setAutoStartup(true);
        bean.setDataSource(dataSource);
        bean.setQuartzProperties(quartzProperties());
        return bean;
    }
    /**
     * quartz配置文件
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}

+ 15 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java

@ -0,0 +1,15 @@
package com.yihu.wlyy.statistics.config.war;
import com.yihu.wlyy.statistics.Application;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
 * Created by Administrator on 2016.10.14.
 */
public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

+ 464 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/BaseController.java

@ -0,0 +1,464 @@
package com.yihu.wlyy.statistics.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.statistics.model.IdEntity;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	protected HttpServletRequest request;
	/**
	 * 獲取髮送請求用戶的uid
	 * @return
	 */
	public String getUID() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("uid");
			
		} catch (Exception e) {
			return null;
		}
	}
	public String getOpenid() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("openid");
			
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 获取用户ID
	 * @return
	 */
	public long getId() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getLong("id");
		} catch (Exception e) {
			return 0;
		}
	}
	public String getIMEI() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("imei");
		} catch (Exception e) {
			return null;
		}
	}
	
	public String getToken() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("token");
		} catch (Exception e) {
			return null;
		}
	}
	public void error(Exception e) {
		logger.error(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	public void warn(Exception e) {
		logger.warn(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	/**
	 * 返回接口处理结果
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String error(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 接口处理成功
	 * @param msg
	 * @return
	 */
	public String success(String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", 200);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, List<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, list);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONObject value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param total 总数
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, int total, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put("total", total);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Object value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			// 是否为第一页
			map.put("isFirst", list.isFirst());
			// 是否为最后一页
			map.put("isLast", list.isLast());
			// 总条数
			map.put("total", list.getTotalElements());
			// 总页数
			map.put("totalPages", list.getTotalPages());
			map.put(key, list.getContent());
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 *
	 *
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", page.isFirst());
			// 是否为最后一页
			json.put("isLast", page.isLast());
			// 总条数
			json.put("total", page.getTotalElements());
			// 总页数
			json.put("totalPages", page.getTotalPages());
			json.put(key, array);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Map<?, ?> value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, String value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, IdEntity entity) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, entity);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", isFirst);
			// 是否为最后一页
			json.put("isLast", isLast);
			// 总条数
			json.put("total", total);
			// 总页数
			json.put("totalPages", totalPages);
			json.put(key, values);
			return json.toString();
		} catch (Exception e) {
			logger.error("BaseController:", e.getMessage());
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	public String trimEnd(String param, String trimChars) {
		if (param.endsWith(trimChars)) {
			param = param.substring(0, param.length() - trimChars.length());
		}
		return param;
	}
	/**
	 * 无效用户消息返回
	 * @param e
	 * @param defaultCode
	 * @param defaultMsg
	 * @return
	 */
	public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
		try {
			// if (e instanceof UndeclaredThrowableException) {
			// UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
			// InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
			// if (iue != null) {
			// return error(iue.getCode(), iue.getMsg());
			// }
			// }
			return error(defaultCode, defaultMsg);
		} catch (Exception e2) {
			return null;
		}
	}
}

+ 64 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/DataProcessController.java

@ -0,0 +1,64 @@
package com.yihu.wlyy.statistics.controller;
import com.fasterxml.jackson.databind.deser.Deserializers;
import com.yihu.wlyy.statistics.task.PatientDiseaseToLabel;
import com.yihu.wlyy.statistics.task.PatientGroupToLabelRunnable;
import com.yihu.wlyy.statistics.task.SignTeamAndGroupRunnable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by lyr-pc on 2016/10/12.
 */
@RestController
@RequestMapping(value = "/data_process")
public class DataProcessController extends BaseController {
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_team_group_thread")
    public String setTeamGroupPage(long start,long end){
        try {
            new Thread(new SignTeamAndGroupRunnable(start,end)).start();
            return write(200,"启动成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "启动失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/disease_to_label_thread")
    public String diseaseToLabel(long start){
        try {
            new Thread(new PatientDiseaseToLabel(start)).start();
            return write(200,"启动成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "启动失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/group_to_label_thread")
    public String diseaseToLabel(long start,long end){
        try {
            new Thread(new PatientGroupToLabelRunnable(start,end)).start();
            return write(200,"启动成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "启动失败");
        }
    }
}

+ 431 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java

@ -0,0 +1,431 @@
package com.yihu.wlyy.statistics.controller;
import com.yihu.wlyy.statistics.service.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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;
/**
 * 任务启动
 *
 * @author chenweida
 */
@RestController
@RequestMapping(value = "/job", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "后台-任务控制")
public class JobController extends BaseController {
    @Autowired
    private  JobService jobService;
    /**
     * 启动任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "根据ID立即单个任务")
    @RequestMapping(value = "startNowById", method = RequestMethod.GET)
    public String startNowById(
            @ApiParam(name = "id", value = "任务ID", required = true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startNowById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去几天的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去几天的数据")
    @RequestMapping(value = "productDataByDay", method = RequestMethod.GET)
    public String productDataByDay(  @ApiParam(name = "day", value = "距离今天的天数(如果是要生成昨天的数据,day=1)")@RequestParam(value = "day", required = true) int day) {
        try {
            jobService.productDataByDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的全部的数据")
    @RequestMapping(value = "productDataByOneDay", method = RequestMethod.GET)
    public String productDataByOneDay( @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day) {
        try {
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的全部的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的全部的数据(包含头尾)")
    @RequestMapping(value = "productDataByDayToDay", method = RequestMethod.GET)
    public String productDataByDayToDay( @ApiParam(name = "start", value = "yyyy-MM-dd", required = true)@RequestParam(value = "start", required = true)String start,
                                         @ApiParam(name = "end", value = "yyyy-MM-dd", required = true)@RequestParam(value = "end", required = true)String end) {
        try {
            jobService.productDataByDayToDay(start,end);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的某个指标的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的某个指标的数据(包含头尾)")
    @RequestMapping(value = "productDataByDayToDayAndId", method = RequestMethod.GET)
    public String productDataByDayToDayAndId( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                         @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end,
                                              @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id) {
        try {
            
            jobService.productDataByDayToDayAndId(start,end,id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的某一个指标的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的全部的数据")
    @RequestMapping(value = "productDataByOneDayWithId", method = RequestMethod.GET)
    public String productDataByOneDayWithId(
            @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day,
            @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去到现在的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去到现在的全部的数据")
    @RequestMapping(value = "productDataByDayAndId", method = RequestMethod.GET)
    public String productDataByDayAndId(
            @ApiParam(name = "day", value = "距离今天的天数(如果是要生成昨天的数据,day=1)")@RequestParam(value = "day", required = true) int day,
            @ApiParam(name="id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动任务
     *
     * @param id id
     * @return
    */
    @ApiOperation(value = "启动单个任务")
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(
            @ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "停止单个任务")
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(@ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止所有任务
     *
     * @return
     */
    @ApiOperation(value = "停止所有任务")
    @RequestMapping(value = "stopAll", method = RequestMethod.GET)
    public String stopAll() {
        try {
            jobService.stopAll();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动判断的任务
     *
     * @return
     */
    @ApiOperation(value = "启动檢查的任务")
    @RequestMapping(value = "startCheckSignJob", method = RequestMethod.GET)
    public String startCheckSignJob() {
        try {
            jobService.startCheckSignJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止判断的任务
     *
     * @return
     */
    @ApiOperation(value = "停止檢查的任务")
    @RequestMapping(value = "stopCheckSignJob", method = RequestMethod.GET)
    public String stopCheckSignJob() {
        try {
            jobService.stopCheckSignJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动所有任务
     *
     * @return
     */
    @ApiOperation(value = "启动所有任务")
    @RequestMapping(value = "startAll", method = RequestMethod.GET)
    public String startAll() {
        try {
            jobService.startAll();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "清除緩存")
    @RequestMapping(value = "cleanCache", method = RequestMethod.GET)
    public String cleanCache() {
        try {
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动健康信息生成的任务
     *
     * @return
     */
    @ApiOperation(value = "启动健康信息生成的任务")
    @RequestMapping(value = "startHealthMessageJob", method = RequestMethod.GET)
    public String startHealthMessageJob() {
        try {
            jobService.startHealthMessageJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "立即启动健康信息生成的任务")
    @RequestMapping(value = "startHealthMessageJobNow", method = RequestMethod.GET)
    public String startHealthMessageJobNow() {
        try {
            jobService.startHealthMessageJobNow();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止判断的任务
     *
     * @return
     */
    @ApiOperation(value = "停止健康信息生成的任务")
    @RequestMapping(value = "stopHealthMessageJob", method = RequestMethod.GET)
    public String stopHealthMessageJob() {
        try {
            jobService.stopHealthMessageJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的健康消息
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的健康消息")
    @RequestMapping(value = "productHealthDataByOneDay", method = RequestMethod.GET)
    public String productHealthDataByOneDay( @ApiParam(name = "day", value = "yyyy-MM-dd")
                                           @RequestParam(value = "day", required = true)String day) {
        try {
            jobService.productHealthDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的某个指标的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的健康消息(包含头尾)")
    @RequestMapping(value = "productHealthDataByDayToDay", method = RequestMethod.GET)
    public String productHealthDataByDayToDay( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                              @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end
                                             ) {
        try {
            jobService.productHealthDataByDayToDay(start,end);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "启动通知任务")
    @RequestMapping(value = "startNoticeJob", method = RequestMethod.GET)
    public String startNoticeJob() {
        try {
            jobService.startNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "立即启动通知任务")
    @RequestMapping(value = "startNoticeJobNow", method = RequestMethod.GET)
    public String startNoticeJobNow() {
        try {
            jobService.startNoticeJobNow();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "停止通知任务")
    @RequestMapping(value = "stopNoticeJob", method = RequestMethod.GET)
    public String stopNoticeJob() {
        try {
            jobService.stopNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /******************************** 随访计划消息 ****************************************************/
    @ApiOperation(value = "启动随访计划消息任务")
    @RequestMapping(value = "startFollowupPlantJob", method = RequestMethod.GET)
    public String startFollowupPlantJob() {
        try {
            jobService.startFollowupPlantJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "停止随访计划消息任务")
    @RequestMapping(value = "stopFollowupPlantJob", method = RequestMethod.GET)
    public String stopFollowupPlantJob() {
        try {
            jobService.stopFollowupPlantJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 19 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/CityDao.java

@ -0,0 +1,19 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.system.City;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface CityDao extends PagingAndSortingRepository<City, Long> {
	// 根據CODE查詢城市名稱
	@Query("select p from City p where p.code = ?1")
	City findByCode(String code);
	
	@Query("select a from City a where a.province = ?1 order by id")
	Iterable<City> findByProvince(String province);
}

+ 119 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/ConsultTeamDao.java

@ -0,0 +1,119 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface ConsultTeamDao extends PagingAndSortingRepository<ConsultTeam, Long>, JpaSpecificationExecutor<ConsultTeam> {
	// 根據consult查詢咨询记录
	ConsultTeam findByConsult(String consult);
	@Query("select a from ConsultTeam a where a.patient = ?1 and a.del = '1' and a.status = 0")
	List<ConsultTeam> findUnfinishedConsult(String patient);
	// 统计未完成的数量
	@Query("select count(1) from ConsultTeam a where a.patient = ?1 and a.status = 0 and a.del = '1'and a.type=?2")
	int countByPatient(String patient, Integer signType);
	// 医生关闭三师咨询
	@Modifying
	@Query("update ConsultTeam a set a.status = 1 where a.consult = ?1")
	int updateStatusByConsult(String consult);
	@Modifying
	@Query("update ConsultTeam a set a.doctorRead = 0 where a.consult = ?1")
	int updateReadedByConsult(String consult);
	/**
	 * 解约时结束家庭咨询
	 *
	 * @param patient
	 * @return
	 */
	@Modifying
	@Query("update ConsultTeam a set a.status = 1 where a.patient =?1 and a.type = 2")
	int updateStatusByPatient(String patient);
	// 取消三师咨询
	@Modifying
	@Query("update ConsultTeam a set a.status = -1 where a.consult = ?1 and a.status <> 1")
	int cancel(String consult);
	// 患者咨询列表(未结束)
	@Query("select a from ConsultTeam a where a.patient = ?1 and a.status=0 and del = '1'")
	Page<ConsultTeam> findNotFinishedBypatient(String patient, Pageable pageRequest);
	@Query("select a from ConsultTeam a where a.patient = ?1 and a.id < ?2 and a.status=0 and del = '1'")
	Page<ConsultTeam> findNotFinishedBypatient(String patient, long id, Pageable pageRequest);
	// 患者咨询列表(已结束)
	@Query("select a from ConsultTeam a where a.patient=?1 and a.status=1 and del = '1'")
	Page<ConsultTeam> findFinishedBypatient(String patient, Pageable pageRequest);
	@Query("select a from ConsultTeam a where a.patient=?1 and a.id < ?2 and a.status=1 and del = '1'")
	Page<ConsultTeam> findFinishedBypatient(String patient, long id, Pageable pageRequest);
	// 患者咨询列表(已取消)
	@Query("select a from ConsultTeam a where a.patient=?1 and a.status=-1 and del = '1'")
	Page<ConsultTeam> findCancelBypatient(String patient, Pageable pageRequest);
	@Query("select a from ConsultTeam a where a.patient=?1 and a.id < ?2 and a.status=-1 and del = '1'")
	Page<ConsultTeam> findCancelBypatient(String patient, long id, Pageable pageRequest);
	// 医生未读数量+1
	@Modifying
	@Query("update ConsultTeam a set a.doctorRead = a.doctorRead + 1 where a.consult = ?1")
	int increaseDoctorRead(String consult);
	// 患者未读数量+1
	@Modifying
	@Query("update ConsultTeam a set a.patientRead = a.patientRead + 1 where a.consult = ?1")
	int increasePatientRead(String consult);
	// 清空医生未读数量
	@Modifying
	@Query("update ConsultTeam a set a.doctorRead = 0 where a.consult = ?1")
	int clearDoctorRead(String consult);
	// 清空患者未读数量
	@Modifying
	@Query("update ConsultTeam a set a.patientRead = 0 where a.consult = ?1")
	int clearPatientRead(String consult);
	// 更新患者评价标识
	@Modifying
	@Query("update ConsultTeam a set a.commentContent = ?2, a.commentStar = ?3 where a.consult = ?4")
	int updateComment(String commentContent, double commentStar, String consult);
	//找出当日的咨询量
	@Query("SELECT a FROM ConsultTeam a WHERE a.type=2 and unix_timestamp(a.czrq)>=unix_timestamp(?1) and unix_timestamp(a.czrq)<unix_timestamp(?2) ")
	List<ConsultTeam> findByCzrqyYesterday(String yesterday, String now);
	//查找
	@Query("SELECT a FROM ConsultTeam a WHERE a.patient=?1 and a.status=0 and a.del=1 and a.type=6")
	ConsultTeam findFamousConsultByPatient(String uid);
	@Query("select a from ConsultTeam a where  a.type=?3  and a.del = '1' and a.patient=?1 and a.doctor=?2 and  a.status=0 ")
	ConsultTeam findByParientCodeAndSignTypeAndDoctor(String patientCode, String doctor, int s);
    // 更新超过24小时未回复的项目,多加一分钟,防止过于频繁更新
    @Modifying
    @Query("UPDATE ConsultTeam a set a.status = -2 where TIMESTAMPDIFF(SECOND, a.czrq, CURRENT_TIME) > 87840 and status = 0")
    void updateUnresponsedConsultOver24Hours();
    // 最近24小时内未回复的项目
    @Query("FROM ConsultTeam a where TIMESTAMPDIFF(SECOND, a.czrq, CURRENT_TIME) < 86400 and a.status = 0 order by a.czrq desc")
    Page<ConsultTeam> getUnresponsedConsultIn24Hours(Pageable pageable);
	@Query("FROM ConsultTeam a where a.type=?1 and a.adminTeamCode is null")
	List<ConsultTeam> findByTypeAndAdminTeamIdIsNull(Integer s);
}

+ 24 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorAdminTeamDao.java

@ -0,0 +1,24 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * 行政团队DAO。
 * 
 * @author Sand
 */
public interface DoctorAdminTeamDao extends
        PagingAndSortingRepository<AdminTeam, Long>,
        JpaSpecificationExecutor<AdminTeam> {
    @Query(" from AdminTeam t where length(t.orgCode) = 10")
    List<AdminTeam> findAllTeam();
}

+ 115 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorDao.java

@ -0,0 +1,115 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroup;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DoctorDao extends PagingAndSortingRepository<Doctor, Long>, JpaSpecificationExecutor<Doctor> {
    Doctor findByName(String name);
    // 按医生标识查询医生信息
    @Query("select p from Doctor p where p.code = ?1")
    Doctor findByCode(String code);
    @Query("select d from Doctor d where d.del = 1")
    List<Doctor> findAllDoctors();
    @Query("select d from Doctor d where d.del = 1 and d.hospital = ?1")
    Iterable<Doctor> findHospitalDoctors(String hospital);
    // 手机号查询医生信息
    @Query("select p from Doctor p where p.mobile = ?1")
    Doctor findByMobile(String mobile);
    // 根据医生分组查询患者信息
    @Query("select a.group, b.code, b.name, b.photo, b.birthday, b.sex, b.diseaseCondition, b.disease, b.recordAmount, a.partAmount, a.qyrq, a.signType,b.idcard from DoctorPatientGroupInfo a, Patient b where a.doctor = ?1 and a.patient = b.code and a.status=1")
    List<Object> findPatientByDoctorSign(String doctor);
    // 根据医生分组查询患者信息
    @Query("select distinct a.patient,  a.id, b.name, b.photo,b.provinceName,b.cityName,b.townName,b.address, a.begin,b.code,b.mobile,a.signType,b.idcard from SignFamily a, Patient b where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = b.code and a.status=1 ORDER BY a.id desc")
    Page<Object> findPatientByDoctorSign(String doctor, Pageable pageRequest);
    // 根据医生分组查询患者信息
    @Query("select distinct a.patient, a.id, b.name, b.photo,b.provinceName,b.cityName,b.townName,b.address, a.begin,b.code,b.mobile,a.signType,b.idcard from SignFamily a, Patient b where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = b.code and a.id< ?2 and a.status=1  ORDER BY a.id desc")
    Page<Object> findPatientByDoctorSign(String doctor, long id, Pageable pageRequest);
    // 根据医生分组查询患者信息
    @Query("select distinct a.patient, a.id, b.name, b.photo,b.provinceName,b.cityName,b.townName,b.address, a.begin,b.code,b.mobile, a.signType,b.idcard  from SignFamily a, Patient b where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = b.code and a.status=1 and b.name like ?2 and a.status=1 ORDER BY a.id desc")
    Page<Object> findPatientByDoctorSign(String doctor, String patientName, Pageable pageRequest);
    // 根据医生分组查询患者信息
    @Query("select distinct a.patient, a.id, b.name, b.photo,b.provinceName,b.cityName,b.townName,b.address, a.begin,b.code,b.mobile,a.signType,b.idcard  from SignFamily a, Patient b where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = b.code and a.id<?2 and a.status=1 and b.name like ?3 and a.status=1  ORDER BY a.id desc")
    Page<Object> findPatientByDoctorSign(String doctor, long id, String patientName, Pageable pageRequest);
    // 查询医生下的患者总数
    @Query("select count(distinct a.patient) from DoctorPatientGroupInfo a where a.doctor = ?1 and a.status=1")
    int amountPatientByDoctorSign(String doctor);
    @Query("select p from DoctorPatientGroup p where p.doctor = ?1  and p.status = 1")
    Iterable<DoctorPatientGroup> findDoctorPatientGroupWithOutNull(String doctor);
    @Query("select p from DoctorPatientGroup p where (p.doctor = ?1 or p.doctor is null) and p.status = 1 order by p.id asc")
    Iterable<DoctorPatientGroup> findDoctorPatientGroup(String doctor);
    @Query("from Doctor p where p.hospital=?1 and p.level = ?2 and p.iscertified=1 and status=1 ")
    List<Doctor> getDoctorCombobxByHospital(String hospital, int type);
    @Query("from Doctor p where p.level = 1 and p.iscertified=1 and p.status=1 ")
    Page<Doctor> findDoctor1ByParient(Pageable pageRequest);
    @Query("from Doctor p where p.level = 1 and p.iscertified=1 and p.status=1 and p.code != ?1")
    Page<Doctor> findDoctor1ByParient(String code, Pageable pageRequest);
    // 手机号查询正常医生信息
    @Query("select p from Doctor p where p.mobile = ?1 and p.del=1")
    Doctor findNormalByMobile(String mobile);
    @Query("select p from Doctor p where p.level=2 and p.del=1 ")
    List<Doctor> findAllQKDoctot();
    @Query("select p from Doctor p where p.level=3 and p.del=1 ")
    List<Doctor> findAllZKDoctot();
    @Query("select p from Doctor p where p.level=1 and p.del=1 ")
    List<Doctor> findAllJKDoctot();
    @Query("select d from Doctor d where d.del = 1 ")
    List<Doctor> findAllCertifiedDoctors();
    @Query("select p from Doctor p where p.level in (2,3) and p.del=1 and p.iscertified=1")
    List<Doctor> findAllQKDoctotAndJKDoctor();
    @Query(" select p from Doctor p where p.hospital =?1 and p.level =?2 and p.del=1  ")
    List<Doctor> findDoctorByLevelAndHospital(String hospital, Integer level);
    @Modifying
    @Query("update Doctor set idcard = ?2 where code = ?1")
    int updateIdcard(String doctor, String idcard);
    List<Doctor> findByIsFamous(Integer isFamous);
    @Query("select p from Doctor p where p.isFamous=1 and p.name like ?1 ")
    Page<Doctor> doctorFamousDoctorList(String name, Pageable pageRequest);
    @Query("select p from Doctor p where p.isFamous=1 ")
    Page<Doctor> doctorFamousDoctorList(Pageable pageRequest);
    @Query("select d from Doctor d where d.del = 1 and (d.password is null or password = '' )")
    List<Doctor> findAllNoPasswordDoctors();
}

+ 111 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorPatientGroupInfoDao.java

@ -0,0 +1,111 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroup;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DoctorPatientGroupInfoDao extends PagingAndSortingRepository<DoctorPatientGroupInfo, Long>, JpaSpecificationExecutor<DoctorPatientGroupInfo> {
	// 根据签约类型获取患者信息
	@Query("select p from DoctorPatientGroupInfo p where p.group = ?1")
	Iterable<DoctorPatientGroupInfo> findPatientByType(String type);
	@Query("select p from DoctorPatientGroupInfo p where p.doctor = ?1 and p.patient = ?2")
	DoctorPatientGroupInfo findGroupInfoByPatient(String doctor, String patient);
	@Query("select p from DoctorPatientGroupInfo p where p.doctor = ?1 and p.patient = ?2 and p.status = 1 and p.signType = '2'")
	List<DoctorPatientGroupInfo> findGroupInfoByPatientAndDoctor(String doctor, String patient);
	// 删除分组时将原来分组患者移动到other分组
	@Modifying
	@Query("update DoctorPatientGroupInfo a set a.group = 'other' where a.group = ?1")
	int moveByCode(String group);
	// 查询所有分组下的患者信息
	@Query("SELECT p FROM Patient p, DoctorPatientGroupInfo d where p.code = d.patient and d.doctor = ?1")
	List<Patient> findPatientByDisease(String doctor);
	// 片段总数+1
	@Modifying
	@Query("update DoctorPatientGroupInfo a set a.partAmount = a.partAmount + 1 where a.doctor = ?1 and a.patient = ?2")
	int addPartAmount(String doctor, String patient);
	// 片段总数-1
	@Modifying
	@Query("update DoctorPatientGroupInfo a set a.partAmount = a.partAmount - 1 where a.doctor = ?1 and a.patient = ?2")
	int reducePartAmount(String doctor, String patient);
	// 病历总数+1
	@Modifying
	@Query("update Patient a set a.recordAmount = a.recordAmount + 1 where a.code = ?1")
	int addRecordAmount(String patient);
	@Query("SELECT a FROM DoctorPatientGroupInfo a where a.patient = ?1")
	List<DoctorPatientGroupInfo> findByPatient(String patient);
	@Modifying
	@Query("delete DoctorPatientGroupInfo a where a.doctor = ?1 and a.patient = ?2")
	int deleteByDoctorPatient(String doctor, String patient);
	
	@Query("select count(1) from DoctorPatientGroupInfo a where a.doctor = ?1 and a.group = ?2 and a.patient = ?3 and a.status = 1")
	int isExistsInGroup(String doctor, String group, String patient);
	@Modifying
	@Query("update DoctorPatientGroupInfo a set a.group ='2'  where a.patient = ?1 and a.group in ('1','3')")
	int updateGroupByParient(String parientCode);
	@Modifying
	@Query("update DoctorPatientGroupInfo a set a.status =0  where a.patient = ?1 and signType='2'")
	void deleteByPatient(String patient);
	//查找家庭签约的病人所在的分组
	@Query("SELECT a FROM DoctorPatientGroupInfo a where a.patient = ?1 and a.signType='2' and a.group in ('1','2','3') and a.status=1 " )
	List<DoctorPatientGroupInfo> findByMorenPatient(String patient);
	/**
	 * 查询患者存在的医生自建组
	 *
	 * @param patient
	 * @return
	 */
	@Query("select a from DoctorPatientGroupInfo a where a.patient = ?1 and a.status = 1 and a.group not in ('1','2','3')")
	List<DoctorPatientGroupInfo> findPatientGroups(String patient);
	//查找所有的签约患者所在的分组
	@Query("select a from DoctorPatientGroupInfo a where  a.status = 1 and a.signType in ('2','3') and a.group in ('1','2','3')")
	List<DoctorPatientGroupInfo> findAllPatient();
	@Query("select a from DoctorPatientGroupInfo a where  a.status = 1 and a.doctor = ?1 and a.patient = ?2 and a.group = ?3")
	List<DoctorPatientGroupInfo> findDoctorPatientGroup(String doctor, String patient, String group);
	@Query("select count(*) from DoctorPatientGroupInfo a where  a.status = 1 and a.doctor = ?1 and a.patient = ?2 and a.group = ?3")
	long countDoctorPatientGroup(String doctor, String patient, String group);
	@Query("select count(*) from DoctorPatientGroupInfo a where  a.status = 1 and a.doctor = ?1 and a.patient = ?2 and a.group = ?3 and a.signType = ?4")
	long countDoctorPatientGroupType(String doctor, String patient, String group, String type);
	@Modifying
	@Query("update DoctorPatientGroupInfo set status = ?4 where doctor = ?1 and patient = ?2 and group = ?3 and status = 1")
	int updateDoctorPatientGroup(String doctor, String patient, String group, int status);
	@Query("select a from DoctorPatientGroupInfo a where  a.status = 1 and a.doctor = ?2 and a.patient = ?1 and a.signType =2")
	List<DoctorPatientGroupInfo> findByPatientAndDoctor(String patient, String oldDoctorCode);
	List<DoctorPatientGroupInfo> findByGroupAndStatus(String group, Integer status);
	@Query("select a from DoctorPatientGroupInfo a where a.id between ?1 and ?2 and a.status = 1")
	Page<DoctorPatientGroupInfo> findByIdRange(Long start, Long end, Pageable pageRequest);
}

+ 29 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorTeamDao.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.team.DoctorTeam;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface DoctorTeamDao extends
PagingAndSortingRepository<DoctorTeam, Long>,
JpaSpecificationExecutor<DoctorTeam> {
	DoctorTeam findByCode(String code);
	//@Query("select dt from DoctorTeam dt,DoctorTeamMember dtm  where dt.code=dtm.team and dt.del=1 and dtm.del=1 and dtm.memberCode= ?1 and dtm.type= 5 and dtm.signType='2'")
	@Query("select dtt from DoctorTeam dtt where dtt.id = (select max(dt.id) from DoctorTeam dt,DoctorTeamMember dtm  where dt.code=dtm.team and dt.del=1 and dtm.del=1 and dtm.memberCode= ?1 and dtm.type= 5 and dtm.signType='2')")
	DoctorTeam findByParientCode(String parientCode);
	@Query("select dt from DoctorTeam dt,DoctorTeamMember dtm  where dt.code=dtm.team and dt.del=1 and dtm.del=1 and dtm.memberCode= ?1 and dtm.type= 5 and dtm.signType='1'")
	DoctorTeam findBySanshiParientCode(String parientCode);
	//@Query("select dt from DoctorTeam dt,DoctorTeamMember dtm  where dt.code=dtm.team and dt.del=1 and dtm.del=1 and dtm.memberCode= ?1 and dtm.type= 5 and dtm.signType=?2 order by dtm.id limit 1")
	@Query("select dtt from DoctorTeam dtt where dtt.id = (select max(dt.id) from DoctorTeam dt,DoctorTeamMember dtm  where dt.code=dtm.team and dt.del=1 and dtm.del=1 and dtm.memberCode= ?1 and dtm.type= 5 and dtm.signType=?2)")
	DoctorTeam findByParientCodeAndSignType(String parientCode, String type);
	@Modifying
	@Query("update DoctorTeam a set a.del =0  where a.code = ?1 and signType='2'")
	void deleteTeam(String teamCode);
}

+ 60 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorTeamMemberDao.java

@ -0,0 +1,60 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.team.DoctorTeamMember;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * Created by Administrator on 2016/7/30.
 */
public interface DoctorTeamMemberDao extends PagingAndSortingRepository<DoctorTeamMember, Long>, JpaSpecificationExecutor<DoctorTeamMember> {
    @Query(" FROM DoctorTeamMember a WHERE a.team=?1 and a.type=?2 and a.del='1'")
    DoctorTeamMember findDoctor2ByTeam(String code, int type);
    @Query(" FROM DoctorTeamMember a WHERE a.team=?1 and a.type=?2 and a.del='1'and signType='1'")
    DoctorTeamMember findDoctorSanshi2ByTeam(String code, int type);
    @Query(" FROM DoctorTeamMember a WHERE a.team=?1 and a.type=?2 and a.del='1'and signType='2'")
    DoctorTeamMember findDoctorJiating2ByTeam(String code, int type);
    @Query(" FROM DoctorTeamMember a WHERE a.team=?1 and a.memberCode=?2 and a.del='1'")
    DoctorTeamMember findMemberCodeAndTeam(String code, String doctor);
    @Modifying
    @Query("update DoctorTeamMember a set a.del = '0' where a.team = ?1 and a.type=1 ")
    void updateType1Del(String code);
    @Modifying
    @Query("update DoctorTeamMember a set a.del = '0' where a.team = ?1 and signType='2' ")
    void deleteMember(String code);
    @Query("select count(a) FROM DoctorTeamMember a WHERE a.memberCode =?1 and  a.del='1'")
    Integer teamListByDoctorCode(String doctorCode);
    @Query(" FROM DoctorTeamMember a WHERE a.team =?1 and  a.del='1' and  a.signType='1'")
    List<DoctorTeamMember> findBySanshiTeam(String teamCode);
    @Query(" FROM DoctorTeamMember a WHERE a.team =?1 and  a.del='1' and  a.signType='1' and  a.type=?2 ")
    DoctorTeamMember findSanshiByTeamAndType(String teamCode, int i);
    List<DoctorTeamMember> findByTeamAndDel(String team, String del);
    @Query(" FROM DoctorTeamMember a WHERE a.team =?1 and  a.del='1' and  a.signType='2' and  a.memberCode=?2 ")
    DoctorTeamMember findMemberByTeamAndCode(String teamCode, String oldDoctorCode);
    /**
     * 判断医生是否为三师签团队的成员。
     *
     * @param doctorCode
     * @return
     */
    @Query("SELECT case when count(a) > 0 THEN true else false END FROM DoctorTeamMember a WHERE a.signType = 1 AND a" +
            ".memberCode = :memberCode")
    Boolean isSanShiSigning(@Param("memberCode") String doctorCode);
}

+ 23 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkTimeDao.java

@ -0,0 +1,23 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkTime;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by lyr on 2016/08/19.
 */
public interface DoctorWorkTimeDao extends PagingAndSortingRepository<WlyyDoctorWorkTime, Long>, JpaSpecificationExecutor<WlyyDoctorWorkTime> {
    /**
     * 查询医生工作时间
     *
     * @param doctor
     * @return
     */
    @Query("select a from WlyyDoctorWorkTime a where a.doctor = ?1")
    WlyyDoctorWorkTime findDoctorWorkTime(String doctor);
}

+ 40 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkWeekDao.java

@ -0,0 +1,40 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkWeek;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr on 2016/08/19.
 */
public interface DoctorWorkWeekDao extends PagingAndSortingRepository<WlyyDoctorWorkWeek, Long>, JpaSpecificationExecutor<WlyyDoctorWorkWeek> {
    /**
     * 查询医生排班列表
     *
     * @param doctor
     * @return
     */
    @Query("select a from WlyyDoctorWorkWeek a where a.doctor = ?1")
    List<WlyyDoctorWorkWeek> findDoctorWorkWeeks(String doctor);
    /**
     * 查询医生某天排班信息
     *
     * @param doctor
     * @param week
     * @return
     */
    @Query("select a from WlyyDoctorWorkWeek a where a.doctor = ?1 and a.week = ?2")
    WlyyDoctorWorkWeek findDoctorWorkWeek(String doctor, String week);
    /**
     * 删除医生的排班信息
     *
     * @param doctor
     */
    void deleteByDoctor(String doctor);
}

+ 25 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/HospitalDao.java

@ -0,0 +1,25 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface HospitalDao extends PagingAndSortingRepository<Hospital, Long>,JpaSpecificationExecutor<Hospital>  {
	@Query("select p from Hospital p where p.del = 1 and p.level =2 and p.centerSite='00' and length(p.code) = 10 ")
	List<Hospital> findHospital2();
	@Query("select p from Hospital p where p.del = 1 and p.level =2 and p.centerSite='00' and length(p.code) = 10  ")
	List<Hospital> findHospitalzxFWZ();
}

+ 17 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/JobConfigDao.java

@ -0,0 +1,17 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface JobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>,JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" from QuartzJobConfig p where p.status=?1 and p.del='1'")
    List<QuartzJobConfig> findByStatus(String s);
}

+ 50 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/MessageDao.java

@ -0,0 +1,50 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface MessageDao extends PagingAndSortingRepository<Message, Long>, JpaSpecificationExecutor<Message> {
    @Query("select count(a) from Message a where a.type =1 and a.read= 1 and a.receiver=?1 ")
    int amountUnreadByReceiver(String doctor);
    @Query("select count(a) from Message a where a.read = 1  and a.receiver=?1 and a.type=3 ")
    int amountUnreadSystemByReceiver(String doctor);
    @Query("select a from Message a where a.type =1 and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    Page<Message> amountUnreadLastByReceiver(String doctor, Pageable pageRequest);
    @Query("select count(a) from Message a where a.type =2 and a.read= 1 and a.receiver=?1 ")
    int amountUnreadHealthByReceiver(String doctor);
    @Query("select a from Message a where (a.type =2 ) and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    Page<Message> amountUnreadHealthLastByReceiver(String doctor, Pageable pageRequest);
    @Modifying
    @Query("update Message a set a.read = 0,a.over='0' where a.id = ?1")
    int read(long msgid);
    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 and a.signStatus = ?3 and read=1")
    Message findByParams(String sender, String receiver, String signStatus);
    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 and a.signStatus = ?3 ")
    Message findAllByParams(String sender, String receiver, String signStatus);
    @Query(" from Message a where a.read = 1 and over ='1' and a.sender = ?1 and a.receiver=?2 and a.signStatus='1'")
    Message findByPatient(String patient, String doctor);
    @Query("select count(a) from Message a where a.read = 0 and over ='0'  and a.receiver=?1 and a.type=?2 ")
    int findMessageNum(String doctor, Integer type);
}

+ 56 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientDao.java

@ -0,0 +1,56 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.patient.Patient;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientDao extends PagingAndSortingRepository<Patient, Long> {
	// 查询患者姓名
	@Query("select p.name from Patient p where p.code=?1 and p.status=1")
	String findNameByCode(String code);
	// 根據患者標識查詢患者信息
	@Query("select p from Patient p where p.code=?1 and p.status=1")
	Patient findByCode(String code);
	// 根據身份證號查詢患者信息
	@Query("select p from Patient p where p.idcard=?1 and p.status=1")
	Patient findByIdcard(String idcard);
	
	@Query("select p from Patient p where p.ssc=?1 and p.status=1")
	Patient findBySsc(String ssc);
	// 根據手机号查詢患者信息
	@Query("select p from Patient p where p.mobile=?1 and p.status=1")
	Patient findByMobile(String mobile);
	// 根據病情等级获取患者信息
	@Query("select p from Patient p where p.diseaseCondition=?1 and p.status=1")
	Iterable<Patient> findInfoByLevel(int level);
	@Query("select p from Patient p where p.openid=?1 and p.status=1")
	Patient findByOpenid(String openid);
	
	@Query("select count(1) from Patient p where p.openid=?1 and p.status=1")
	int countByOpenid(String openid);
	
	//清空openid
	@Modifying
	@Query("update Patient p set p.openid = null where p.code <> ?1 and p.openid = ?2 and p.status=1")
	int clearOpenid(String patient, String openid);
	@Query(" select p from Patient p,SignFamily s where p.code=s.patient and s.status > 0 ")
	List<Patient> findAllSignPatient();
	@Query(" select p from Patient p where password is null or password = ''  ")
	List<Patient> findAllIdCardPatientAndNoPassword();
}

+ 59 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientDiseaseDao.java

@ -0,0 +1,59 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.patient.PatientDisease;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 患者疾病Dao
 *
 * Created by lyr on 2016/09/09.
 */
public interface PatientDiseaseDao extends PagingAndSortingRepository<PatientDisease, Long>, JpaSpecificationExecutor<PatientDisease> {
    /**
     * 根据居民code获取居民疾病
     *
     * @param patient
     * @return
     */
    List<PatientDisease> findByPatient(String patient);
    /**
     * 根据居民code获取居民疾病
     *
     * @param patient
     * @return
     */
    List<PatientDisease> findByPatientAndSignType(String patient, String signType);
    /**
     * 根据居民code获取居民疾病
     *
     * @param patient
     * @return
     */
    @Query("select a from PatientDisease a where a.patient = ?1 and a.signType = '1' and a.del ='1' ")
    List<PatientDisease> findByPatientSsDisease(String patient);
    /**
     * 删除患者疾病
     *
     * @param patient
     * @return
     */
    int deleteByPatient(String patient);
    @Modifying
    @Query("update PatientDisease set del = '0' where patient = ?1 and del = '1' and signType = '2' ")
    int updateDiseaseDel(String patient);
    @Query("select a from PatientDisease a where a.del = '1' and a.id >= ?1")
    Page<PatientDisease> findByIdRange(Long start, Pageable pageRequest);
}

+ 54 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/PatientHealthGuidanceDao.java

@ -0,0 +1,54 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface PatientHealthGuidanceDao extends PagingAndSortingRepository<PatientHealthGuidance, Long>, JpaSpecificationExecutor<PatientHealthGuidance> {
	@Query("select b.name, b.photo, a.id, a.content, a.czrq,b.level from PatientHealthGuidance a, Doctor b where a.patient = ?1 and a.doctor = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByPatient(String patient, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq,b.level from PatientHealthGuidance a, Doctor b where a.patient = ?1 and a.doctor = b.code and a.id < ?2 and a.del = '1' order by a.id desc")
	Page<Object> findByPatient(String patient, long id, Pageable pageRequest);
	
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, Pageable pageRequest);
	
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.id < ?2 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, long id, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.patient = ?2 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, String patient, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.patient = ?2 and a.patient = b.code and a.id < ?3 and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, String patient, long id, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.czrq between ?2 and ?3 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, Date begin, Date end, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.czrq between ?2 and ?3 and a.id < ?4 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, Date begin, Date end, long id, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.patient = ?2 and a.czrq between ?3 and ?4 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, String patient, Date begin, Date end, Pageable pageRequest);
	@Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, Patient b where a.doctor = ?1 and a.patient = ?2 and a.czrq between ?3 and ?4 and a.id < ?5 and a.patient = b.code and a.del = '1' order by a.id desc")
	Page<Object> findByDoctor(String doctor, String patient, Date begin, Date end, long id, Pageable pageRequest);
	//查找昨天的健康指导
	@Query("SELECT a FROM PatientHealthGuidance a WHERE unix_timestamp(a.czrq)>=unix_timestamp(?1) and unix_timestamp(a.czrq)<unix_timestamp(?2) ")
	List<PatientHealthGuidance> findByCzrqyYesterday(String yesterday, String now);
}

+ 27 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java

@ -0,0 +1,27 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/17.
 */
public interface QuartzJobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>, JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.status=?2 and a.del='1'")
    QuartzJobConfig findById(String code, String status);
    @Query(" FROM QuartzJobConfig a WHERE a.status=?1 and a.del='1'")
    List<QuartzJobConfig> findByAll(String s);
    @Query(" FROM QuartzJobConfig a WHERE  a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")
    QuartzJobConfig findById(String id);
}

+ 11 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobLogDao.java

@ -0,0 +1,11 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuartzJobLogDao extends PagingAndSortingRepository<QuartzJobLog, String>, JpaSpecificationExecutor<QuartzJobLog> {
}

+ 11 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/QuotaDao.java

@ -0,0 +1,11 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.job.WlyyQuota;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuotaDao extends PagingAndSortingRepository<WlyyQuota, String>, JpaSpecificationExecutor<WlyyQuota> {
}

+ 47 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignFamilyDao.java

@ -0,0 +1,47 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Long>, JpaSpecificationExecutor<SignFamily> {
	@Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
	SignFamily findByIdcard(String idcard);
	@Query(" from SignFamily a where  a.type =1 and a.czrq= ?1  ")
	List<SignFamily> findByDate(String s);
	@Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
	SignFamily findByPatientAndType(String patient,int type);
	//查找昨天的家庭签约数据
	@Query(" from SignFamily a where  a.type =2 and a.status = 1  and a.applyDate>= ?1 and a.applyDate< ?2 and a.expensesStatus=1 ")
	List<SignFamily> findByJiatingSignYesterdayExpensesStatus(String yesterday, String today);
	//查找昨天的家庭签约数据
	@Query(" from SignFamily a where  a.type =2 and a.status >= 1  and  a.applyDate<=?1 and a.expensesStatus=1 ")
	List<SignFamily> findByJiatingSignYesterdayExpensesStatus(String yesterday);
	//查找昨天的家庭签约数据
	@Query(" from SignFamily a where  a.type =2 and a.status >= 1  and  a.applyDate<=?1 ")
	List<SignFamily> findByJiatingSignYesterday(String yesterday);
	//查找昨天的家庭解约数据
	@Query(" from SignFamily a where  a.type =2 and a.status in (-3,-4) and a.applyUnsignDate>=?1 and a.applyUnsignDate<?2 and a.expensesStatus=1")
	List<SignFamily> findByJiatingUnSignYesterdayExpensesStatus(String yesterday, String today);
	//查找昨天的家庭待数据
	@Query(" from SignFamily a where  a.type =2 and a.status =0  and a.patientApplyDate>=?1 and a.patientApplyDate<?2")
	List<SignFamily> findByJiatingWaitSignYesterdayExpensesStatus(String yesterday, String today);
	//查找昨天的家庭待改签
	@Query(" from SignFamily a where  a.type =2 and a.status =100  and a.patientApplyDate>=?1 and a.patientApplyDate<?2 and a.expensesStatus=1 ")
	List<SignFamily> findByJiatingChaangeSignYesterdayExpensesStatus(String yesterday, String now);
	// 查询同步数据
	@Query("select a from SignFamily a where a.id between ?3 and ?4 and a.type = ?1 and a.signSource = ?2 and a.status > 0 order by a.id")
	Page<SignFamily> findByTypeAndSignSourceAndId(Integer type,String signSource,Long start,Long end,Pageable pageable);
}

+ 55 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignPatientLabelDao.java

@ -0,0 +1,55 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.label.SignPatientLabel;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr on 2016/10/9.
 */
public interface SignPatientLabelDao extends
        PagingAndSortingRepository<SignPatientLabel, Long>,
        JpaSpecificationExecutor<SignPatientLabel> {
    /**
     * 根据标签code、标签类型、状态查询标签
     *
     * @param labelCode 标签code
     * @param labelType 标签类型
     * @param status 状态
     * @return
     */
    SignPatientLabel findByLabelCodeAndLabelTypeAndStatus(String labelCode, String labelType, Integer status);
    /**
     * 查询某个类型系统标签
     *
     * @param labelType
     * @param status
     * @return
     */
    List<SignPatientLabel> findByLabelTypeAndStatus(String labelType, Integer status);
    /**
     * 查询非自定义系统标签
     *
     * @return
     */
    @Query("select a from SignPatientLabel a where a.status = 1 and a.isSystem = 1 and a.labelType < 4")
    List<SignPatientLabel> findSystemLabels();
    /**
     * 查询某个团队自定义标签
     *
     * @param teamCode
     * @return
     */
    @Query("select a from SignPatientLabel a where a.status = 1 and (a.isSystem = 1  or a.teamCode = ?1) and a.labelType = 4")
    List<SignPatientLabel> findCustomLabels(long teamCode);
    @Query("select a from SignPatientLabel a where a.status = 1 and a.labelName = ?1 and a.labelType = ?2 and a.teamCode = ?3")
    SignPatientLabel findByLabelNameAndLabelTypeAndTeamCode(String labelName, String labelType, Long teamCode);
}

+ 68 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/SignPatientLabelInfoDao.java

@ -0,0 +1,68 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr on 2016/10/9.
 */
public interface SignPatientLabelInfoDao extends
        PagingAndSortingRepository<SignPatientLabelInfo, Long>,
        JpaSpecificationExecutor<SignPatientLabelInfo> {
    /**
     * 查询某个患者的标签
     *
     * @param patient 患者
     * @param status  状态
     * @return
     */
    List<SignPatientLabelInfo> findByPatientAndStatus(String patient, Integer status);
    /**
     * 查询某个患者的某个类型标签
     *
     * @param patient   患者
     * @param labelType 标签类型
     * @param status    状态
     * @return
     */
    List<SignPatientLabelInfo> findByPatientAndLabelTypeAndStatus(String patient, String labelType, Integer status);
    /**
     * 查询某个患者的某个类型的某个标签
     *
     * @param patient   患者
     * @param labelCode  标签代码
     * @param labelType 标签类型
     * @param status    状态
     * @return
     */
    SignPatientLabelInfo findByPatientAndLabelAndLabelTypeAndStatus(String patient, String labelCode, String labelType, Integer status);
    /**
     * 删除患者的某个标签类型的所有指定状态标签
     *
     * @param patient
     * @param labelType
     * @param status
     * @return
     */
    int deleteByPatientAndLabelTypeAndStatus(String patient, String labelType, Integer status);
    /**
     * 更新某个标签名称
     *
     * @param labelName
     * @param labelCode
     * @return
     */
    @Query("update SignPatientLabelInfo a set a.labelName = ?1 where a.label= ?2 and a.labelType = '4' ")
    int updateLabelName(String labelName, String labelCode);
    List<SignPatientLabelInfo> findByLabelTypeAndStatus(String s, int i);
}

+ 24 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/TownDao.java

@ -0,0 +1,24 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.system.Town;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface TownDao extends PagingAndSortingRepository<Town, Long> {
	// 根據CODE查詢區縣名稱
	@Query("select p from Town p where p.code = ?1")
	Town findByCode(String code);
	@Query("select a from Town a where a.city = ?1 order by id")
	Iterable<Town> findByCity(String province);
	@Query("select a from Town a where a.city = ?1 order by id")
	List<Town> findByCityCode(String province);
}

+ 17 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/WlyyDimensionQuotaDao.java

@ -0,0 +1,17 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by chenweida on 2017/7/10.
 */
public interface WlyyDimensionQuotaDao extends PagingAndSortingRepository<WlyyDimensionQuota, Long>, JpaSpecificationExecutor< WlyyDimensionQuota> {
    @Query("from WlyyDimensionQuota w where w.quotaCode=?1 order by sort asc")
    List<WlyyDimensionQuota> findDimensionQuotasByQuotaCode(String id);
}

+ 24 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/dao/WlyyQuotaResultDao.java

@ -0,0 +1,24 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface WlyyQuotaResultDao extends PagingAndSortingRepository<WlyyQuotaResult, String>, JpaSpecificationExecutor<WlyyQuotaResult> {
    @Query(" FROM WlyyQuotaResult a WHERE a.quotaDate =?1 and a.quatoCode=?2")
    List<WlyyQuotaResult> findByYesterday(String yesterday, String quatoCode);
    @Modifying
    @Query(" delete FROM WlyyQuotaResult a WHERE a.quotaDate =?1 and a.quatoCode=?2")
    void deleteByDateAndCode(String yesterday, String quatoCode);
    @Query(" FROM WlyyQuotaResult a WHERE a.level1Type =?1 and a.qkdoctorJobName != ?2 and a.quatoCode=1")
    List<WlyyQuotaResult> findByLevel1TypeAndQkdoctorJobName(String level1Type, String qkdoctorJobName);
}

+ 63 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/data/DataHandingService.java

@ -0,0 +1,63 @@
package com.yihu.wlyy.statistics.data;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.PatientDao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2016.10.17.
 */
@Service
public class DataHandingService {
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private DoctorDao doctorDao;
    @Transactional
    public String producePatientAndDoctorPassword() {
        int patientCount=0;
        int patientErrorCount=0;
        int doctorCount=0;
        int doctorErrorCount=0;
        List<Patient> patients= patientDao.findAllIdCardPatientAndNoPassword();
        for (Patient patient:patients){
            String idcard=patient.getIdcard();
            if(!StringUtils.isEmpty(patient.getPassword())||StringUtils.isEmpty(idcard)||(idcard.length()!=15&&idcard.length()!=18)){
                patientErrorCount++;
                continue;
            }
            String password=idcard.substring(idcard.length()-6);
            String salt= UUID.randomUUID().toString().replace("-","");
            patient.setSalt(salt);
            patient.setPassword(MD5.GetMD5Code(password+salt));
            patientCount++;
        }
        patientDao.save(patients);
        List<Doctor> doctors= doctorDao.findAllNoPasswordDoctors();
        for (Doctor doctor:doctors){
            String phone= doctor.getMobile();
            if(!StringUtils.isEmpty(doctor.getPassword())||StringUtils.isEmpty(phone)||phone.length()!=11){
                doctorErrorCount++;
                continue;
            }
            String password=phone.substring(5);
            String salt= UUID.randomUUID().toString().replace("-","");
            doctor.setSalt(salt);
            doctor.setPassword(MD5.GetMD5Code(password+salt));
            doctorCount++;
        }
        doctorDao.save(doctors);
        return "更新患者(默认身份证后六位):"+patientCount+",有身份证异常的患者:"+patientErrorCount+",更新医生(默认电话后六位):"+doctorCount+",有电话号码异常的医生:"+doctorErrorCount;
    }
}

+ 34 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/data/DataHandlingController.java

@ -0,0 +1,34 @@
package com.yihu.wlyy.statistics.data;
import com.yihu.wlyy.statistics.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * Created by Administrator on 2016.10.08.
 * 修改历史数据处理控制器
 */
@Controller
@RequestMapping(value = "/dataHandling", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DataHandlingController extends BaseController {
    @Autowired
    private DataHandingService dataHandingService;
    /**
     * 生成医生和患者表中有身份的用户的密码
     * @return
     */
    @RequestMapping(value = "/producePatientAndDoctorPassword")
    @ResponseBody
    public String producePatientAndDoctorPasswor() {
        try {
            return write(200, dataHandingService.producePatientAndDoctorPassword());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
}

+ 28 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/cache/Cache.java

@ -0,0 +1,28 @@
package com.yihu.wlyy.statistics.etl.cache;
import com.yihu.wlyy.statistics.vo.DataModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2017/7/11.
 */
public class Cache {
    private static Map<String, List<DataModel>> cache = new HashMap<>();
    public static void addCache(String key, List<DataModel> data) {
        cache.put(key, data);
    }
    public static List<DataModel> getCache(String key) {
        return cache.get(key);
    }
    public static void cleanCache(){
        cache.clear();
    }
}

+ 189 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/compute/ComputeHelper.java

@ -0,0 +1,189 @@
package com.yihu.wlyy.statistics.etl.compute;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.WlyyDimensionQuotaDao;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.Contant;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.text.DecimalFormat;
import java.util.*;
/**
 * Created by chenweida on 2017/6/1.
 */
@Component
@Scope("prototype")
public class ComputeHelper {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * @param dataModels      过滤之后的数据
     * @param dimensionQuotas 指标的维度
     * @param wlyyJobConfigVO
     * @param endTime
     * @return
     */
    public List<SaveModel> compute(List<DataModel> dataModels, List<WlyyDimensionQuota> dimensionQuotas, WlyyJobConfigVO wlyyJobConfigVO, String endTime, String timeLevel) {
        try {
            //得到全部团队
            List<AdminTeam> teams = findAllTeam();
            //计算数据 返回map key 根据团队和维度拼凑在map中的key   1-2-1  如果维度是长度是0返回团队id 1
            Map<String,  List<DataModel>> computeMap = computeDataModel(dimensionQuotas, dataModels);
            //初始化map并且设置统计出来的数目
            List<SaveModel> savemodels = initAndSetResult(teams, dimensionQuotas, computeMap, wlyyJobConfigVO, endTime,timeLevel);
            return savemodels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * //计算数据 返回map
     *
     * @param dataModels      过滤过后的元数据
     * @param dimensionQuotas 该指标的维度
     * @return
     */
    private Map<String,  List<DataModel>> computeDataModel( List<WlyyDimensionQuota> dimensionQuotas, List<DataModel> dataModels) {
        Map<String,  List<DataModel>> returnMap = new HashMap<>();
        dataModels.stream().forEach(one -> {
            String key = getKey(one, dimensionQuotas.size());
            List<DataModel> sms=new ArrayList<DataModel>();
            if (returnMap.containsKey(key)) {
                sms=returnMap.get(key);
            }
            sms.add(one);
        });
        return returnMap;
    }
    /**
     * 获取key  根据团队和维度拼凑在map中的key   1-2-1  如果维度是长度是0返回团队id 1
     *
     * @param one
     * @param size
     * @return
     */
    private String getKey(DataModel one, int size) {
        try {
            if (size > 0) {
                StringBuffer str = new StringBuffer(one.getTeam());
                for (int i = 1; i <= size; i++) {
                    String invokeKey = (String) DataModel.class.getMethod("getSlaveKey" + i).invoke(one);
                    str.append("-" + invokeKey);
                }
                return str.toString();
            } else {
                return one.getTeam();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 得到全部团队
     *
     * @return
     */
    private List<AdminTeam> findAllTeam() {
        String sql = "SELECT " +
                "  wat.id id, " +
                "  wat.name name, " +
                "  h.`code` org_code, " +
                "  h.`name` org_name, " +
                "  h.town   town_code, " +
                "  h.town_name  town_name " +
                "FROM " +
                "  dm_hospital h, " +
                "  wlyy_admin_team wat " +
                "WHERE " +
                "  h.`code` = wat.org_code " +
                "AND wat.available = 1";
        List<AdminTeam> adminTeams = jdbcTemplate.query(sql, new BeanPropertyRowMapper(AdminTeam.class));
        return adminTeams;
    }
    /**
     * 初始化map
     */
    private List<SaveModel> initAndSetResult(List<AdminTeam> teams, List<WlyyDimensionQuota> dimensionQuotas, Map<String,  List<DataModel>> countMap,  WlyyJobConfigVO wlyyJobConfigVO, String endTime,String timeLevel) throws Exception {
        List<SaveModel> returnList = new ArrayList<>();
        Map<String, SaveModel> lastMaps = new HashMap<>();
        //初始化团队的数据
        for (int i = 0; i < teams.size(); i++) {
            AdminTeam one = teams.get(i);
            SaveModel saveModel = new SaveModel();
            saveModel.setCity("350200");
            saveModel.setCityName("厦门市");
            saveModel.setTown(one.getTownCode());
            saveModel.setTownName(one.getTownName());
            saveModel.setHospital(one.getOrgCode());
            saveModel.setHospitalName(one.getOrgName());
            saveModel.setTeam(one.getId().toString());
            saveModel.setTeamName(one.getName());
            saveModel.setQuotaCode(wlyyJobConfigVO.getId());
            saveModel.setCreateTime(new Date());
            saveModel.setTimeLevel(timeLevel);
            saveModel.setAreaLevel("5");//团队
            saveModel.setQuotaDate(DateUtil.strToDate(endTime,"yyyy-MM-dd"));
            lastMaps.put(one.getId().toString(), saveModel);
        }
        //根据维度初始化数据
        for (int i = 0; i < dimensionQuotas.size(); i++) {
            Map<String, SaveModel> mapTemp = new HashMap<>();
            WlyyDimensionQuota dimensionQuota = dimensionQuotas.get(i);
            List<DictModel> dictModels = jdbcTemplate.query(dimensionQuota.getDictSql(), new BeanPropertyRowMapper(DictModel.class));
            for (Map.Entry<String, SaveModel> oneSaveModel : lastMaps.entrySet()) {
                for (int j = 0; j < dictModels.size(); j++) {
                    SaveModel saveModelTemp = new SaveModel();
                    DictModel dictModel = dictModels.get(j);
                    BeanUtils.copyProperties(oneSaveModel.getValue(), saveModelTemp);
                    SaveModel.class.getMethod("setSlaveKey" + (i + 1) + "Name",String.class).invoke(saveModelTemp, dictModel.getName());
                    SaveModel.class.getMethod("setSlaveKey" + (i + 1),String.class).invoke(saveModelTemp, dictModel.getCode());
                    //根据维度生成新的key
                    StringBuffer strKey = new StringBuffer(oneSaveModel.getKey() + "-" + dictModel.getCode());
                    mapTemp.put(strKey.toString(), saveModelTemp);
                }
            }
            lastMaps = mapTemp;
        }
        //设置值
        for (Map.Entry<String, SaveModel> one : lastMaps.entrySet()) {
            if (countMap.containsKey(one.getKey())) {
                List<DataModel> dataModels=countMap.get(one.getKey());
                Integer result1=0;
                Integer result2=0;
                for(int j=0;j<dataModels.size();j++){
                    DataModel dataModel=dataModels.get(j);
                    result1+=dataModel.getNum();
                    result2++;
                }
                one.getValue().setResult1(result1);
                one.getValue().setResult2(result2);
            }
            returnList.add(one.getValue());
        }
        return returnList;
    }
}

+ 15 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/Convert.java

@ -0,0 +1,15 @@
package com.yihu.wlyy.statistics.etl.convert;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 */
public interface Convert {
    public List<DataModel> convert(List<DataModel> oneList, String slaveLevel, WlyyDimensionQuota temp );
}

+ 48 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/ConvertHelper.java

@ -0,0 +1,48 @@
package com.yihu.wlyy.statistics.etl.convert;
import com.yihu.wlyy.statistics.dao.WlyyDimensionQuotaDao;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.FilterModel;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/5.
 * 维度的key值转换器
 */
@Component
@Scope("prototype")
public class ConvertHelper {
    @Autowired
    private WlyyDimensionQuotaDao wlyyDimensionQuotaDao;
    /**
     * 把每个维度的key清洗到对应的slaveKey中
     * @param filterModel  过滤之后的model
     * @param dimensionQuotas 维度的列表
     * @return
     * @throws Exception
     */
    public FilterModel convert(FilterModel filterModel, List<WlyyDimensionQuota> dimensionQuotas) throws Exception {
        for (int i = 0; i < dimensionQuotas.size(); i++) {
            WlyyDimensionQuota temp = dimensionQuotas.get(i);
            String clazz = temp.getConvertClazz();
            if (!StringUtils.isEmpty(clazz)) {
                //反射出对象并且调用convert方法去转换对应的slavekey
                Object obj = Class.forName(clazz).newInstance();
                Method method = obj.getClass().getMethod("convert", List.class,String.class,WlyyDimensionQuota.class);
                method.invoke(obj, filterModel.getData(), String.valueOf(i + 1),temp);
            }
        }
        return filterModel;
    }
}

+ 51 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/AgeConvert.java

@ -0,0 +1,51 @@
package com.yihu.wlyy.statistics.etl.convert.wlyy;
import com.yihu.wlyy.statistics.etl.convert.Convert;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.util.Contant;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 */
public class AgeConvert implements Convert {
    /**
     * @param oneList    数据
     * @param slaveLevel 从1开始
     * @return
     */
    public List<DataModel> convert(List oneList, String slaveLevel, WlyyDimensionQuota temp ) {
        oneList.stream().forEach(one -> {
            try {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                Integer age= IdCardUtil.getAgeForIdcard(String.valueOf(value));
                String key = getAgeCode(age);
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, key);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return oneList;
    }
    public String getAgeCode(Integer age) {
        if (age <= 6) {
            return Contant.convert.level_age_1;
        } else if (age >= 7 && age <= 18) {
            return Contant.convert.level_age_2;
        } else if (age >= 19 && age <= 30) {
            return Contant.convert.level_age_3;
        } else if (age >= 31 && age <= 50) {
            return Contant.convert.level_age_4;
        } else if (age >= 51 && age <= 65) {
            return Contant.convert.level_age_5;
        } else {
            return Contant.convert.level_age_6;
        }
    }
}

+ 34 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/ConsultTimeConvert.java

@ -0,0 +1,34 @@
package com.yihu.wlyy.statistics.etl.convert.wlyy;
import com.yihu.wlyy.statistics.etl.convert.Convert;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 */
public class ConsultTimeConvert implements Convert {
    /**
     * @param oneList    数据
     * @param slaveLevel 从1开始
     * @return
     */
    public List<DataModel> convert(List oneList, String slaveLevel, WlyyDimensionQuota temp ) {
        oneList.stream().forEach(one -> {
            try {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                String sex= IdCardUtil.getSexForIdcard(String.valueOf(value));
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, sex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return oneList;
    }
}

+ 36 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/SexConvert.java

@ -0,0 +1,36 @@
package com.yihu.wlyy.statistics.etl.convert.wlyy;
import com.yihu.wlyy.statistics.etl.convert.Convert;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.util.Contant;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 */
public class SexConvert implements Convert {
    /**
     * @param oneList    数据
     * @param slaveLevel 从1开始
     * @return
     */
    public List<DataModel> convert(List oneList, String slaveLevel, WlyyDimensionQuota temp ) {
        oneList.stream().forEach(one -> {
            try {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                String sex= IdCardUtil.getSexForIdcard(String.valueOf(value));
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, sex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return oneList;
    }
}

+ 33 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/SimpleConvert.java

@ -0,0 +1,33 @@
package com.yihu.wlyy.statistics.etl.convert.wlyy;
import com.yihu.wlyy.statistics.etl.convert.Convert;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 */
public class SimpleConvert implements Convert {
    /**
     * @param oneList    数据
     * @param slaveLevel 从1开始
     * @return
     */
    public List<DataModel> convert(List oneList, String slaveLevel, WlyyDimensionQuota temp ) {
        oneList.stream().forEach(one -> {
            try {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, value.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return oneList;
    }
}

+ 84 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/ExtractHelper.java

@ -0,0 +1,84 @@
package com.yihu.wlyy.statistics.etl.extract;
import com.yihu.wlyy.statistics.etl.extract.db.DBExtract;
import com.yihu.wlyy.statistics.util.SpringUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/1.
 */
@Component
@Scope("prototype")
public class ExtractHelper {
    private String startTime;
    private String endTime;
    private Logger logger = LoggerFactory.getLogger(ExtractHelper.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${wlyy.im.databaseName}")
    private String imDatabaseName;
    /**
     * 公共的抽取数据
     *
     * @param wlyyJobConfigVO
     * @return
     * @throws Exception
     */
    public List<DataModel> extractData(WlyyJobConfigVO wlyyJobConfigVO, String startTime, String endTime, String year, String timeLevel) throws Exception {
        try {
            this.startTime = startTime;
            this.endTime = endTime;
            String timeSql = "";
            if ("1".equals(timeLevel)) {
                timeSql = wlyyJobConfigVO.getSqlDay();
            } else if ("2".equals(timeLevel)) {
                timeSql = wlyyJobConfigVO.getSqlYear();
            } else {
                timeSql = wlyyJobConfigVO.getSqlDay();
            }
            //设置时间
            String sql = initSql(wlyyJobConfigVO.getSql() + "  " + timeSql, startTime, endTime, year);
            String sqlCount = initSql(wlyyJobConfigVO.getSqlCount() + "  " + timeSql, startTime, endTime, year);
            logger.info(" sql: " + sql);
            logger.info(" sqlCount: " + sqlCount);
            //抽取数据
            return SpringUtil.getBean(DBExtract.class).extractByPage(
                    DataModel.class,
                    sql,
                    sqlCount,
                    true,
                    jdbcTemplate);
        } catch (Exception e) {
            logger.error("extract error:" + e.getMessage());
            logger.error("quotaVO str:" + wlyyJobConfigVO.toString());
        }
        return null;
    }
    public String initSql(String sql, String startTime, String endTime, String year) {
        return sql.replace("[startTime]", startTime).replace("[endTime]", endTime).replace("[year]", year).replace("[im]",imDatabaseName);
    }
}

+ 67 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/db/DBExtract.java

@ -0,0 +1,67 @@
package com.yihu.wlyy.statistics.etl.extract.db;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 数据库抽取
 */
@Component
@Scope("prototype")
public class DBExtract<T> {
    /**
     * 不分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<T> extract(Class<T> clazz,String sql,JdbcTemplate jdbcTemplate){
        List<T> returnList= jdbcTemplate.query(sql,new BeanPropertyRowMapper(clazz));
        return returnList;
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @param pageSize 每页显示多少 默认10000
     * @param isMultithreading 是否多线程抽取 默认否
     * @return
     */
    public List<T> extractByPage(Class<T> clazz,String sql,String countSql,int pageSize,Boolean isMultithreading,JdbcTemplate jdbcTemplate)throws  Exception{
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @param isMultithreading 是否多线程抽取 默认否
     * @return
     */
    public List<T> extractByPage(Class<T> clazz,String sql,String countSql,Boolean isMultithreading,JdbcTemplate jdbcTemplate)throws  Exception{
        if(StringUtils.isEmpty(countSql)){
            return extract(clazz,sql,jdbcTemplate);
        }
        int pageSize=10000;
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<Object> extractByPage(Class<T> clazz,String sql,JdbcTemplate jdbcTemplate)throws  Exception{
        int pageSize=10000;
        Boolean isMultithreading=false;
        String countSql="";
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
}

+ 155 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/extract/db/DBPageExtract.java

@ -0,0 +1,155 @@
package com.yihu.wlyy.statistics.etl.extract.db;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 分页抽取器
 */
@Component
@Scope("prototype")
public class DBPageExtract<T> {
    private  List<T> returnList=new ArrayList<T>();
    public synchronized void addData( List<T> dataList) {
         returnList.addAll(dataList);
    }
    public List<T> extractByPage(Class<T> clazz, String sql, String countSql, int pageSize, Boolean isMultithreading,JdbcTemplate jdbcTemplate) throws Exception{
        if(!StringUtils.isEmpty(countSql)){
            isMultithreading=true;
        }
        if(isMultithreading){
            if(StringUtils.isEmpty(countSql)){
                throw new Exception("countSql is null");
            }
            return MultiThreadExtract(clazz, sql,countSql, pageSize,jdbcTemplate);
        }else{
            return noMultiThreadExtract(clazz, sql, pageSize,jdbcTemplate);
        }
    }
    /**
     * 不用多线程抽取
     * @param clazz
     * @param sql
     * @param pageSize
     * @return
     */
    private List<T> noMultiThreadExtract(Class<T> clazz, String sql, int pageSize,JdbcTemplate jdbcTemplate) {
        List<T> returnList=new ArrayList<T>();
        int start=0;
        int page=1;
        while (true){
            String finalSql=sql+" limit "+start+","+pageSize; //拼凑分页的语句
            List<T> listTemp= jdbcTemplate.query(finalSql,new BeanPropertyRowMapper(clazz));
            returnList.addAll(listTemp);//添加到list里面
            //判断是都是最后页面
            if(listTemp.size()!=pageSize){
                listTemp.clear();
                break;
            }else{
                start =page*pageSize;
                page++;
                listTemp.clear();
            }
        }
        return returnList;
    }
    /**
     * 多线程抽取数据
     * @param clazz
     * @param sql
     * @param pageSize
     * @return
     */
    private   List<T> MultiThreadExtract(Class<T> clazz, String sql,String countSql, int pageSize,JdbcTemplate jdbcTemplate)  {
        try{
            //得到数据的总数
            Integer dataCount=getCount(countSql,jdbcTemplate);
            //根据count 计算出 总共要执行几次
            Integer forCount=getForCount(dataCount,pageSize);
            forCount++;
            //綫程返回值的值
            List<AsyncResult<Boolean>> asyncResultPool=new ArrayList<AsyncResult<Boolean>>();
            for(int page=0;page<forCount;page++){
                //启动多线程采集数据
                AsyncResult<Boolean> future= multiExtractData(sql,page*pageSize,pageSize,clazz,jdbcTemplate);
                asyncResultPool.add(future);
            }
            ///循环判断,等待获取结果信息
            while (true){
                //得到迭代器
                Iterator<AsyncResult<Boolean>> asyncResultIterator=asyncResultPool.iterator();
                //判断有没有下一个
                while (asyncResultIterator.hasNext()){
                    AsyncResult<Boolean> asyncResult= asyncResultIterator.next();
                    if(asyncResult.isDone()){
                        //如果做完了就移除迭代器
                        asyncResultIterator.remove();
                    }else{
                        Thread.sleep(500L);
                    }
                }
                //如果一直移除到没有下一个就跳出循环 说明数据已经采集完成
                if(!asyncResultIterator.hasNext()){
                    break;
                }
            }
            return returnList;
        }catch (Exception e){
            //如果多线程错误 就改用单线程
            return noMultiThreadExtract(clazz,sql,pageSize,jdbcTemplate);
        }
    }
    private Integer getForCount(Integer dataCount, int pageSize) {
        //根据所有的数据取余数
        int yushu=dataCount%pageSize;
        int page=dataCount/pageSize;
        if(yushu==0){
            //如果没有余数 返回总的页数
            return page;
        }else{
            //如果有余数 页数多加1
            page++;
            return page;
        }
    }
    private Integer getCount(String countSql,JdbcTemplate jdbcTemplate) {
        Integer countMap= jdbcTemplate.queryForObject(countSql,Integer.class);
        return countMap;
    }
    /**
     * 多线程采集数据
     * @param sql
     * @param start
     * @param pageSize
     * @param clazz
     * @return
     */
    @Async("dbExtractExecutor")
    private AsyncResult<Boolean> multiExtractData(String sql, int start, int pageSize, Class<T> clazz, JdbcTemplate jdbcTemplate) {
        String finalSql=sql+" limit "+start+","+pageSize; //拼凑分页的语句
        List<T> listTemp= jdbcTemplate.query(finalSql,new BeanPropertyRowMapper(clazz));
        addData(listTemp);
        return new AsyncResult<>(true);
    }
}

+ 47 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/filter/FilterHelper.java

@ -0,0 +1,47 @@
package com.yihu.wlyy.statistics.etl.filter;
import com.yihu.wlyy.statistics.vo.DataModel;
import com.yihu.wlyy.statistics.vo.ErrModel;
import com.yihu.wlyy.statistics.vo.FilterModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/6/1.
 */
@Component
@Scope("prototype")
public class FilterHelper {
    public FilterHelper() {
    }
    /**
     * 根据过滤规则过滤数据
     *
     * @param dataModels
     * @return
     */
    public FilterModel filter(List<DataModel> dataModels) {
        //成功的list
        List<DataModel> newList = new ArrayList<>();
        //失败的list
        List<ErrModel> errorList = new ArrayList<>();
        dataModels.stream().forEach(one -> {
            String returnStr=one.isNull();
            if (StringUtils.isEmpty(returnStr)) {
                dataModels.add(one);
            }else{
                //脏数据
                errorList.add(new ErrModel(one.getBusinessId(),returnStr));
            }
        });
        return new FilterModel(newList, errorList);
    }
}

+ 34 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/filter/filter/NotNullFilter.java

@ -0,0 +1,34 @@
package com.yihu.wlyy.statistics.etl.filter.filter;
import com.yihu.wlyy.statistics.vo.FilterModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/6/1.
 */
@Component
@Scope("prototype")
public class NotNullFilter {
    private Logger logger = LoggerFactory.getLogger(NotNullFilter.class);
    /**
     * 不判断主维度的数据是否为空,只判断从维度额的数据是否为空
     *
     * @param filterModel
     * @return
     */
    public FilterModel filter(FilterModel filterModel) {
        try {
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }
}

+ 25 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/SaveHelper.java

@ -0,0 +1,25 @@
package com.yihu.wlyy.statistics.etl.save;
import com.yihu.wlyy.statistics.etl.save.es.ElastricSearchSave;
import com.yihu.wlyy.statistics.util.SpringUtil;
import com.yihu.wlyy.statistics.vo.SaveModel;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class SaveHelper {
    public Boolean save(List<SaveModel> sms) {
        return SpringUtil.getBean(ElastricSearchSave.class).save(sms);
    }
}

+ 44 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/es/ElasticFactory.java

@ -0,0 +1,44 @@
package com.yihu.wlyy.statistics.etl.save.es;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/6/5.
 */
@Component
public class ElasticFactory {
    private static JestClientFactory factory = null;
    @Value("${es.host}")
    private String esHost;
    /**
     * @param "http://localhost:9200"
     * @return
     */
    public JestClient getClient() {
        if (factory == null) {
            //初始化链接
            init();
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     */
    public synchronized void init() {
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://" + esHost)
                .multiThreaded(true)
                .discoveryEnabled(true)
                .readTimeout(30000)//30秒
                .build());//得到链接
    }
}

+ 56 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/save/es/ElastricSearchSave.java

@ -0,0 +1,56 @@
package com.yihu.wlyy.statistics.etl.save.es;
import com.yihu.wlyy.statistics.vo.SaveModel;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {
    @Value("${es.type}")
    private String esType;
    @Value("${es.index}")
    private String esIndex;
    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private ElasticFactory elasticFactory;
    public Boolean save(List<SaveModel> sms) {
        try {
            //得到链接
            JestClient jestClient = elasticFactory.getClient();
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (SaveModel obj : sms) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            //关闭链接
            jestClient.shutdownClient();
            return br.isSucceeded();
        } catch (Exception e) {
            logger.error(" save error :" + e.getMessage());
        }
        return null;
    }
}

+ 323 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentMysqlToEsQuotaJob.java

@ -0,0 +1,323 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.QuartzJobConfigDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.dao.WlyyDimensionQuotaDao;
import com.yihu.wlyy.statistics.etl.cache.Cache;
import com.yihu.wlyy.statistics.etl.compute.ComputeHelper;
import com.yihu.wlyy.statistics.etl.convert.ConvertHelper;
import com.yihu.wlyy.statistics.etl.extract.ExtractHelper;
import com.yihu.wlyy.statistics.etl.filter.FilterHelper;
import com.yihu.wlyy.statistics.etl.save.SaveHelper;
import com.yihu.wlyy.statistics.etl.save.es.ElasticFactory;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.SpringUtil;
import com.yihu.wlyy.statistics.vo.*;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.lucene.queryparser.xml.FilterBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by chenweida on 2017/7/10.  实时查询
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class CurrentMysqlToEsQuotaJob implements Job {
    private Logger logger = LoggerFactory.getLogger(MysqlToEsQuotaJob.class);
    private String endTime;//结束时间
    private String startTime;//开始时间
    private String year;//要统计的年份
    private Date quotaDate;//统计的时间
    private String timeLevel;//1 日 2年
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private WlyyDimensionQuotaDao dimensionQuotaDao;
    @Autowired
    private ElasticFactory elasticFactory;
    @Value("${es.type}")
    private String esType;
    @Value("${es.index}")
    private String esIndex;
    @Autowired
    private QuartzJobConfigDao quartzJobConfigDao;
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try {
            //springz注入
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            initParams(context);
            //统计指标
            computequota();
        } catch (Exception e) {
            //如果出錯立即重新執行
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }
    /**
     * 初始化参数
     *
     * @param context
     */
    private void initParams(JobExecutionContext context) throws Exception {
        JobDataMap map = context.getJobDetail().getJobDataMap();
        this.timeLevel = map.getString("timeLevel");
        //为空默认是统计昨天的数据  统计昨天的数据是从 前天的下午17:00:00 到昨天的下午17:00:00
        //初始化结束时间
        this.endTime = DateUtil.getStringDate("yyyy-MM-dd HH:mm:ss");
        //初始化开始时间
        this.startTime = new LocalDate(new DateTime().minusDays(1)).toString("yyyy-MM-dd") + " 17:00:00"; //2017-06-01 17:00:00
        //初始化统计年份
        this.year = getNowYearByDate(endTime);
        this.quotaDate = DateUtil.strToDate(endTime, "yyyy-MM-dd");
    }
    /**
     * 计算指标
     */
    private void computequota() {
        //清空缓存
        Cache.cleanCache();
        List<QuartzJobConfig> list = quartzJobConfigDao.findByIds();
        list.stream().forEach(one -> {
            try {
                QuartzJobLog tjQuotaLog = new QuartzJobLog();
                tjQuotaLog.setJobId(one.getId());
                tjQuotaLog.setJobStartTime(new Date());
                //1..抽取数据 如果是累加就是 List<DataModel>  如果是相除 Map<String,List<DataModel>>
                List<DataModel> dataModels = extract(one);
                //2..根据规则过滤数据
                FilterModel filterModel = filter(dataModels);
                //得到改指标的维度
                List<WlyyDimensionQuota> dimensionQuotas = dimensionQuotaDao.findDimensionQuotasByQuotaCode(one.getId());
                //2.1.从维度的key转换
                if (dimensionQuotas != null && dimensionQuotas.size() > 0) {
                    filterModel = convert(filterModel, dimensionQuotas);
                }
                //3.统计数据
                List<SaveModel> sms = compute(filterModel.getData(), dimensionQuotas, timeLevel, one);
                //4.更新数据
                Boolean success = updateData(sms, quotaDate, one.getId(), timeLevel);
                tjQuotaLog.setJobType(success ? "1" : "0");
                tjQuotaLog.setJobEndTime(new Date());
                tjQuotaLog.setJobContent(JSONArray.fromObject(filterModel.getErrorModels()).toString());
                saveLog(tjQuotaLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * 删除 某个指标某一天的某个timelevel的数据
     *
     * @param quotaDate
     * @param quotaCode
     * @param timeLevel
     */
    private boolean updateData(List<SaveModel> sms, Date quotaDate, String quotaCode, String timeLevel) {
        try {
            JestClient jestClient = elasticFactory.getClient();
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("quotaCode", quotaCode))
                            .must(QueryBuilders.matchQuery("timeLevel", timeLevel))
                            .must(QueryBuilders.matchQuery("quotaDate", quotaDate))).size(10000);
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(esIndex).addType(esType)
                    .build();
            SearchResult result = jestClient.execute(search);
            List<SaveModel> saveModels = result.getSourceAsObjectList(SaveModel.class);
            //如果之前有值批量更新
            if (saveModels != null && saveModels.size() > 0) {
                //list转map
                Map<String, SaveModel> smsMap = new HashMap<>();
                sms.stream().forEach(one -> {
                    smsMap.put(one.getId(), one);
                });
                //根据id批量更新
                Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
                for (SaveModel obj : saveModels) {
                    SaveModel newResult = smsMap.get(obj.getId());
                    obj.setResult1(newResult.getResult1());
                    obj.setResult2(newResult.getResult2());
                    Update index = new Update.Builder(obj.getId()).build();
                    bulk.addAction(index);
                }
                BulkResult br = jestClient.execute(bulk.build());
                logger.info("update data count:" + saveModels.size());
                logger.info("update flag:" + br.isSucceeded());
                return br.isSucceeded();
            } else {
                //批量插入
                return saveDate(sms);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    @Transactional
    private void saveLog(QuartzJobLog tjQuotaLog) {
        quartzJobLogDao.save(tjQuotaLog);
    }
    private FilterModel convert(FilterModel dataModels, List<WlyyDimensionQuota> dimensionQuotas) {
        try {
            return SpringUtil.getBean(ConvertHelper.class).convert(dataModels, dimensionQuotas);
        } catch (Exception e) {
            logger.error("convert error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 保存数据
     *
     * @param sms
     */
    private Boolean saveDate(List<SaveModel> sms) {
        try {
            return SpringUtil.getBean(SaveHelper.class).save(sms);
        } catch (Exception e) {
            logger.error("save error:" + e.getMessage());
        }
        return false;
    }
    /**
     * 根据计算规则统计数据
     *
     * @param dataModels
     */
    private List<SaveModel> compute(List<DataModel> dataModels, List<WlyyDimensionQuota> dimensionQuotas, String timeLevel, QuartzJobConfig quartzJobConfig) {
        try {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            return SpringUtil.getBean(ComputeHelper.class).compute(dataModels, dimensionQuotas, wlyyJobConfigVO, endTime, timeLevel);
        } catch (Exception e) {
            logger.error("compute error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 过滤数据
     *
     * @param filterModel
     * @return
     */
    private FilterModel filter(List<DataModel> filterModel) {
        try {
            return SpringUtil.getBean(FilterHelper.class).filter(filterModel);
        } catch (Exception e) {
            logger.error("filter error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 抽取数据
     *
     * @return
     */
    private List<DataModel> extract(QuartzJobConfig quartzJobConfig) {
        try {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            List<DataModel> dataModels = null;
            //先判断指标是否支持缓存
            if (StringUtils.isEmpty(wlyyJobConfigVO.getCacheKey())) {
                //不支持直接去数据库拿
                dataModels = SpringUtil.getBean(ExtractHelper.class).extractData(wlyyJobConfigVO, startTime, endTime, year, timeLevel);
            } else {
                //缓存的key 是 时间+timelevel+key
                StringBuffer bu = new StringBuffer(DateUtil.dateToStr(quotaDate, "yyyy-MM-dd") + "-" + timeLevel + wlyyJobConfigVO.getCacheKey());
                //支持的话判断缓存有没有值
                dataModels = Cache.getCache(bu.toString());
                if (dataModels == null) {
                    //如果缓存是空的那么直接数据库拿 在放入缓存
                    dataModels = SpringUtil.getBean(ExtractHelper.class).extractData(wlyyJobConfigVO, startTime, endTime, year, timeLevel);
                    Cache.addCache(bu.toString(), dataModels);
                }
            }
            return dataModels;
        } catch (Exception e) {
            logger.error("extract error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 获取现在时间属于那个年度
     *
     * @param date
     * @return
     */
    public static String getNowYearByDate(String date) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        String todayString = simpleDateFormat.format(today);
        String startDateString = (1900 + today.getYear()) + "-06-30";
        Date startDate = simpleDateFormat.parse(startDateString);
        if (simpleDateFormat.parse(todayString).after(startDate)) {
            return (1900 + today.getYear()) + "";
        } else {
            return (1900 + today.getYear() - 1) + "";
        }
    }
}

+ 309 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/MysqlToEsQuotaJob.java

@ -0,0 +1,309 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.dao.WlyyDimensionQuotaDao;
import com.yihu.wlyy.statistics.etl.cache.Cache;
import com.yihu.wlyy.statistics.etl.compute.ComputeHelper;
import com.yihu.wlyy.statistics.etl.convert.ConvertHelper;
import com.yihu.wlyy.statistics.etl.extract.ExtractHelper;
import com.yihu.wlyy.statistics.etl.filter.FilterHelper;
import com.yihu.wlyy.statistics.etl.save.SaveHelper;
import com.yihu.wlyy.statistics.etl.save.es.ElasticFactory;
import com.yihu.wlyy.statistics.model.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.SpringUtil;
import com.yihu.wlyy.statistics.vo.*;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.lucene.queryparser.xml.FilterBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
 * Created by chenweida on 2017/7/10.
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class MysqlToEsQuotaJob implements Job {
    private Logger logger = LoggerFactory.getLogger(MysqlToEsQuotaJob.class);
    private WlyyJobConfigVO wlyyJobConfigVO;//指标对象
    private String endTime;//结束时间
    private String startTime;//开始时间
    private String year;//要统计的年份
    private Date quotaDate;//统计的时间
    private String timeLevel;//1 日 2年
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private WlyyDimensionQuotaDao dimensionQuotaDao;
    @Autowired
    private ElasticFactory elasticFactory;
    @Value("${es.type}")
    private String esType;
    @Value("${es.index}")
    private String esIndex;
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try {
            //springz注入
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            initParams(context);
            //统计指标
            computequota();
        } catch (Exception e) {
            //如果出錯立即重新執行
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }
    /**
     * 初始化参数
     *
     * @param context
     */
    private void initParams(JobExecutionContext context) throws Exception {
        JobDataMap map = context.getJobDetail().getJobDataMap();
        this.timeLevel = map.getString("timeLevel");
        this.endTime = map.getString("endTime");
        this.startTime = map.getString("startTime");
        //为空默认是统计昨天的数据  统计昨天的数据是从 前天的下午17:00:00 到昨天的下午17:00:00
        //初始化结束时间
        if (StringUtils.isEmpty(endTime)) {
            endTime = new LocalDate(new DateTime().minusDays(1)).toString("yyyy-MM-dd") + " 17:00:00"; //2017-06-01 17:00:00
        } else {
            endTime = endTime + " 17:00:00";
        }
        //初始化开始时间
        if (StringUtils.isEmpty(startTime)) {
            startTime = new LocalDate(new DateTime().minusDays(2)).toString("yyyy-MM-dd") + " 17:00:00"; //2017-06-01 17:00:00
        } else {
            startTime = startTime + " 17:00:00";
        }
        //初始化统计年份
        this.year = getNowYearByDate(endTime);
        this.quotaDate = DateUtil.strToDate(endTime, "yyyy-MM-dd");
        this.wlyyJobConfigVO = (WlyyJobConfigVO) map.get("jobConfig");
    }
    /**
     * 计算指标
     */
    private void computequota() {
        try {
            QuartzJobLog tjQuotaLog = new QuartzJobLog();
            tjQuotaLog.setJobId(wlyyJobConfigVO.getId());
            tjQuotaLog.setJobStartTime(new Date());
            // 0 删除这天的数据
            deleteData(quotaDate, wlyyJobConfigVO.getId(), timeLevel);
            //1..抽取数据 如果是累加就是 List<DataModel>  如果是相除 Map<String,List<DataModel>>
            List<DataModel> dataModels = extract();
            //2..根据规则过滤数据
            FilterModel filterModel = filter(dataModels);
            //得到该指标的维度
            List<WlyyDimensionQuota> dimensionQuotas = dimensionQuotaDao.findDimensionQuotasByQuotaCode(wlyyJobConfigVO.getId());
            //2.1.从维度的key转换
            if (dimensionQuotas != null && dimensionQuotas.size() > 0) {
                filterModel = convert(filterModel, dimensionQuotas);
            }
            //3.统计数据
            List<SaveModel> sms = compute(filterModel.getData(), dimensionQuotas, timeLevel);
            //4.保存数据
            Boolean success = saveDate(sms);
            tjQuotaLog.setJobType(success ? "1" : "0");
            tjQuotaLog.setJobEndTime(new Date());
            tjQuotaLog.setJobContent(JSONArray.fromObject(filterModel.getErrorModels()).toString());
            saveLog(tjQuotaLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除 某个指标某一天的某个timelevel的数据
     *
     * @param quotaDate
     * @param quotaCode
     * @param timeLevel
     */
    private void deleteData(Date quotaDate, String quotaCode, String timeLevel) {
        try {
            JestClient jestClient = elasticFactory.getClient();
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("quotaCode", quotaCode))
                            .must(QueryBuilders.matchQuery("timeLevel", timeLevel))
                            .must(QueryBuilders.matchQuery("quotaDate", quotaDate))).size(10000);
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(esIndex).addType(esType)
                    .build();
            SearchResult result = jestClient.execute(search);
            List<SaveModel> saveModels = result.getSourceAsObjectList(SaveModel.class);
            //根据id批量删除
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (SaveModel obj : saveModels) {
                Delete index = new Delete.Builder(obj.getId()).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("delete data count:" + saveModels.size());
            logger.info("delete flag:" + br.isSucceeded());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Transactional
    private void saveLog(QuartzJobLog tjQuotaLog) {
        quartzJobLogDao.save(tjQuotaLog);
    }
    private FilterModel convert(FilterModel dataModels, List<WlyyDimensionQuota> dimensionQuotas) {
        try {
            return SpringUtil.getBean(ConvertHelper.class).convert(dataModels, dimensionQuotas);
        } catch (Exception e) {
            logger.error("convert error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 保存数据
     *
     * @param sms
     */
    private Boolean saveDate(List<SaveModel> sms) {
        try {
            return SpringUtil.getBean(SaveHelper.class).save(sms);
        } catch (Exception e) {
            logger.error("save error:" + e.getMessage());
        }
        return false;
    }
    /**
     * 根据计算规则统计数据
     *
     * @param dataModels
     */
    private List<SaveModel> compute(List<DataModel> dataModels, List<WlyyDimensionQuota> dimensionQuotas, String timeLevel) {
        try {
            return SpringUtil.getBean(ComputeHelper.class).compute(dataModels, dimensionQuotas, wlyyJobConfigVO, endTime, timeLevel);
        } catch (Exception e) {
            logger.error("compute error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 过滤数据
     *
     * @param dataModel
     * @return
     */
    private FilterModel filter(List<DataModel> dataModel) {
        try {
            FilterModel filterModel= SpringUtil.getBean(FilterHelper.class).filter(dataModel);
            logger.info("FilterModel:  success sizs:"+filterModel.getData().size()+",error size:"+filterModel.getErrorModels().size());
            return filterModel;
        } catch (Exception e) {
            logger.error("filter error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 抽取数据
     *
     * @return
     */
    private List<DataModel> extract() {
        try {
            List<DataModel> dataModels = null;
            //先判断指标是否支持缓存
            if (StringUtils.isEmpty(wlyyJobConfigVO.getCacheKey())) {
                //不支持直接去数据库拿
                dataModels = SpringUtil.getBean(ExtractHelper.class).extractData(wlyyJobConfigVO, startTime, endTime, year, timeLevel);
            }else{
                //缓存的key 是 时间+timelevel+key
                StringBuffer bu=new StringBuffer(DateUtil.dateToStr(quotaDate,"yyyy-MM-dd")+"-"+timeLevel+"-"+wlyyJobConfigVO.getCacheKey());
                //支持的话判断缓存有没有值
                dataModels= Cache.getCache(bu.toString());
                if(dataModels==null){
                    //如果缓存是空的那么直接数据库拿 在放入缓存
                    dataModels = SpringUtil.getBean(ExtractHelper.class).extractData(wlyyJobConfigVO, startTime, endTime, year, timeLevel);
                     Cache.addCache(bu.toString(),dataModels);
                }
            }
            logger.info("quotaCode:"+wlyyJobConfigVO.getId()+",size:"+dataModels.size());
            return dataModels;
        } catch (Exception e) {
            logger.error("extract error:" + e.getMessage());
        }
        return null;
    }
    /**
     * 获取现在时间属于那个年度
     *
     * @param date
     * @return
     */
    public static String getNowYearByDate(String date) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        String todayString = simpleDateFormat.format(today);
        String startDateString = (1900 + today.getYear()) + "-07-01";
        Date startDate = simpleDateFormat.parse(startDateString);
        if (simpleDateFormat.parse(todayString).after(startDate)) {
            return (1900 + today.getYear()) + "";
        } else {
            return (1900 + today.getYear() - 1) + "";
        }
    }
}

+ 95 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/check/CheckSignJob.java

@ -0,0 +1,95 @@
package com.yihu.wlyy.statistics.job.check;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by Administrator on 2016.10.11.
 * 判断签约的数据对不对 不对的话 添加任务重新生成签约数据
 */
@Component
@Scope("prototype")
public class CheckSignJob implements Job{
    public static String jobKey="CHECK_SIGN_JOB";
    public static String cron="0 */5 * * * ?";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.from}")
    private String from;;
    @Value("${spring.mail.to}")
    private String to;;
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            String timeKey=redisTemplate.opsForValue().get("quota:timeKey");
            long produceTime=  redisTemplate.getExpire("quota:16:4:350200:"+timeKey);
            long now =new Date().getTime();
            long nh = 1000*60*60;//一小时的毫秒数
            long nm = 60;//一分钟的毫秒数
            //如果当前时间扣掉生成时间大于2小时
            if((now-Long.valueOf(timeKey))/nh>2){
                sendEmail("实时统计失败,redis数据生成失败,redis数据生成时间時間:"+ DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+",当前系统时间:"+ DateUtil.dateToStrLong(new Date())+",key剩下多少时间:"+ (produceTime/3600)+"小时"+(produceTime%3600/60)+"分钟"+(produceTime%3600%60)+"秒");
            }
            //判断当前时间是不是
            if(!redisTemplate.hasKey("quota:16:4:350200:"+timeKey)){
                //发送邮件给管理员
               sendEmail("实时统计失败,redis数据生成失败,redis数据为空時間:"+ DateUtil.dateToStrLong(new Date()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void sendEmail(String text) throws Exception {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);//发送者.
        message.setSubject("实时统计失败");//邮件主题.
        message.setText(text);//邮件内容.
        String[] tos=to.split(",");
        message.setTo(tos);
        javaMailSender.send(message);
    }
    public void dateDiff(String startTime, String endTime, String format) throws Exception{
        //按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000*24*60*60;//一天的毫秒数
        long nh = 1000*60*60;//一小时的毫秒数
        long nm = 1000*60;//一分钟的毫秒数
        long ns = 1000;//一秒钟的毫秒数long diff;try {
        //获得两个时间的毫秒时间差异
        long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        long day = diff/nd;//计算差多少天
        long hour = diff%nd/nh;//计算差多少小时
        long min = diff%nd%nh/nm;//计算差多少分钟
        long sec = diff%nd%nh%nm/ns;//计算差多少秒//输出结果
        System.out.println("时间相差:"+day+"天"+hour+"小时"+min+"分钟"+sec+"秒。");
    }
    public static void main(String[] args) {
        Long produceTime=47265L;
        System.out.println( );
    }
}

+ 101 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/FollowupPlanJob.java

@ -0,0 +1,101 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import javax.transaction.Transactional;
import java.util.*;
/**
 * Created by hzp on 2017.1.4.
 */
@Component
@Scope("prototype")
public class FollowupPlanJob implements Job {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private MessageDao messageDao;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        System.out.print("follow plan message sending...");
        String date = DateUtil.dateToStrShort(new Date());
        //发送随访计划消息
        sendMessage(date);
        System.out.print("follow plan message send over.");
    }
    /**
     * 每日发送随访计划提醒消息
     */
    @Transactional
    public void sendMessage(String date)
    {
        try{
            String start = date +" 00:00:00";
            String end = date +" 23:59:59";
            String sql = "select doctor_code,count(1) count from wlyy_followup where status not in ('0','1') and followup_plan_date>='"+start+"' and followup_plan_date<='"+end+"' group by doctor_code";
            //获取所有未执行随访计划
            List<Map<String,Object>> followupToday = jdbcTemplate.queryForList(sql);
            if(followupToday!=null)
            {
                List<Message> list = new ArrayList<>();
                for(Map<String,Object> map:followupToday)
                {
                    String doctor = String.valueOf(map.get("doctor_code"));
                    String count = String.valueOf(map.get("count"));
                    // 添加签约消息
                    String title = "随访计划提醒";
                    String content = "您今日有" +count+"个随访计划待处理";
                    Message message = new Message();
                    message.setCode(UUID.randomUUID().toString());
                    message.setCzrq(new Date());
                    message.setCreateTime(new Date());
                    message.setContent(content);
                    message.setRead(1);//设置未读
                    message.setReceiver(doctor);//设置接受医生的code
                    message.setSender("system");//设置发送的用户
                    message.setTitle(title);
                    message.setType(4);//随访计划提醒
                    message.setReadonly(1);//是否只读消息
                    list.add(message);
                    // 推送消息给医生
                    PushMsgTask.url= url;
                    // 推送消息给医生
                    PushMsgTask.getInstance().put(doctor,"4",title,content,"");
                }
                messageDao.save(list);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

+ 150 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/HealthMessageJob.java

@ -0,0 +1,150 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.etl.extract.db.DBExtract;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Administrator on 2016.10.25.
 */
@Component
@Scope("prototype")
public class HealthMessageJob implements Job {
    public static String jobKey = "Health_Message_JOB";
    public static String cron = "0 0 8 * * ?";
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(jobKey);
            quartzJobLog.setJobName(jobKey);
            String yesterday = jobExecutionContext.getMergedJobDataMap().getString("yesterday");
            String now = jobExecutionContext.getMergedJobDataMap().getString("now");
            if (StringUtils.isEmpty(yesterday)) {
                yesterday = getYesterday(-1, new Date());
            }
            if (StringUtils.isEmpty(now)) {
                now = getYesterday(0, new Date());
            }
            //删除原来的数据
            String deleteSql = "delete from wlyy_message where type=3 and czrq >= '" + yesterday + " 00:00:00'and czrq <= '" + now + " 00:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql = "select admin_team_code  from wlyy_sign_family " +
                    " where  status >0 and type='2' " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            String countSql = "select count(id) from wlyy_sign_family " +
                    " where  status >0 and type='2'  " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            List<SignFamily> signFamilyList = dbExtract.extractByPage(SignFamily.class, sql, countSql, true, jdbcTemplate);
            Map<Long, List<SignFamily>> signFamilyMap = new HashMap<Long, List<SignFamily>>();
            for (int i = 0; i < signFamilyList.size(); i++) {
                SignFamily signFamilyTemp = signFamilyList.get(i);
                if (signFamilyMap.containsKey(signFamilyTemp.getAdminTeamCode())) {
                    signFamilyMap.get(signFamilyTemp.getAdminTeamCode()).add(signFamilyTemp);
                } else {
                    List<SignFamily> signFamilies = new ArrayList<>();
                    signFamilies.add(signFamilyTemp);
                    signFamilyMap.put(signFamilyTemp.getAdminTeamCode(), signFamilies);
                }
            }
            JSONArray jsonArray = new JSONArray();
            for (Map.Entry<Long, List<SignFamily>> entry : signFamilyMap.entrySet()) {
                //得到未分配的所有数目
                countSql = "select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2'  " +
                        "  and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '') and admin_team_code=" + entry.getKey() + "";
                Integer allCount = jdbcTemplate.queryForObject(countSql, Integer.class);
                //得到团队的leader
                sql = "select leader_code from wlyy_admin_team m where m.id= ?";
                String teamLeader = jdbcTemplate.queryForObject(sql, String.class, entry.getKey());
                Message message = new Message();
                message.setType(3);
                message.setRead(0);
                message.setOver("0");
                message.setDel("1");
                message.setSender("system");
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setState(1);
                String title = "新增系统消息";
                message.setTitle(title);
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
                String content = dateFormat2.format(dateFormat1.parse(yesterday)) + "新增" + entry.getValue().size() + "个签约居民待分配健管师,目前共" + allCount + "人待处理";
                message.setContent(content);
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(teamLeader);
                messageDao.save(message);
                quartzJobLogDao.save(quartzJobLog);
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", teamLeader);
                json.put("type", "D_NH_01");
                json.put("title", title);
                json.put("msg", content);
                json.put("data", "");
                jsonArray.add(json);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成" + yesterday + "的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            // 推送消息给医生
            PushMsgTask.url = url;
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String getYesterday(Integer day, Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.add(Calendar.DAY_OF_MONTH, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public static void main(String[] args) {
    }
}

+ 221 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/NoticeJob.java

@ -0,0 +1,221 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.service.DoctorWorkTimeService;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/11/7.
 */
@Component
@Scope("prototype")
public class NoticeJob implements Job {
    public static String jobKey = "Notice_JOB";
    public static String jobCron = "0 0 8,14 * * ?"; //每天8点,14点,20 点执行一次
    private static String noticeKey1 = "D_ST_01";//专科
    private static String noticeKey2 = "D_ST_02";//全科
    private static String noticeKey3 = "D_ST_03";//健康管理师
    private static String noticeTitle = "系统消息";
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private QuartzJobLogDao dbStorage;
    @Autowired
    private DoctorDao doctorDao;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MessageDao messageDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(jobKey);
        quartzJobLog.setJobName(jobKey);
        try {
            List<Doctor> doctors = doctorDao.findAllDoctors();
            //得到所有未发送的医生的通知
            Map<String, JSONObject> maps = new HashMap<>();
            //发送通知
            for (Doctor doctor : doctors) {
                //判断医生是不是在工作时间内
                String noticeContent1 = " 您当前有[zxsize]条未处理消息,其中[qysize]条为签约消息。请尽快处理~";
                String noticeContent2 = " 您当前有[zxsize]条未处理消息,请尽快处理~";
                String noticeContent3 = " 您当前有[qysize]条签约消息待处理,请尽快处理~";
                String workTime = "";
                try {
                    workTime = doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).getString("status");
                } catch (Exception e) {
                }
                if ("1".equals(workTime)) {
                    //得到医生多少条咨询消息
                    Integer zxsize = getDoctorMesssageCount(doctor.getCode(), 1);
                    //得到医生多少条签约消息
                    Integer qysize = getDoctorMesssageCount(doctor.getCode(), 2);
                    //如果既有签约又有咨询
                    if (zxsize > 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent1 = noticeContent1.replace("[zxsize]", zxsize + "");
                        noticeContent1 = noticeContent1.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent1);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize > 0 && qysize == 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent2 = noticeContent2.replace("[zxsize]", zxsize + "");
                        jo.put("content", noticeContent2);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize == 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent3 = noticeContent3.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent3);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            //发送通知
            for (Map.Entry<String, JSONObject> entry : maps.entrySet()) {
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", entry.getKey());
                json.put("type", getType(entry.getValue().getInt("level")));
                json.put("title", noticeTitle);
                json.put("msg", entry.getValue().getString("content"));
                json.put("data", "");
                jsonArray.add(json);
            }
            // 推送消息给医生
            PushMsgTask.url = url;
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知成功");
            quartzJobLog.setJobType("1");
            dbStorage.save(quartzJobLog);
        } catch (Exception e) {
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知失败");
            quartzJobLog.setJobType("0");
            dbStorage.save(quartzJobLog);
            e.printStackTrace();
        }
    }
    private String getType(Integer level) {
        switch (level) {
            case 1: {
                //专科
                return noticeKey1;
            }
            case 2: {
                //全科
                return noticeKey2;
            }
            case 3: {
                //健康管理师
                return noticeKey3;
            }
        }
        return "";
    }
    /**
     * 得到医生的未读数目
     *
     * @param doctorCode 医生code
     * @param type       1是咨询 2个签约 3是体征
     * @return
     */
    private Integer getDoctorMesssageCount(String doctorCode, int type) throws Exception {
        switch (type) {
            case 1: {
                return getImMsgAmount(doctorCode);
            }
            case 2: {
                String sql = "select count(a.id) from wlyy_message a where a.type =1 and a.has_read=1 and a.receiver=?";
                return jdbcTemplate.queryForObject(sql, Integer.class, doctorCode);
            }
        }
        return 0;
    }
    private int findDoctorAllMessage(String doctor) {
        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        // 体征指标未读消息总数
        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        //系统消息
        int systemMessage = messageDao.amountUnreadSystemByReceiver(doctor);
        Integer doctorCount = 0;
        Integer patientCount = 0;
        JSONObject json = new JSONObject();
        getImMsgAmount(json, doctor);
        if (json.containsKey("imMsgCount")) {
            JSONObject jsonC = json.getJSONObject("imMsgCount");
            if (jsonC.containsKey("doctor")) {
                doctorCount = jsonC.getInt("doctor");
            }
            if (jsonC.containsKey("patient")) {
                patientCount = jsonC.getInt("patient");
            }
        }
        return sign + healthIndex + systemMessage + doctorCount + patientCount;
    }
    private void getImMsgAmount(JSONObject obj, String doctor) {
        String urlall = url + "/api/v1/chats/msg/amount?user_id=" + doctor;
        String response = HttpClientUtil.get(urlall, "UTF-8");
        obj.put("imMsgCount", response);
    }
    private Integer getImMsgAmount(String doctor) throws Exception {
        /**
         * {"msg":"获取消息总数成功!","data":{"imMsgCount":"{\"doctor\":0,\"patient\":0}","healthIndex":{"amount":0},"sign":{"amount":0}},"status":200}
         */
        return findDoctorAllMessage(doctor);
    }
}

+ 38 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/IdEntity.java

@ -0,0 +1,38 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
/**
 * 统一定义id的entity基类.
 * 
 * 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
 * Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
 * 
 * @author calvin
 */
// JPA 基类的标识
@MappedSuperclass
public abstract class IdEntity implements Serializable {
	private static final long serialVersionUID = 3673803562328635206L;
	protected Long id;  // 非业务主键
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}

+ 230 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/consult/ConsultTeam.java

@ -0,0 +1,230 @@
package com.yihu.wlyy.statistics.model.consult;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 三师咨询
 * @author George
 */
@Entity
@Table(name = "wlyy_consult_team")
public class ConsultTeam extends IdEntity {
	private static final long serialVersionUID = -7644448339473861513L;
	private String consult;         // 咨询标识
	private String doctor;          // 医生标识
	private String team;            // 三师团队标识
	private Integer type;           //  1、三师咨询,2、家庭医生咨询,6、名医咨询
	private String patient;         // 提问者标识
	private String name;            // 患者姓名
	private Integer sex;            // 患者性别
	private Date birthday;          // 患者生日
	private String photo;           // 患者头像
	private String when;            // 发病日期
	private String symptoms;        // 主要症状
	private Integer status;         // 咨询状态(0进行中,1已完成,-1患者取消,-2超时未响应自动关闭)
	private String images;          // 咨询图片URL,多图以逗号分隔
	private String voice;           // 咨询语音URL
	private String comment;         // 用户评价标识
	private String commentContent;  // 用户评价内容
	private Integer commentStar;    // 用户评价星级
	private Integer doctorRead;     // 医生未读数量
	private Integer patientRead;    // 患者未读数量
	private Date czrq;              // 咨询时间
	private String del;             // 作废标识,1正常,0作废
	private Long adminTeamCode;//行政团队ID
	@Column(name = "admin_team_code")
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getConsult() {
		return consult;
	}
	public void setConsult(String consult) {
		this.consult = consult;
	}
	public ConsultTeam() {
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getTeam() {
		return team;
	}
	public void setTeam(String team) {
		this.team = team;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	@Column(name = "fbsj")
	public String getWhen() {
		return when;
	}
	public void setWhen(String when) {
		this.when = when;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getImages() {
		return images;
	}
	public void setImages(String images) {
		this.images = images;
	}
	public String getVoice() {
		return voice;
	}
	public void setVoice(String voice) {
		this.voice = voice;
	}
	public String getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}
	@Column(name = "comment_content")
	public String getCommentContent() {
		return commentContent;
	}
	public void setCommentContent(String commentContent) {
		this.commentContent = commentContent;
	}
	@Column(name = "comment_star")
	public Integer getCommentStar() {
		return commentStar;
	}
	public void setCommentStar(Integer commentStar) {
		this.commentStar = commentStar;
	}
	@Column(name = "doctor_read")
	public Integer getDoctorRead() {
		return doctorRead;
	}
	public void setDoctorRead(Integer doctorRead) {
		this.doctorRead = doctorRead;
	}
	@Column(name = "patient_read")
	public Integer getPatientRead() {
		return patientRead;
	}
	public void setPatientRead(Integer patientRead) {
		this.patientRead = patientRead;
	}
	// 设定JSON序列化时的日期格式
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getSymptoms() {
		return symptoms;
	}
	public void setSymptoms(String symptoms) {
		this.symptoms = symptoms;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
}

+ 221 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/consult/ConsultTeamDto.java

@ -0,0 +1,221 @@
package com.yihu.wlyy.statistics.model.consult;
import com.yihu.wlyy.statistics.model.IdEntity;
import java.util.Date;
/**
 * Created by Trick on 2017/4/25.
 */
public class ConsultTeamDto extends IdEntity {
    private static final long serialVersionUID = -7644448339473861513L;
    private String consult;         // 咨询标识
    private String doctor;          // 医生标识
    private String team;            // 三师团队标识
    private Integer type;           //  1、三师咨询,2、家庭医生咨询,6、名医咨询
    private String patient;         // 提问者标识
    private String name;            // 患者姓名
    private Integer sex;            // 患者性别
    private Date birthday;          // 患者生日
    private String photo;           // 患者头像
    private String when;            // 发病日期
    private String symptoms;        // 主要症状
    private Integer status;         // 咨询状态(0进行中,1已完成,-1患者取消,-2超时未响应自动关闭)
    private String images;          // 咨询图片URL,多图以逗号分隔
    private String voice;           // 咨询语音URL
    private String comment;         // 用户评价标识
    private String commentContent;  // 用户评价内容
    private Integer commentStar;    // 用户评价星级
    private Integer doctorRead;     // 医生未读数量
    private Integer patientRead;    // 患者未读数量
    private Date czrq;              // 咨询时间
    private String del;             // 作废标识,1正常,0作废
    private Long adminTeamCode;//行政团队ID
    private Date replyTime;
    public String getConsult() {
        return consult;
    }
    public void setConsult(String consult) {
        this.consult = consult;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getTeam() {
        return team;
    }
    public void setTeam(String team) {
        this.team = team;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    public String getWhen() {
        return when;
    }
    public void setWhen(String when) {
        this.when = when;
    }
    public String getSymptoms() {
        return symptoms;
    }
    public void setSymptoms(String symptoms) {
        this.symptoms = symptoms;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getVoice() {
        return voice;
    }
    public void setVoice(String voice) {
        this.voice = voice;
    }
    public String getComment() {
        return comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
    public String getCommentContent() {
        return commentContent;
    }
    public void setCommentContent(String commentContent) {
        this.commentContent = commentContent;
    }
    public Integer getCommentStar() {
        return commentStar;
    }
    public void setCommentStar(Integer commentStar) {
        this.commentStar = commentStar;
    }
    public Integer getDoctorRead() {
        return doctorRead;
    }
    public void setDoctorRead(Integer doctorRead) {
        this.doctorRead = doctorRead;
    }
    public Integer getPatientRead() {
        return patientRead;
    }
    public void setPatientRead(Integer patientRead) {
        this.patientRead = patientRead;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    public Long getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(Long adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
    public Date getReplyTime() {
        return replyTime;
    }
    public void setReplyTime(Date replyTime) {
        this.replyTime = replyTime;
    }
}

+ 115 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/dimension/WlyyDimension.java

@ -0,0 +1,115 @@
package com.yihu.wlyy.statistics.model.dimension;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by chenweida on 2017/7/10.
 */
@Entity
@Table(name = "wlyy_dimension")
public class WlyyDimension extends IdEntity{
    private String code;
    private String type;
    private String name;
    private Date createTime;
    private String createUser;
    private String createUserName;
    private Date updateTime;
    private String updateUser;
    private String updateUserName;
    private Integer status;////-1 删除 0 禁用 可用
    private String remark;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getUpdateUserName() {
        return updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
}

+ 69 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/dimension/WlyyDimensionQuota.java

@ -0,0 +1,69 @@
package com.yihu.wlyy.statistics.model.dimension;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by chenweida on 2017/7/10.
 */
@Entity
@Table(name = "wlyy_dimension_quota")
public class WlyyDimensionQuota extends IdEntity {
    private String quotaCode;
    private String dimensionCode;
    private String dictSql;
    private Integer sort;
    private String convertClazz;
    private String key;
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    public String getDimensionCode() {
        return dimensionCode;
    }
    public void setDimensionCode(String dimensionCode) {
        this.dimensionCode = dimensionCode;
    }
    public String getDictSql() {
        return dictSql;
    }
    public void setDictSql(String dictSql) {
        this.dictSql = dictSql;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public String getConvertClazz() {
        return convertClazz;
    }
    public void setConvertClazz(String convertClazz) {
        this.convertClazz = convertClazz;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
}

+ 362 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/Doctor.java

@ -0,0 +1,362 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * 医生信息
 * @author George
 */
@Entity
@Table(name = "wlyy_doctor")
public class Doctor extends IdEntity {
	private static final long serialVersionUID = -6585552029939285364L;
    
	private String code;        // 业务主键
	
	private String name;
	private Integer sex;        // 性别(1男,2女)
	private Date birthday;
	private String photo;
	private String mobile;
	private String password;
	private String salt;        // 密码标识
	private Integer status;     // 状态(1正常,0禁用)
	
	private String province;
	private String city;
	private String town;
	private String provinceName;
	private String cityName;
    private String townName;
	
	private String hospital;        // 医院代码
	private String hosptialName;
	private String dept;            // 科室代码
	private String deptName;
	private String job;             // 职称代码
	private String jobName;         // 职称名
	
	private String expertise;       // 医生专长
	private String introduce;       // 医生介绍
	
	private Integer level;          // 类型:1专科医生,2全科医生,3健康管理师
	private Integer iscertified;   // 资格是否认证通过,1是,0否
    private String qrcode;          // 二维码
	
	private Date czrq;              // 更新时间
	private Integer del;            // 状态(1正常,0删除)
	private String idcard;          //身份证号
	private Integer isFamous;       //是否是名医 1是  0或者空不是
	private String isPasswordPrompt;// 是否提示密码信息 1是 0或者空是否
	public Doctor() {}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public Doctor(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSalt() {
		return salt;
	}
	public void setSalt(String salt) {
		this.salt = salt;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getTown() {
		return town;
	}
	public void setTown(String town) {
		this.town = town;
	}
	
	@Column(name = "province_name")
	public String getProvinceName() {
		return provinceName;
	}
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	@Column(name = "city_name")
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	@Column(name = "town_name")
	public String getTownName() {
		return townName;
	}
	public void setTownName(String townName) {
		this.townName = townName;
	}
	
	@Column(name = "hospital_name")
	public String getHosptialName() {
		return hosptialName;
	}
	public void setHosptialName(String hosptialName) {
		this.hosptialName = hosptialName;
	}
	@Column(name = "dept_name")
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	@Column(name = "job_name")
	public String getJobName() {
		return jobName;
	}
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}
	public String getHospital() {
		return hospital;
	}
	public void setHospital(String hospital) {
		this.hospital = hospital;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public String getExpertise() {
		return expertise;
	}
	public void setExpertise(String expertise) {
		this.expertise = expertise;
	}
	public String getIntroduce() {
		return introduce;
	}
	public void setIntroduce(String introduce) {
		this.introduce = introduce;
	}
	public Integer getLevel() {
		return level;
	}
	public void setLevel(Integer level) {
		this.level = level;
	}
    @Column(name = "iscertified")
    public Integer getIscertified() {
		return iscertified;
	}
	public void setIscertified(Integer isCertified) {
		this.iscertified = isCertified;
	}
	public String getQrcode() {
		return qrcode;
	}
	public void setQrcode(String qrcode) {
		this.qrcode = qrcode;
	}
	// 设定JSON序列化时的日期格式
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
	@Column(name = "del")
	public Integer getDel() {
		return del;
	}
	public void setDel(Integer del) {
		this.del = del;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	@Column(name = "is_famous")
	public Integer getIsFamous() {
		return isFamous;
	}
	public void setIsFamous(Integer isFamous) {
		this.isFamous = isFamous;
	}
    /**
     * 是否为专科医生。
     *
     * @return
     */
    @Transient
	public boolean isProfessionalDoctor(){
	    return level == 1;
    }
    /**
     * 是否为全科医生。
     *
     * @return
     */
    @Transient
	public boolean isGeneralDoctor(){
	    return level == 2;
    }
    /**
     * 是否为健康管理师。
     *
     * @return
     */
    @Transient
    public boolean isHealthDoctor(){
        return level == 3;
    }
	@Column(name = "is_password_prompt")
	public String getIsPasswordPrompt() {
		return isPasswordPrompt;
	}
	public void setIsPasswordPrompt(String isPasswordPrompt) {
		this.isPasswordPrompt = isPasswordPrompt;
	}
}

+ 71 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/DoctorPatientGroup.java

@ -0,0 +1,71 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 医生分组(三师、普通签约等)表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_doctor_patient_group")
public class DoctorPatientGroup extends IdEntity {
	private static final long serialVersionUID = 2055055862188986760L;
	
	// 业务主键
	private String code;
	//组名
	private String name;	
	// 医生标识
	private String doctor;
	// 发布时间
	private Date czrq;
	// 状态,1正常,0作废
	private Integer status;
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	
}

+ 128 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/DoctorPatientGroupInfo.java

@ -0,0 +1,128 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 医生对患者分组(三师、普通签约等)记录表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_doctor_patient_group_info")
public class DoctorPatientGroupInfo extends IdEntity {
	private static final long serialVersionUID = 5559656428707106920L;
	// 医生标识
	private String doctor;
	// 患者标识
	private String patient;
	// 患者姓名
	private String pname;
	// 分组标识(1:健康人群 2:慢病人群 3:我的具名)
	private String group;
	// 病历片段总数
	private Integer partAmount;
	// 签约日期/已诊日期
	private Date qyrq;
	// 到期日期
	private Date dqrq;
	// 添加时间
	private Date czrq;
	// 状态,1正常,0作废
	private Integer status;
	//签约类型(1表示三师签约,2表示家庭签约)
	private String signType;
	@Column(name = "sign_type")
	public String getSignType() {
		return signType;
	}
	public void setSignType(String signType) {
		this.signType = signType;
	}
	
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	@Column(name = "group_code")
	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getDqrq() {
		return dqrq;
	}
	public void setDqrq(Date dqrq) {
		this.dqrq = dqrq;
	}
	@Column(name = "part_amount")
	public Integer getPartAmount() {
		return partAmount;
	}
	public void setPartAmount(Integer partAmount) {
		this.partAmount = partAmount;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getQyrq() {
		return qyrq;
	}
	public void setQyrq(Date qyrq) {
		this.qyrq = qyrq;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
}

+ 116 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkTime.java

@ -0,0 +1,116 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by lyr on 2016/08/19.
 */
@Entity
@Table(name = "wlyy_doctor_work_time")
public class WlyyDoctorWorkTime extends IdEntity {
    // 医生标识
    private String doctor;
    // 医生姓名
    private String doctorName;
    // 接收咨询 0不接受 1接受
    private String receiveConsult;
    // 名医咨询次数
    private Integer famousConsultTimes;
    // 上午开始时间
    private String morningBegin;
    // 上午结束时间
    private String morningEnd;
    // 下午开始时间
    private String afternoonBegin;
    // 下午结束时间
    private String afternoonEnd;
    // 晚上开始时间
    private String nightBegin;
    // 晚上结束时间
    private String nightEnd;
    // 更新时间
    private Date czrq;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getReceiveConsult() {
        return receiveConsult;
    }
    public void setReceiveConsult(String receiveConsult) {
        this.receiveConsult = receiveConsult;
    }
    public Integer getFamousConsultTimes() {
        return famousConsultTimes;
    }
    public void setFamousConsultTimes(Integer famousConsultTimes) {
        this.famousConsultTimes = famousConsultTimes;
    }
    public String getMorningBegin() {
        return morningBegin;
    }
    public void setMorningBegin(String morningBegin) {
        this.morningBegin = morningBegin;
    }
    public String getMorningEnd() {
        return morningEnd;
    }
    public void setMorningEnd(String morningEnd) {
        this.morningEnd = morningEnd;
    }
    public String getAfternoonBegin() {
        return afternoonBegin;
    }
    public void setAfternoonBegin(String afternoonBegin) {
        this.afternoonBegin = afternoonBegin;
    }
    public String getAfternoonEnd() {
        return afternoonEnd;
    }
    public void setAfternoonEnd(String afternoonEnd) {
        this.afternoonEnd = afternoonEnd;
    }
    public String getNightBegin() {
        return nightBegin;
    }
    public void setNightBegin(String nightBegin) {
        this.nightBegin = nightBegin;
    }
    public String getNightEnd() {
        return nightEnd;
    }
    public void setNightEnd(String nightEnd) {
        this.nightEnd = nightEnd;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 70 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkWeek.java

@ -0,0 +1,70 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import java.util.Date;
/**
 * Created by lyr on 2016/08/19.
 */
@Entity
public class WlyyDoctorWorkWeek extends IdEntity {
    private String doctor;
    private String doctorName;
    private String week;
    private String morning;
    private String afternoon;
    private String night;
    private Date czrq;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getWeek() {
        return week;
    }
    public void setWeek(String week) {
        this.week = week;
    }
    public String getMorning() {
        return morning;
    }
    public void setMorning(String morning) {
        this.morning = morning;
    }
    public String getAfternoon() {
        return afternoon;
    }
    public void setAfternoon(String afternoon) {
        this.afternoon = afternoon;
    }
    public String getNight() {
        return night;
    }
    public void setNight(String night) {
        this.night = night;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 156 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/hosptial/Hospital.java

@ -0,0 +1,156 @@
package com.yihu.wlyy.statistics.model.hosptial;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 医院
 *
 * @author George
 */
@Entity
@Table(name = "dm_hospital")
public class Hospital extends IdEntity {
	private static final long serialVersionUID = 8039389705624435301L;
	private String code;            // 医院編碼
	private String name;	        // 医院名稱
	private String del;             // 作废标志
	private String province;        //省份标志
	private String provinceName;    //省份名称
	private String city;            //城市标志
	private String cityName;        //城市名称
	private String town;            //区县标志
	private String townName;        //区县名称
	private Integer level;          //级别,1医院,2社区医院
	private String address;         //医院详细地址
	private String intro;           //医院简介
	private String photo;           //医院图片
	private String roadCode;        //街道编码
	private String centerSite;      //中心/站点
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getProvinceName() {
		return provinceName;
	}
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public String getTown() {
		return town;
	}
	public void setTown(String town) {
		this.town = town;
	}
	public String getTownName() {
		return townName;
	}
	public void setTownName(String townName) {
		this.townName = townName;
	}
	public Integer getLevel() {
		return level;
	}
	public void setLevel(Integer level) {
		this.level = level;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getIntro() {
		return intro;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	@Column(name="road_code")
	public String getRoadCode() {
		return roadCode;
	}
	public void setRoadCode(String roadCode) {
		this.roadCode = roadCode;
	}
	@Column(name="center_site")
	public String getCenterSite() {
		return centerSite;
	}
	public void setCenterSite(String centerSite) {
		this.centerSite = centerSite;
	}
}

+ 170 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/QuartzJobConfig.java

@ -0,0 +1,170 @@
package com.yihu.wlyy.statistics.model.job;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
 * 计划任务
 */
@Entity
@Table(name = "wlyy_job_config")
public class QuartzJobConfig implements java.io.Serializable {
	private String id;
	private String quotaId;//指标id
	private String jobName;//任务名称
	private String jobInfo;//任务描述
	private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
	private String jobClass;//任务执行的class
	private String quartzCron;//quartz表达式
	private String status;//1 启动 0停止
	private String del;//是否删除 1正常 0删除
	private String sql;
	private String sqlCount;
	private String sqlDay;
	private String sqlYear;
	private String cacheKey;//缓存的key
	/** minimal constructor */
	public QuartzJobConfig() {
	}
	/** full constructor */
	public QuartzJobConfig(String jobName, String jobInfo, String jobType,
                           String jobClass, String quartzCron, String status) {
		this.jobName = jobName;
		this.jobInfo = jobInfo;
		this.jobType = jobType;
		this.jobClass = jobClass;
		this.quartzCron = quartzCron;
		this.status = status;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "job_name", length = 50)
	public String getJobName() {
		return this.jobName;
	}
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}
	@Column(name = "job_info", length = 200)
	public String getJobInfo() {
		return this.jobInfo;
	}
	public void setJobInfo(String jobInfo) {
		this.jobInfo = jobInfo;
	}
	@Column(name = "job_type", length = 10)
	public String getJobType() {
		return this.jobType;
	}
	public void setJobType(String jobType) {
		this.jobType = jobType;
	}
	@Column(name = "job_class", length = 200)
	public String getJobClass() {
		return jobClass;
	}
	public void setJobClass(String jobClass) {
		this.jobClass = jobClass;
	}
	@Column(name = "quartz_cron", length = 200)
	public String getQuartzCron() {
		return this.quartzCron;
	}
	public void setQuartzCron(String quartzCron) {
		this.quartzCron = quartzCron;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "quota_id", length = 50)
	public String getQuotaId() {
		return quotaId;
	}
	public void setQuotaId(String quotaId) {
		this.quotaId = quotaId;
	}
	@Column(name = "del", length = 1)
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	public String getSql() {
		return sql;
	}
	public void setSql(String sql) {
		this.sql = sql;
	}
	public String getSqlCount() {
		return sqlCount;
	}
	public void setSqlCount(String sqlCount) {
		this.sqlCount = sqlCount;
	}
	public String getSqlDay() {
		return sqlDay;
	}
	public void setSqlDay(String sqlDay) {
		this.sqlDay = sqlDay;
	}
	public String getSqlYear() {
		return sqlYear;
	}
	public void setSqlYear(String sqlYear) {
		this.sqlYear = sqlYear;
	}
	public String getCacheKey() {
		return cacheKey;
	}
	public void setCacheKey(String cacheKey) {
		this.cacheKey = cacheKey;
	}
}

+ 104 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/QuartzJobLog.java

@ -0,0 +1,104 @@
package com.yihu.wlyy.statistics.model.job;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
/**
 * QuartzJobLog entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "wlyy_job_log")
public class QuartzJobLog implements java.io.Serializable {
	private String id;
	private Date jobStartTime;  //任务开始执行时间
	private Date jobEndTime;    //任务结束时间
	private String jobId;       //任务id
	private String jobName;     //任务名称
	private String jobContent;  //任务执行情况
	private String jobType;     // 1成功 0失败
    public QuartzJobLog(){}
	public QuartzJobLog(String jobId) {
		this.jobId = jobId;
	}
	public QuartzJobLog(Timestamp jobStartTime, Timestamp jobEndTime,
                        String jobId, String jobContent, String jobType) {
		this.jobStartTime = jobStartTime;
		this.jobEndTime = jobEndTime;
		this.jobId = jobId;
		this.jobContent = jobContent;
		this.jobType = jobType;
	}
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "job_start_time", length = 0)
	public Date getJobStartTime() {
		return this.jobStartTime;
	}
	public void setJobStartTime(Date jobStartTime) {
		this.jobStartTime = jobStartTime;
	}
	@Column(name = "Job_end_time", length = 0)
	public Date getJobEndTime() {
		return this.jobEndTime;
	}
	public void setJobEndTime(Date jobEndTime) {
		this.jobEndTime = jobEndTime;
	}
	@Column(name = "job_id", nullable = false, length = 50)
	public String getJobId() {
		return this.jobId;
	}
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
	@Column(name = "job_content", length = 1000)
	public String getJobContent() {
		return this.jobContent;
	}
	public void setJobContent(String jobContent) {
		this.jobContent = jobContent;
	}
	@Column(name = "job_type", length = 1)
	public String getJobType() {
		return this.jobType;
	}
	public void setJobType(String jobType) {
		this.jobType = jobType;
	}
	@Column(name = "job_name", length = 200)
	public String getJobName() {
		return jobName;
	}
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}
}

+ 117 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/WlyyQuota.java

@ -0,0 +1,117 @@
package com.yihu.wlyy.statistics.model.job;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
 * WlyyQuota entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "wlyy_quota")
public class WlyyQuota implements java.io.Serializable {
	private String id;
	private String name;//指标名称
	private String level1;//指标维度(1:机构维度)
	private String level2;//2级维度 (1:患者性别 2:患者分组 3:患者年龄)
	private String level3;//3级维度 (1:患者疾病)
	private String cycle;//统计周期( 1:天 )
	private String type;//尺度(1 新增 2是累计)
	private Date createTime;//创建时间
	private Date modifyTime;//修改时间
	private String del;//1: 正常 0: 删除
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 100)
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "name", length = 200)
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "level_2", length = 2)
	public String getLevel2() {
		return this.level2;
	}
	public void setLevel2(String level2) {
		this.level2 = level2;
	}
	@Column(name = "level_1", length = 2)
	public String getLevel1() {
		return this.level1;
	}
	public void setLevel1(String level1) {
		this.level1 = level1;
	}
	@Column(name = "cycle", length = 2)
	public String getCycle() {
		return this.cycle;
	}
	public void setCycle(String cycle) {
		this.cycle = cycle;
	}
	@Column(name = "type", length = 2)
	public String getType() {
		return this.type;
	}
	public void setType(String type) {
		this.type = type;
	}
	@Column(name = "create_time", length = 0)
	public Date getCreateTime() {
		return this.createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Column(name = "modify_time", length = 0)
	public Date getModifyTime() {
		return this.modifyTime;
	}
	public void setModifyTime(Date modifyTime) {
		this.modifyTime = modifyTime;
	}
	@Column(name = "del", length = 1)
	public String getDel() {
		return this.del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@Column(name = "level_3", length = 2)
	public String getLevel3() {
		return level3;
	}
	public void setLevel3(String level3) {
		this.level3 = level3;
	}
}

+ 229 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/job/WlyyQuotaResult.java

@ -0,0 +1,229 @@
package com.yihu.wlyy.statistics.model.job;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
 * WlyyQuotaResult entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "wlyy_quota_result")
public class WlyyQuotaResult implements java.io.Serializable {
    private String id;
    private Date quotaDate;//统计时间
    private String quatoCode;//指标code
    private String quatoName;//指标name
    private String result;//统计结果
    private String del;//1: 正常 0: 删除
    private String level1Type;//等级 1:团队 2社区机构 3区级 4市级
    private String level2Type;//如果有二级维度那么这个存的是二级维度的code 例如二级维度是性别 那么这个存 1
    private String level2TypeName;//如果有二级维度那么这个存的是二级维度的code 例如二级维度是性别 那么这个存 男
    private String level3Type;//如果有三级维度那么这个存的是三级维度的code 例如三级维度是疾病 那么这个存 1
    private String level3TypeName;//如果有三级维度那么这个存的是三级维度的code 例如三级维度是疾病 那么这个存 高血压
    private String city;//市
    private String cityName;//市级名称
    private String town;//区级
    private String townName;//区级名称
    private String orgCode;//机构code
    private String orgName;//机构名称
    private String qkdoctorName;//全科医生名称 --现在是团队名称
    private String qkdoctorCode;//全科医生code --现在是团队code
    private String qkdoctorJobName;//全科医生职称   用于检验统计线程判断指标是否需要重新生成  等于 1 的时候是不需要
    private Date createTime;//创建时间
    @Id
    @GenericGenerator(name = "generator", strategy = "uuid")
    @GeneratedValue(generator = "generator")
    @Column(name = "id", unique = true, nullable = false, length = 100)
    public String getId() {
        return this.id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(name = "org_code", length = 100)
    public String getOrgCode() {
        return this.orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    @Column(name = "org_name", length = 200)
    public String getOrgName() {
        return this.orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    @Column(name = "quota_date")
    public Date getQuotaDate() {
        return quotaDate;
    }
    public void setQuotaDate(Date quotaDate) {
        this.quotaDate = quotaDate;
    }
    @Column(name = "quato_code", length = 100)
    public String getQuatoCode() {
        return this.quatoCode;
    }
    public void setQuatoCode(String quatoCode) {
        this.quatoCode = quatoCode;
    }
    @Column(name = "quato_name", length = 200)
    public String getQuatoName() {
        return this.quatoName;
    }
    public void setQuatoName(String quatoName) {
        this.quatoName = quatoName;
    }
    @Column(name = "result", length = 500)
    public String getResult() {
        return this.result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    @Column(name = "city", length = 10)
    public String getCity() {
        return this.city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Column(name = "city_name", length = 200)
    public String getCityName() {
        return this.cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    @Column(name = "town", length = 10)
    public String getTown() {
        return this.town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    @Column(name = "town_name", length = 200)
    public String getTownName() {
        return this.townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    @Column(name = "qkdoctor_name", length = 200)
    public String getQkdoctorName() {
        return this.qkdoctorName;
    }
    public void setQkdoctorName(String qkdoctorName) {
        this.qkdoctorName = qkdoctorName;
    }
    @Column(name = "qkdoctor_job_name", length = 200)
    public String getQkdoctorJobName() {
        return this.qkdoctorJobName;
    }
    public void setQkdoctorJobName(String qkdoctorJobName) {
        this.qkdoctorJobName = qkdoctorJobName;
    }
    @Column(name = "del", length = 1)
    public String getDel() {
        return this.del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Column(name = "qkdoctor_code", length = 200)
    public String getQkdoctorCode() {
        return qkdoctorCode;
    }
    public void setQkdoctorCode(String qkdoctorCode) {
        this.qkdoctorCode = qkdoctorCode;
    }
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "level1_type", length = 2)
    public String getLevel1Type() {
        return level1Type;
    }
    public void setLevel1Type(String level1Type) {
        this.level1Type = level1Type;
    }
    @Column(name = "level2_type", length = 50)
    public String getLevel2Type() {
        return level2Type;
    }
    public void setLevel2Type(String level2Type) {
        this.level2Type = level2Type;
    }
    @Column(name = "level2_type_name", length = 50)
    public String getLevel2TypeName() {
        return level2TypeName;
    }
    public void setLevel2TypeName(String level2TypeName) {
        this.level2TypeName = level2TypeName;
    }
    @Column(name = "level3_type", length = 50)
    public String getLevel3Type() {
        return level3Type;
    }
    public void setLevel3Type(String level3Type) {
        this.level3Type = level3Type;
    }
    @Column(name = "level3_type_name", length = 50)
    public String getLevel3TypeName() {
        return level3TypeName;
    }
    public void setLevel3TypeName(String level3TypeName) {
        this.level3TypeName = level3TypeName;
    }
}

+ 96 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/label/SignPatientLabel.java

@ -0,0 +1,96 @@
package com.yihu.wlyy.statistics.model.label;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by lyr on 2016/10/9.
 */
@Entity
@Table(name = "wlyy_sign_patient_label")
public class SignPatientLabel extends IdEntity {
    // 标签code
    private String labelCode;
    // 标签名称
    private String labelName;
    // 标签类型 1:卫计委三大分组 2:健康情况 3:疾病类型 4:自定义
    private String labelType;
    // 是否系统标签
    private Integer isSystem;
    // 创建者
    private String creator;
    // 所属团队code
    private Long teamCode;
    // 排序
    private Integer sort;
    // 状态 0:无效 1:有效
    private Integer status;
    // 操作日期
    private Date czrq;
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public Integer getIsSystem() {
        return isSystem;
    }
    public void setIsSystem(Integer isSystem) {
        this.isSystem = isSystem;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public Long getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(Long teamCode) {
        this.teamCode = teamCode;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 79 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/label/SignPatientLabelInfo.java

@ -0,0 +1,79 @@
package com.yihu.wlyy.statistics.model.label;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by lyr on 2016/10/9.
 */
@Entity
@Table(name = "wlyy_sign_patient_label_info")
public class SignPatientLabelInfo extends IdEntity {
    // 患者code
    private String patient;
    // 患者姓名
    private String pname;
    // 标签code
    private String label;
    // 标签名称
    private String labelName;
    // 标签类型
    private String labelType;
    // 状态 0:无效 1:有效
    private Integer status;
    // 操作日期
    private Date czrq;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 321 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/Patient.java

@ -0,0 +1,321 @@
package com.yihu.wlyy.statistics.model.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
 * 患者信息
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient")
public class Patient extends IdEntity implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8358924836164389434L;
	// 业务主键
	private String code;
	// 身份证号
	private String idcard;
	// 登录密码
	private String password;
	private String salt;
	// 姓名
	private String name;
	// 生日
	private Date birthday;
	// 性別,1男,2女
	private Integer sex;
	// 手機號
	private String mobile;
	// 聯繫電話
	private String phone;
	// 社保卡號
	private String ssc;
	// 頭像HTTP地址
	private String photo;
	// 省代碼
	private String province;
	// 城市代碼
	private String city;
	// 區縣代碼
	private String town;
	// 街道代码
	private String street;
	// 省名
	private String provinceName;
	// 市名
	private String cityName;
	// 區縣名
	private String townName;
	// 街道名称
	private String streetName;
	// 地址
	private String address;
	// 疾病类型,0健康,1高血压,2糖尿病,3高血压+糖尿病
	private Integer disease;
	// 病情:0绿标,1黄标,2红标
	private Integer diseaseCondition;
	// 病历记录总数
	private Integer recordAmount;
	// 總積分
	private Integer points;
	// 更新時間
	private Date czrq;
	// 微信编号
	private String openid;
	// 用户状态:1正常,0禁用,-1恶意注册,2审核中
	private Integer status;
	public Patient() {
	}
	public Patient(Long id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSalt() {
		return salt;
	}
	public void setSalt(String salt) {
		this.salt = salt;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getTown() {
		return town;
	}
	public void setTown(String town) {
		this.town = town;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	@Column(name = "province_name")
	public String getProvinceName() {
		return provinceName;
	}
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	@Column(name = "city_name")
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	@Column(name = "town_name")
	public String getTownName() {
		return townName;
	}
	public void setTownName(String townName) {
		this.townName = townName;
	}
	@Column(name = "street_name")
	public String getStreetName() {
		return streetName;
	}
	public void setStreetName(String streetName) {
		this.streetName = streetName;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getDisease() {
		return disease;
	}
	public void setDisease(Integer disease) {
		this.disease = disease;
	}
	@Column(name = "disease_condition")
	public Integer getDiseaseCondition() {
		return diseaseCondition;
	}
	public void setDiseaseCondition(Integer diseaseCondition) {
		this.diseaseCondition = diseaseCondition;
	}
	@Column(name = "record_amount")
	public Integer getRecordAmount() {
		return recordAmount;
	}
	public void setRecordAmount(Integer recordAmount) {
		this.recordAmount = recordAmount;
	}
	public Integer getPoints() {
		return points;
	}
	public void setPoints(Integer points) {
		this.points = points;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
}

+ 67 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientDisease.java

@ -0,0 +1,67 @@
package com.yihu.wlyy.statistics.model.patient;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
 * 患者疾病。
 *
 * @author lyr
 */
@Entity
@Table(name = "wlyy_patient_disease")
public class PatientDisease extends IdEntity implements Serializable {
    private String patient;         // 患者
    private String disease;         // 疾病代码
    private String diseaseName;     // 疾病名称
    private String del;              // 是否有效 1有效 0无效
    private String signType;        // 签约类型 1:三师 2:家庭
    private Date czrq;              // 操作日期
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getDisease() {
        return disease;
    }
    public void setDisease(String disease) {
        this.disease = disease;
    }
    public String getDiseaseName() {
        return diseaseName;
    }
    public void setDiseaseName(String diseaseName) {
        this.diseaseName = diseaseName;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    public String getSignType() {
        return signType;
    }
    public void setSignType(String signType) {
        this.signType = signType;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 96 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientHealthGuidance.java

@ -0,0 +1,96 @@
package com.yihu.wlyy.statistics.model.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 健康指导
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_guidance")
public class PatientHealthGuidance extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4187769034437765691L;
	// 患者标识
	private String patient;
	// 医生标识
	private String doctor;
	// 指导内容
	private String content;
	// 咨询图片URL,多图以逗号分隔
	private String images;
	// 咨询语音URL
	private String voice;
	// 作废标识:1正常,0作废
	private String del;
	// 添加时间
	private Date czrq;
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getImages() {
		return images;
	}
	public void setImages(String images) {
		this.images = images;
	}
	public String getVoice() {
		return voice;
	}
	public void setVoice(String voice) {
		this.voice = voice;
	}
}

+ 322 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientReservation.java

@ -0,0 +1,322 @@
package com.yihu.wlyy.statistics.model.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 预约挂号记录表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_reservation")
public class PatientReservation extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8452660447546825044L;
	// 预约号/预约流水号
	private String code;
	// 医生标识(医生帮患者预约时才会有值)
	private String doctor;
	// 医生姓名(医生帮患者预约时才会有值)
	private String dname;
	// 患者标识
	private String patient;
	// 患者身份证
	private String idcard;
	// 患者姓名
	private String name;
	// 患者手机号
	private String phone;
	// 患者社保卡号
	private String ssc;
	// 预约时间段:AM (上午)或者PM (下午)
	private String sectionType;
	// 一次预约段的开始时间
	private Date startTime;
	// 一次预约段的结束时间
	private Date endTime;
	// 医生所在医疗机构编码
	private String orgCode;
	// 医疗机构名称
	private String orgName;
	// 科室编码
	private String deptCode;
	// 科室名称
	private String deptName;
	// 专家ID/编码
	private String doctorCode;
	// 专家姓名
	private String doctorName;
	// 专家头像
	private String doctorPhoto;
	// 专家职称
	private String doctorJob;
	// 状态:1预约成功,0预约取消
	private Integer status;
	//取消预约者(状态为预约取消时才有值)
	private String canceler;
	//取消预约者姓名(状态为预约取消时才有值)
	private String cancelerName;
	//取消预约者角色(状态为预约取消时才有值)1专科医生,2全科医生,3健康管理师,4临时专科 5.患者 (与医生服务团队角色一直)
	private Integer cancelerType;
	//取消时间(状态为预约取消时才有值)
	private String cancelerTime;
	// 预约时间
	private Date czrq;
	// 0 健康之路 1智业
	private String type;
	// 签约类型 1三师 2家庭
	private Integer signType;
	// 行政团队
	private Long adminTeamCode;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	@Column(name = "section_type")
	public String getSectionType() {
		return sectionType;
	}
	public void setSectionType(String sectionType) {
		this.sectionType = sectionType;
	}
	@Column(name = "start_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getStartTime() {
		return startTime;
	}
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}
	@Column(name = "end_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEndTime() {
		return endTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	@Column(name = "org_code")
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	@Column(name = "org_name")
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}
	@Column(name = "dept_code")
	public String getDeptCode() {
		return deptCode;
	}
	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}
	@Column(name = "dept_name")
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	@Column(name = "doctor_code")
	public String getDoctorCode() {
		return doctorCode;
	}
	public void setDoctorCode(String doctorCode) {
		this.doctorCode = doctorCode;
	}
	@Column(name = "doctor_name")
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	@Column(name = "doctor_photo")
	public String getDoctorPhoto() {
		return doctorPhoto;
	}
	public void setDoctorPhoto(String doctorPhoto) {
		this.doctorPhoto = doctorPhoto;
	}
	@Column(name = "doctor_job")
	public String getDoctorJob() {
		return doctorJob;
	}
	public void setDoctorJob(String doctorJob) {
		this.doctorJob = doctorJob;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getCanceler() {
		return canceler;
	}
	public void setCanceler(String canceler) {
		this.canceler = canceler;
	}
	@Column(name = "canceler_name")
	public String getCancelerName() {
		return cancelerName;
	}
	public void setCancelerName(String cancelerName) {
		this.cancelerName = cancelerName;
	}
	@Column(name = "canceler_type")
	public Integer getCancelerType() {
		return cancelerType;
	}
	public void setCancelerType(Integer cancelerType) {
		this.cancelerType = cancelerType;
	}
	@Column(name = "canceler_time")
	public String getCancelerTime() {
		return cancelerTime;
	}
	public void setCancelerTime(String cancelerTime) {
		this.cancelerTime = cancelerTime;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public Integer getSignType() {
		return signType;
	}
	public void setSignType(Integer signType) {
		this.signType = signType;
	}
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
}

File diff suppressed because it is too large
+ 256 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/Message.java


+ 454 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamily.java

@ -0,0 +1,454 @@
package com.yihu.wlyy.statistics.model.signfamily;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 家庭签约
 * @author George
 */
@Entity
@Table(name = "wlyy_sign_family")
public class SignFamily extends IdEntity {
	private static final long serialVersionUID = 364799142991631092L;
	private String code;        // 签约标识
	private String lwCode;      // 两网标识
	private Integer type;       // 签约类型:1三师签约,2网络签约
	private String patient;     // 患者标识
	private String openid;      // 微信OPENID
	private String name;        // 患者姓名
	private String idcard;      // 身份证号
	private String ssc;         // 社保卡号
	private String mobile;      // 手机号
	private String emerMobile;  // 紧急联系人手机号
	private String hospital;    // 签约医院标识
	private String hospitalName;    // 签约医院名称
	private String doctor;      // 全科医生
	private String doctorName;  // 全科医生姓名
	private String doctorHealth;    // 健康管理师
	private String doctorHealthName;    // 健康管理师姓名
	private Date begin;         // 签约开始日期
	private Date end;           // 签约结束日期
	private Integer status;     // 签约状态(-1患者已取消,-2已拒绝,-3已解约,-4已到期,0待签约,1已签约,2患者申请取消签约
	private String images;      // 签约图片附件URL,多图以逗号分隔
	private String reason;      // 解约原因
	private Date czrq;          // 操作时间
	private String teamCode;
	private Date applyDate;     //签约时间
	private Date applyUnsignDate;//解约时间
	private Date patientApplyDate;//患者发起签约时间
	private Date patientApplyUnsignDate;//患者发起解约时间
	private String signType;//1 用户自己申请  2医生手工带签  3.医生发起邀请
	private String familyCode;//签约code
	private Double expenses;//签约费用
	private String expensesStatus;//扣费状态【0未扣费 1已扣费 2已退费】
	private String signSource;// 签约来源【1 社区签约 2 移动签约】
	private String signDoctorCode;//簽約人code
	private String signDoctorName;//簽約人銘
	private String signDoctorLevel;//簽約人等级
	private String expensesType;//补贴类型(4种类型:01无补贴,02全部贴,03补个人承担部分(20),04补统筹基金(70))
	private String signYear;//签约年度
	private String medicalInsuranceNum;//医保流水号
	private String agentDoctorCode;//代理簽約人code
	private String agentDoctorName;//代理簽約人銘
	private String agentDoctorLevel;//代理簽約人等级
	private Long adminTeamCode;//行政团队ID
	private Date expensesTime;//缴费时间
	private String serverType;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getLwCode() {
		return lwCode;
	}
	public void setLwCode(String lwCode) {
		this.lwCode = lwCode;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	@Column(name = "emer_mobile")
	public String getEmerMobile() {
		return emerMobile;
	}
	public void setEmerMobile(String emerMobile) {
		this.emerMobile = emerMobile;
	}
	public String getHospital() {
		return hospital;
	}
	public void setHospital(String hospital) {
		this.hospital = hospital;
	}
	@Column(name = "hospital_name")
	public String getHospitalName() {
		return hospitalName;
	}
	public void setHospitalName(String hospitalName) {
		this.hospitalName = hospitalName;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	@Column(name = "doctor_name")
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	@Column(name = "doctor_health")
	public String getDoctorHealth() {
		return doctorHealth;
	}
	public void setDoctorHealth(String doctorHealth) {
		this.doctorHealth = doctorHealth;
	}
	@Column(name = "doctor_health_name")
	public String getDoctorHealthName() {
		return doctorHealthName;
	}
	public void setDoctorHealthName(String doctorHealthName) {
		this.doctorHealthName = doctorHealthName;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBegin() {
		return begin;
	}
	public void setBegin(Date begin) {
		this.begin = begin;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getEnd() {
		return end;
	}
	public void setEnd(Date end) {
		this.end = end;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getImages() {
		return images;
	}
	public void setImages(String images) {
		this.images = images;
	}
	public String getReason() {
		return reason;
	}
	public void setReason(String reason) {
		this.reason = reason;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	@Column(name = "team_code")
	public String getTeamCode() {
		return teamCode;
	}
	public void setTeamCode(String teamCode) {
		this.teamCode = teamCode;
	}
	@Column(name = "sign_type")
	public String getSignType() {
		return signType;
	}
	public void setSignType(String signType) {
		this.signType = signType;
	}
	@Column(name = "apply_date")
	public Date getApplyDate() {
		return applyDate;
	}
	public void setApplyDate(Date applyDate) {
		this.applyDate = applyDate;
	}
	@Column(name = "patient_apply_date")
	public Date getPatientApplyDate() {
		return patientApplyDate;
	}
	public void setPatientApplyDate(Date patientApplyDate) {
		this.patientApplyDate = patientApplyDate;
	}
	@Column(name = "patient_apply_unsgin_date")
	public Date getPatientApplyUnsignDate() {
		return patientApplyUnsignDate;
	}
	public void setPatientApplyUnsignDate(Date patientApplyUnsignDate) {
		this.patientApplyUnsignDate = patientApplyUnsignDate;
	}
	@Column(name = "family_code")
	public String getFamilyCode() {
		return familyCode;
	}
	public void setFamilyCode(String familyCode) {
		this.familyCode = familyCode;
	}
	@Column(name = "expenses")
	public Double getExpenses() {
		return expenses;
	}
	public void setExpenses(Double expenses) {
		this.expenses = expenses;
	}
	@Column(name = "sign_doctor_code")
	public String getSignDoctorCode() {
		return signDoctorCode;
	}
	public void setSignDoctorCode(String signDoctorCode) {
		this.signDoctorCode = signDoctorCode;
	}
	@Column(name = "sign_doctor_name")
	public String getSignDoctorName() {
		return signDoctorName;
	}
	public void setSignDoctorName(String signDoctorName) {
		this.signDoctorName = signDoctorName;
	}
	@Column(name = "sign_doctor_level")
	public String getSignDoctorLevel() {
		return signDoctorLevel;
	}
	public void setSignDoctorLevel(String signDoctorLevel) {
		this.signDoctorLevel = signDoctorLevel;
	}
	@Column(name = "apply_unsign_date")
	public Date getApplyUnsignDate() {
		return applyUnsignDate;
	}
	public void setApplyUnsignDate(Date applyUnsignDate) {
		this.applyUnsignDate = applyUnsignDate;
	}
	@Column(name = "expenses_type")
	public String getExpensesType() {
		return expensesType;
	}
	public void setExpensesType(String expensesType) {
		this.expensesType = expensesType;
	}
	@Column(name = "sign_year")
	public String getSignYear() {
		return signYear;
	}
	public void setSignYear(String signYear) {
		this.signYear = signYear;
	}
	@Column(name = "medical_insurance_num")
	public String getMedicalInsuranceNum() {
		return medicalInsuranceNum;
	}
	public void setMedicalInsuranceNum(String medicalInsuranceNum) {
		this.medicalInsuranceNum = medicalInsuranceNum;
	}
	@Column(name = "agent_doctor_code")
	public String getAgentDoctorCode() {
		return agentDoctorCode;
	}
	public void setAgentDoctorCode(String agentDoctorCode) {
		this.agentDoctorCode = agentDoctorCode;
	}
	@Column(name = "agent_doctor_name")
	public String getAgentDoctorName() {
		return agentDoctorName;
	}
	public void setAgentDoctorName(String agentDoctorName) {
		this.agentDoctorName = agentDoctorName;
	}
	@Column(name = "agent_doctor_level")
	public String getAgentDoctorLevel() {
		return agentDoctorLevel;
	}
	public void setAgentDoctorLevel(String agentDoctorLevel) {
		this.agentDoctorLevel = agentDoctorLevel;
	}
	@Column(name = "expenses_status")
	public String getExpensesStatus() {
		return expensesStatus;
	}
	public void setExpensesStatus(String expensesStatus) {
		this.expensesStatus = expensesStatus;
	}
	@Column(name = "sign_source")
	public String getSignSource() {
		return signSource;
	}
	public void setSignSource(String signSource) {
		this.signSource = signSource;
	}
	@Column(name = "admin_team_code")
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	@Override
	public String toString() {
		return "SignFamily{" +
				"code='" + code + '\'' +
				", expensesStatus='" + expensesStatus + '\'' +
				", hospital='" + hospital + '\'' +
				", adminTeamCode=" + adminTeamCode +
				'}';
	}
	public Date getExpensesTime() {
		return expensesTime;
	}
	public void setExpensesTime(Date expensesTime) {
		this.expensesTime = expensesTime;
	}
	public String getServerType() {
		return serverType;
	}
	public void setServerType(String serverType) {
		this.serverType = serverType;
	}
}

+ 539 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamilyRenew.java

@ -0,0 +1,539 @@
package com.yihu.wlyy.statistics.model.signfamily;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 家庭签约
 *
 * @author George
 */
@Entity
@Table(name = "wlyy_sign_family_renew")
public class SignFamilyRenew extends IdEntity {
    private static final long serialVersionUID = 364799142991631092L;
    private String code;        // 签约标识
    private String lwCode;      // 两网标识
    private Integer type;       // 签约类型:1三师签约,2网络签约
    private String patient;     // 患者标识
    private String openid;      // 微信OPENID
    private String name;        // 患者姓名
    private String idcard;      // 身份证号
    private String ssc;         // 社保卡号
    private String mobile;      // 手机号
    private String emerMobile;  // 紧急联系人手机号
    private String hospital;    // 签约医院标识
    private String hospitalName;    // 签约医院名称
    private String doctor;      // 全科医生
    private String doctorName;  // 全科医生姓名
    private String doctorHealth;    // 健康管理师
    private String doctorHealthName;    // 健康管理师姓名
    private Date begin;         // 签约开始日期
    private Date end;           // 签约结束日期
    private Integer status;     // 签约状态(-1患者已取消,-2已拒绝,-3已解约,-4已到期,0待签约,1已签约,2患者申请取消签约
    private String images;      // 签约图片附件URL,多图以逗号分隔
    private String reason;      // 解约原因
    private Date czrq;          // 操作时间
    private String teamCode;
    private Date applyDate;     //签约时间
    private Date applyUnsignDate;//解约时间
    private Date patientApplyDate;//患者发起签约时间
    private Date patientApplyUnsignDate;//患者发起解约时间
    private String signType;//1 用户自己申请  2医生手工带签  3.医生发起邀请
    private String familyCode;//签约code
    private Double expenses;//签约费用
    private String expensesStatus;//扣费状态【0未扣费 1已扣费 2已退费】
    private String signSource;// 签约来源【1 社区签约 2 移动签约】
    private String signDoctorCode;//簽約人code
    private String signDoctorName;//簽約人銘
    private String signDoctorLevel;//簽約人等级
    private String expensesType;//补贴类型(4种类型:01无补贴,02全部贴,03补个人承担部分(20),04补统筹基金(70))
    private String signYear;//签约年度
    private String medicalInsuranceNum;//医保流水号
    private String agentDoctorCode;//代理簽約人code
    private String agentDoctorName;//代理簽約人銘
    private String agentDoctorLevel;//代理簽約人等级
    private Long adminTeamId;//行政团队ID
    private Date expensesTime;//缴费时间
    private Integer isValid;//是否生效
    private String renewFlag;//1 医生续签 2 医生改签续签
    private String renewChangeReason;//原因
    //1.3.3.2新增字段
    //基卫服务类型
    private String serverType;
    //基卫服务类型名称
    private String serverTypeName;
    //基卫特殊人群类别
    private String specialPopulation;
    //基卫特殊人群类别名称
    private String specialPopulationName;
    public String getRenewFlag() {
        return renewFlag;
    }
    public void setRenewFlag(String renewFlag) {
        this.renewFlag = renewFlag;
    }
    public String getServerType() {
        return serverType;
    }
    public void setServerType(String serverType) {
        this.serverType = serverType;
    }
    public String getServerTypeName() {
        return serverTypeName;
    }
    public void setServerTypeName(String serverTypeName) {
        this.serverTypeName = serverTypeName;
    }
    public String getSpecialPopulation() {
        return specialPopulation;
    }
    public void setSpecialPopulation(String specialPopulation) {
        this.specialPopulation = specialPopulation;
    }
    public String getSpecialPopulationName() {
        return specialPopulationName;
    }
    public void setSpecialPopulationName(String specialPopulationName) {
        this.specialPopulationName = specialPopulationName;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getLwCode() {
        return lwCode;
    }
    public void setLwCode(String lwCode) {
        this.lwCode = lwCode;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    @Column(name = "emer_mobile")
    public String getEmerMobile() {
        return emerMobile;
    }
    public void setEmerMobile(String emerMobile) {
        this.emerMobile = emerMobile;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "hospital_name")
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "doctor_health")
    public String getDoctorHealth() {
        return doctorHealth;
    }
    public void setDoctorHealth(String doctorHealth) {
        this.doctorHealth = doctorHealth;
    }
    @Column(name = "doctor_health_name")
    public String getDoctorHealthName() {
        return doctorHealthName;
    }
    public void setDoctorHealthName(String doctorHealthName) {
        this.doctorHealthName = doctorHealthName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getBegin() {
        return begin;
    }
    public void setBegin(Date begin) {
        this.begin = begin;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getEnd() {
        return end;
    }
    public void setEnd(Date end) {
        this.end = end;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getReason() {
        return reason;
    }
    public void setReason(String reason) {
        this.reason = reason;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "team_code")
    public String getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(String teamCode) {
        this.teamCode = teamCode;
    }
    @Column(name = "sign_type")
    public String getSignType() {
        return signType;
    }
    public void setSignType(String signType) {
        this.signType = signType;
    }
    @Column(name = "apply_date")
    public Date getApplyDate() {
        return applyDate;
    }
    public void setApplyDate(Date applyDate) {
        this.applyDate = applyDate;
    }
    @Column(name = "patient_apply_date")
    public Date getPatientApplyDate() {
        return patientApplyDate;
    }
    public void setPatientApplyDate(Date patientApplyDate) {
        this.patientApplyDate = patientApplyDate;
    }
    @Column(name = "patient_apply_unsgin_date")
    public Date getPatientApplyUnsignDate() {
        return patientApplyUnsignDate;
    }
    public void setPatientApplyUnsignDate(Date patientApplyUnsignDate) {
        this.patientApplyUnsignDate = patientApplyUnsignDate;
    }
    @Column(name = "family_code")
    public String getFamilyCode() {
        return familyCode;
    }
    public void setFamilyCode(String familyCode) {
        this.familyCode = familyCode;
    }
    @Column(name = "expenses")
    public Double getExpenses() {
        return expenses;
    }
    public void setExpenses(Double expenses) {
        this.expenses = expenses;
    }
    @Column(name = "sign_doctor_code")
    public String getSignDoctorCode() {
        return signDoctorCode;
    }
    public void setSignDoctorCode(String signDoctorCode) {
        this.signDoctorCode = signDoctorCode;
    }
    @Column(name = "sign_doctor_name")
    public String getSignDoctorName() {
        return signDoctorName;
    }
    public void setSignDoctorName(String signDoctorName) {
        this.signDoctorName = signDoctorName;
    }
    @Column(name = "sign_doctor_level")
    public String getSignDoctorLevel() {
        return signDoctorLevel;
    }
    public void setSignDoctorLevel(String signDoctorLevel) {
        this.signDoctorLevel = signDoctorLevel;
    }
    @Column(name = "apply_unsign_date")
    public Date getApplyUnsignDate() {
        return applyUnsignDate;
    }
    public void setApplyUnsignDate(Date applyUnsignDate) {
        this.applyUnsignDate = applyUnsignDate;
    }
    @Column(name = "expenses_type")
    public String getExpensesType() {
        return expensesType;
    }
    public void setExpensesType(String expensesType) {
        this.expensesType = expensesType;
    }
    @Column(name = "sign_year")
    public String getSignYear() {
        return signYear;
    }
    public void setSignYear(String signYear) {
        this.signYear = signYear;
    }
    @Column(name = "medical_insurance_num")
    public String getMedicalInsuranceNum() {
        return medicalInsuranceNum;
    }
    public void setMedicalInsuranceNum(String medicalInsuranceNum) {
        this.medicalInsuranceNum = medicalInsuranceNum;
    }
    @Column(name = "agent_doctor_code")
    public String getAgentDoctorCode() {
        return agentDoctorCode;
    }
    public void setAgentDoctorCode(String agentDoctorCode) {
        this.agentDoctorCode = agentDoctorCode;
    }
    @Column(name = "agent_doctor_name")
    public String getAgentDoctorName() {
        return agentDoctorName;
    }
    public void setAgentDoctorName(String agentDoctorName) {
        this.agentDoctorName = agentDoctorName;
    }
    @Column(name = "agent_doctor_level")
    public String getAgentDoctorLevel() {
        return agentDoctorLevel;
    }
    public void setAgentDoctorLevel(String agentDoctorLevel) {
        this.agentDoctorLevel = agentDoctorLevel;
    }
    @Column(name = "expenses_status")
    public String getExpensesStatus() {
        return expensesStatus;
    }
    public void setExpensesStatus(String expensesStatus) {
        this.expensesStatus = expensesStatus;
    }
    @Column(name = "sign_source")
    public String getSignSource() {
        return signSource;
    }
    public void setSignSource(String signSource) {
        this.signSource = signSource;
    }
    @Column(name = "admin_team_code")
    public Long getAdminTeamId() {
        return adminTeamId;
    }
    public void setAdminTeamId(Long adminTeamId) {
        this.adminTeamId = adminTeamId;
    }
    @Override
    public String toString() {
        return "SignFamily{" +
                "code='" + code + '\'' +
                ", lwCode='" + lwCode + '\'' +
                ", type=" + type +
                ", patient='" + patient + '\'' +
                ", openid='" + openid + '\'' +
                ", name='" + name + '\'' +
                ", idcard='" + idcard + '\'' +
                ", ssc='" + ssc + '\'' +
                ", mobile='" + mobile + '\'' +
                ", emerMobile='" + emerMobile + '\'' +
                ", hospital='" + hospital + '\'' +
                ", hospitalName='" + hospitalName + '\'' +
                ", doctor='" + doctor + '\'' +
                ", doctorName='" + doctorName + '\'' +
                ", doctorHealth='" + doctorHealth + '\'' +
                ", doctorHealthName='" + doctorHealthName + '\'' +
                ", begin=" + begin +
                ", end=" + end +
                ", status=" + status +
                ", images='" + images + '\'' +
                ", reason='" + reason + '\'' +
                ", czrq=" + czrq +
                ", teamCode='" + teamCode + '\'' +
                ", applyDate=" + applyDate +
                ", signType='" + signType + '\'' +
                ", familyCode='" + familyCode + '\'' +
                '}';
    }
    public Date getExpensesTime() {
        return expensesTime;
    }
    public void setExpensesTime(Date expensesTime) {
        this.expensesTime = expensesTime;
    }
    @Column(name="is_valid")
    public Integer getIsValid() {
        return isValid;
    }
    public void setIsValid(Integer isValid) {
        this.isValid = isValid;
    }
    public String getRenewChangeReason() {
        return renewChangeReason;
    }
    public void setRenewChangeReason(String renewChangeReason) {
        this.renewChangeReason = renewChangeReason;
    }
}

+ 57 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/system/City.java

@ -0,0 +1,57 @@
package com.yihu.wlyy.statistics.model.system;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 城市信息對象
 * @author George
 *
 */
@Entity
@Table(name = "dm_city")
public class City extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 366338400555505599L;
	
	// 省編碼
	private String province;
	// 城市編碼
	private String code;
	// 城市名稱
	private String name;
	public City() {
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

+ 78 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/system/Town.java

@ -0,0 +1,78 @@
package com.yihu.wlyy.statistics.model.system;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 區縣信息對象
 * @author George
 *
 */
@Entity
@Table(name = "dm_town")
public class Town extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3851597133734507811L;
	
	// 省編碼
	private String province;
	// 城市編碼
	private String city;
	// 區縣編碼
	private String code;
	// 區縣名稱
	private String name;
	private String photo;
	public Town() {
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
}

+ 107 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/AdminTeam.java

@ -0,0 +1,107 @@
package com.yihu.wlyy.statistics.model.team;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * 医生行政团队。
 *
 * @author Sand
 */
@Entity
@Table(name = "wlyy_admin_team")
public class AdminTeam extends IdEntity {
    private String name;
    private Date createTime;
    private String leaderCode;
    private boolean available;
    private String orgCode;
    private String orgName;
    private String townCode;
    private String townName;
    public String getName() {
        return name;
    }
    @Column(name = "name")
    public void setName(String name) {
        this.name = name;
    }
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    @Column(name = "create_time")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getOrgCode() {
        return orgCode;
    }
    @Column(name = "org_code")
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    public String getLeaderCode() {
        return leaderCode;
    }
    @Column(name = "leader_id")
    public void setLeaderCode(String leaderCode) {
        this.leaderCode = leaderCode;
    }
    public boolean isAvailable() {
        return available;
    }
    @Column(name = "available")
    public void setAvailable(boolean available) {
        this.available = available;
    }
    @Transient
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    @Transient
    public String getTownCode() {
        return townCode;
    }
    public void setTownCode(String townCode) {
        this.townCode = townCode;
    }
    @Transient
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
}

+ 68 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/DoctorTeam.java

@ -0,0 +1,68 @@
package com.yihu.wlyy.statistics.model.team;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 三师团队/医生签约团队
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_doctor_team")
public class DoctorTeam extends IdEntity {
	private static final long serialVersionUID = 715817516721723210L;
	private String code;    // 组标识
	private String name;    // 组名
	private Date czrq;      // 更新时间
	private String del;     // 是否作废,1正常,0作废
	private String signType;//签约类型(1表示三师签约,2表示家庭签约)
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@Column(name = "sign_type")
	public String getSignType() {
		return signType;
	}
	public void setSignType(String signType) {
		this.signType = signType;
	}
}

+ 130 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/model/team/DoctorTeamMember.java

@ -0,0 +1,130 @@
package com.yihu.wlyy.statistics.model.team;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.Date;
/**
 * 医生签约团队成员。
 *
 * @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "wlyy_doctor_team_member")
public class DoctorTeamMember extends IdEntity {
    // Fields
    private String team;
    private String memberCode;
    private String code;
    private String name;
    private Integer type;//医生类型:1专科医生,2全科医生,3健康管理师,4临时专科 5.患者
    private Date czrq;
    private String del;//是否作废,1正常,0作废
    private String signType;//签约类型(1表示三师签约,2表示家庭签约)
    /**
     * default constructor
     */
    public DoctorTeamMember() {
    }
    /**
     * minimal constructor
     */
    public DoctorTeamMember(String team, String doctor, Integer type,
                            Timestamp czrq) {
        this.team = team;
        this.type = type;
        this.czrq = czrq;
    }
    /**
     * full constructor
     */
    public DoctorTeamMember(String team, String doctor, String name,
                            Integer type, Timestamp czrq, String del) {
        this.team = team;
        this.name = name;
        this.type = type;
        this.czrq = czrq;
        this.del = del;
    }
    @Column(name = "team", nullable = false, length = 50)
    public String getTeam() {
        return this.team;
    }
    public void setTeam(String team) {
        this.team = team;
    }
    @Column(name = "member_code", nullable = false, length = 50)
    public String getMemberCode() {
        return memberCode;
    }
    public void setMemberCode(String memberCode) {
        this.memberCode = memberCode;
    }
    @Column(name = "name", length = 50)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "type", nullable = false)
    public Integer getType() {
        return this.type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "czrq", nullable = false, length = 0)
    public Date getCzrq() {
        return this.czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "del", length = 1)
    public String getDel() {
        return this.del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "sign_type")
    public String getSignType() {
        return signType;
    }
    public void setSignType(String signType) {
        this.signType = signType;
    }
}

+ 306 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/DoctorWorkTimeService.java

@ -0,0 +1,306 @@
package com.yihu.wlyy.statistics.service;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.DoctorWorkTimeDao;
import com.yihu.wlyy.statistics.dao.DoctorWorkWeekDao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkTime;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkWeek;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生工作排班
 * <p>
 * Created by lyr on 2016/08/19.
 */
@Service
@Transactional
public class DoctorWorkTimeService {
    static Object obj = new Object();
    @Autowired
    private DoctorWorkTimeDao doctorWorkTimeDao;
    @Autowired
    private DoctorWorkWeekDao doctorWorkWeekDao;
    @Autowired
    private DoctorDao doctorDao;
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public JSONObject findDoctorWeekWorkTime(String doctor, String week) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        result.put("workTime", workTime != null ? new JSONObject(workTime) : "");
        result.put("workWeek", workWeek != null ? new JSONObject(workWeek) : "");
        return result;
    }
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public Map<String, Object> findDoctorWeekWork(String doctor, String week) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("doctor-worktime-error:doctor not exist");
        }
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        map.put("workTime", workTime);
        map.put("workWeek", workWeek);
        return map;
    }
    /**
     * 医生是否在工作
     *
     * @param doctor 医生
     * @return
     */
    public JSONObject isDoctorWorking(String doctor, Integer week) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        if (week < 0) {
            week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 0) {
                week = 7;
            }
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("msg", "医生当前接受咨询");
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                // 医生设置不接受咨询
                json.put("status", "0");
                json.put("msg", "医生不接受咨询");
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("msg", "医生当前接受咨询");
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        if (flag == 1) {
                            json.put("status", "1");
                            json.put("msg", "医生当前接受咨询");
                        } else {
                            json.put("status", "2");
                            json.put("msg", "医生当前不在工作时间");
                        }
                    } else {
                        json.put("status", "2");
                        json.put("msg", "医生当前不在工作时间");
                    }
                }
            }
        }
        return json;
    }
    public Date getDoctorWeek(String doctor, Integer week) throws Exception {
        Date json = new Date();
        Calendar calendar = Calendar.getInstance();
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            return json;
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                return null;
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    return json;
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                               String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                               preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                                preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                                preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                    } else {
                        return null;
                    }
                }
            }
        }
        return null;
    }
    /**
     * 得到医生的下次工作时间
     *
     * @param doctor
     * @return
     * @throws Exception
     */
    public Date getDoctorNextWork(String doctor) throws Exception {
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        //得到今天的是否有工作
        Date date=getDoctorWeek(doctor,week);
        if(date==null){
            //如果工作时间遍历得到最新的一天的时间
            for(int i=1;i<8;i++){
                int weekTemp=(i+week)%7;
                if(weekTemp==0){
                    weekTemp=7;
                }
                date=getDoctorWeek(doctor,weekTemp);
            }
        }
        return date;
    }
}

+ 446 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java

@ -0,0 +1,446 @@
package com.yihu.wlyy.statistics.service;
import com.yihu.wlyy.statistics.dao.DoctorPatientGroupInfoDao;
import com.yihu.wlyy.statistics.dao.QuartzJobConfigDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.job.check.CheckSignJob;
import com.yihu.wlyy.statistics.job.message.FollowupPlanJob;
import com.yihu.wlyy.statistics.job.message.HealthMessageJob;
import com.yihu.wlyy.statistics.job.message.NoticeJob;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import com.yihu.wlyy.statistics.util.QuartzHelper;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author chenweida
 */
@Service
public class JobService {
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private QuartzJobConfigDao wlyyJobConfigDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Transactional
    public void stopById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "1");
        if (quartzJobConfig != null) {
            for (int j = 1; j <= 2; j++) {
                quartzHelper.removeJob(quartzJobConfig.getId() + "-" + j);
                quartzJobConfig.setStatus("0");
            }
        } else {
            throw new Exception("任务已经停止");
        }
    }
    @Transactional
    public void startById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "0");
        if (quartzJobConfig != null) {
            startOneJob(quartzJobConfig);
        } else {
            throw new Exception("任务已经启动");
        }
    }
    @Transactional
    public void stopAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("1");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                for (int j = 1; j <= 2; j++) {
                    quartzHelper.removeJob(quartzJobConfig.getId() + "-" + j);
                    quartzJobConfig.setStatus("0");
                }
            }
        } else {
            throw new Exception("任务已经全部停止");
        }
    }
    @Transactional
    public void startAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("0");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                startOneJob(quartzJobConfig);
            }
        } else {
            throw new Exception("任务已经全部启动");
        }
    }
    /**
     * 启动单个任务
     *
     * @param quartzJobConfig
     * @throws Exception
     */
    private void startOneJob(QuartzJobConfig quartzJobConfig) throws Exception {
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", wlyyJobConfigVO);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            for (int j = 1; j <= 2; j++) {
                //往quartz框架添加任务
                quartzHelper.addJob(getRightClass(quartzJobConfig), quartzJobConfig.getQuartzCron(), quartzJobConfig.getId() + "-" + j, params);
                quartzJobConfig.setStatus("1");//设置任务状态是启动 }
            }
        }
    }
    public void startNowById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findOne(id);
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", wlyyJobConfigVO);
        for (int i = 2; i <= 2; i++) {
            params.put("timeLevel", i + "");
            //往quartz框架添加任务
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            }
        }
    }
    public void productDataByDay(Integer day) throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                for (int j = 2; j <= 2; j++) {
                    params.put("timeLevel", j + "");
                    //往quartz框架添加任务
                    params.put("daybefore", getYesterday(0 - i - 1));
                    params.put("yesterday", getYesterday(0 - i));
                    if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                        quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                       Thread.sleep(6000L);
                    }
                }
            }
        }
    }
    public static String getYesterday(Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public void productDataByOneDay(String yesterday) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("jobConfig", wlyyJobConfigVO);
            //往quartz框架添加任务
            params.put("daybefore", daybefore);
            params.put("yesterday", yesterday);
            for (int j = 1; j <= 2; j++) {
                params.put("timeLevel", j + "");
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                    Thread.sleep(6000L);
                }
            }
        }
    }
    /**
     * @param quartzJobConfig
     * @return
     * @throws ClassNotFoundException
     */
    private Class getRightClass(QuartzJobConfig quartzJobConfig) throws ClassNotFoundException {
        return Class.forName(quartzJobConfig.getJobClass());
    }
    public void productDataByOneDayWithId(String yesterday, String id) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
        }
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        params.put("daybefore", daybefore);
        params.put("yesterday", yesterday);
        for (int j = 1; j <= 2; j++) {
            params.put("timeLevel", j + "");
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                Thread.sleep(6000L);
            }
        }
    }
    @Transactional
    @Async("dbExtractExecutor")
    public void startaaaa() throws Exception {
        quartzHelper.startNow(HealthMessageJob.class, UUID.randomUUID().toString().replace("-", ""), new HashMap<>());
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
        }
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", wlyyJobConfigVO);
        for (int i = 1; i <= day; i++) {
            //往quartz框架添加任务
            params.put("daybefore", getYesterday(0 - i - 1));
            params.put("yesterday", getYesterday(0 - i));
            for (int j = 1; j <= 2; j++) {
                params.put("timeLevel", j + "");
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                    Thread.sleep(6000L);
                }
            }
        }
    }
    public void startCheckSignJob() throws Exception {
        if (!quartzHelper.isExistJob(CheckSignJob.jobKey)) {
            quartzHelper.addJob(CheckSignJob.class, CheckSignJob.cron, CheckSignJob.jobKey, new HashMap<>());
        }
    }
    public void stopCheckSignJob() throws Exception {
        if (quartzHelper.isExistJob(CheckSignJob.jobKey)) {
            quartzHelper.removeJob(CheckSignJob.jobKey);
        }
    }
    public void productDataByDayToDay(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDay(getYesterday(i, startDate));
        }
    }
    public static String getYesterday(Integer day, Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.add(Calendar.DAY_OF_MONTH, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    public void productDataByDayToDayAndId(String start, String end, String id) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDayWithId(getYesterday(i, startDate), id);
        }
    }
    public void startHealthMessageJob() throws Exception {
        if (!quartzHelper.isExistJob(HealthMessageJob.jobKey)) {
            quartzHelper.addJob(HealthMessageJob.class, HealthMessageJob.cron, HealthMessageJob.jobKey, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopHealthMessageJob() throws Exception {
        if (quartzHelper.isExistJob(HealthMessageJob.jobKey)) {
            quartzHelper.removeJob(HealthMessageJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }
    public void productHealthDataByOneDay(String day) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(day);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        Map<String, Object> params = new HashMap<String, Object>();
        //往quartz框架添加任务
        params.put("now", yesterday);
        params.put("yesterday", day);
        quartzHelper.startNow(HealthMessageJob.class, HealthMessageJob.jobKey + UUID.randomUUID().toString().replace("-", ""), params);
        //Thread.sleep(40000L);
    }
    public void productHealthDataByDayToDay(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productHealthDataByOneDay(getYesterday(i, startDate));
        }
    }
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse("2016-10-20");
        Date endDate = sdf.parse("2016-10-28");
        System.out.println(daysBetween(startDate, endDate));
        System.out.println(getYesterday(0, startDate));
    }
    public void startNoticeJob() throws Exception {
        if (!quartzHelper.isExistJob(NoticeJob.jobKey)) {
            quartzHelper.addJob(NoticeJob.class, NoticeJob.jobCron, NoticeJob.jobKey, new HashMap<>());
            // quartzHelper.startNow(NoticeJob.class, UUID.randomUUID().toString().replace("-", ""), new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopNoticeJob() throws Exception {
        if (quartzHelper.isExistJob(NoticeJob.jobKey)) {
            quartzHelper.removeJob(NoticeJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }
    /*******************************
     * 随访计划任务
     *******************************************************/
    @Value("${spring.followupMessage.jobId}")
    private String followupJob;
    @Value("${spring.followupMessage.cron}")
    private String followupJobCron;
    public void startFollowupPlantJob() throws Exception {
        if (!quartzHelper.isExistJob(followupJob)) {
            quartzHelper.addJob(FollowupPlanJob.class, followupJobCron, followupJob, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopFollowupPlantJob() throws Exception {
        if (quartzHelper.isExistJob(followupJob)) {
            quartzHelper.removeJob(followupJob);
        } else {
            throw new Exception("已经停止");
        }
    }
    public void startNoticeJobNow() throws Exception {
        quartzHelper.startNow(NoticeJob.class, UUID.randomUUID().toString(), new HashMap<>());
    }
    public void startHealthMessageJobNow() throws Exception {
        quartzHelper.startNow(HealthMessageJob.class, UUID.randomUUID().toString(), new HashMap<>());
    }
}

+ 96 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PatientDiseaseToLabel.java

@ -0,0 +1,96 @@
package com.yihu.wlyy.statistics.task;
import com.yihu.wlyy.statistics.Application;
import com.yihu.wlyy.statistics.dao.PatientDiseaseDao;
import com.yihu.wlyy.statistics.dao.SignPatientLabelInfoDao;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.model.patient.PatientDisease;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by lyr-pc on 2016/10/13.
 */
public class PatientDiseaseToLabel implements Runnable {
    long start = 1;
    PatientDiseaseDao diseaseDao;
    SignPatientLabelInfoDao labelInfoDao;
    JpaTransactionManager transactionManager;
    public PatientDiseaseToLabel(Long start) {
        this.start = start;
        this.diseaseDao = SpringUtil.getApplicationContext().getBean(PatientDiseaseDao.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
    }
    @Override
    public void run() {
        boolean flag = true;
        while (flag) {
            PageRequest pageRequest = new PageRequest(0, 500);
            Page<PatientDisease> diseases = diseaseDao.findByIdRange(start, pageRequest);
            if (diseases != null && diseases.getContent().size() < 500) {
                flag = false;
            }
            start = diseases.getContent().get(diseases.getContent().size() - 1).getId() + 1;
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务
            TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
            try {
                diseasesToLabel(diseases);
                //事物提交
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
            }
        }
    }
    void diseasesToLabel(Page<PatientDisease> diseases) {
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        Map<String, SignPatientLabelInfo> labelInfos = new HashMap<>();
        for (PatientDisease disease : diseases.getContent()) {
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            SignPatientLabelInfo exLabelInfo = labelInfoDao.findByPatientAndLabelAndLabelTypeAndStatus(
                    disease.getPatient(), disease.getDisease(), "3", 1);
            if (exLabelInfo != null) {
                continue;
            }
            labelInfo.setPatient(disease.getPatient());
            labelInfo.setLabel(disease.getDisease());
            labelInfo.setLabelName(disease.getDiseaseName());
            labelInfo.setLabelType("3");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            labelInfos.put(disease.getPatient() + disease.getDisease(), labelInfo);
        }
        labelInfoDao.save(labelInfos.values());
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}

+ 156 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PatientGroupToLabelRunnable.java

@ -0,0 +1,156 @@
package com.yihu.wlyy.statistics.task;
import com.yihu.wlyy.statistics.Application;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.label.SignPatientLabel;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by lyr-pc on 2016/10/12.
 */
public class PatientGroupToLabelRunnable implements Runnable {
    long start = 0;
    long end = 0;
    DoctorPatientGroupInfoDao groupInfoDao;
    SignPatientLabelInfoDao labelInfoDao;
    JpaTransactionManager transactionManager;
    public PatientGroupToLabelRunnable(Long start, Long end) {
        this.start = start;
        this.end = end;
        this.groupInfoDao = SpringUtil.getApplicationContext().getBean(DoctorPatientGroupInfoDao.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
    }
    @Override
    public void run() {
        boolean flag = true;
        while (flag) {
            PageRequest pageRequest = new PageRequest(0, 100);
            Page<DoctorPatientGroupInfo> groups = groupInfoDao.findByIdRange(start, end, pageRequest);
            if (groups != null && groups.getContent().size() < 100) {
                flag = false;
            }
            start = groups.getContent().get(groups.getContent().size() - 1).getId() + 1;
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务
            TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
            try {
                groupToLabel(groups);
                //事物提交
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
            }
        }
    }
    void groupToLabel(Page<DoctorPatientGroupInfo> groups) {
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        Map<String, SignPatientLabelInfo> normalLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> healthMap = new HashMap<>();
        List<DoctorPatientGroupInfo> groupInfos = groups.getContent();
        for (DoctorPatientGroupInfo groupInfo : groupInfos) {
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            labelInfo.setPatient(groupInfo.getPatient());
            labelInfo.setPname(groupInfo.getPname());
            if (groupInfo.getGroup().equals("1")) {
                labelInfo.setLabel("1");
                labelInfo.setLabelName("普通人群");
            } else if (groupInfo.getGroup().equals("2")) {
                labelInfo.setLabel("2");
                labelInfo.setLabelName("慢病人群");
            } else if (groupInfo.equals(3)) {
                labelInfo.setLabel("3");
                labelInfo.setLabelName("65岁以上人群");
            } else {
                continue;
            }
            labelInfo.setLabelType("1");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            List<SignPatientLabelInfo> patientLabels = labelInfoDao.findByPatientAndStatus(labelInfo.getPatient(), 1);
            SignPatientLabelInfo healthLabel = null;
            SignPatientLabelInfo wjwGroup = null;
            String typeTwo = "1";
            for (SignPatientLabelInfo patientLabel : patientLabels) {
                if (patientLabel.getLabelType().equals("3")) {
                    typeTwo = "2";
                }
                if (patientLabel.getLabelType().equals("1")) {
                    wjwGroup = patientLabel;
                }
                if (patientLabel.getLabelType().equals("2")) {
                    healthLabel = patientLabel;
                }
            }
            if (healthLabel == null) {
                healthLabel = new SignPatientLabelInfo();
                healthLabel.setPatient(groupInfo.getPatient());
                healthLabel.setPname(groupInfo.getPname());
                healthLabel.setLabelType("2");
                healthLabel.setStatus(1);
                healthLabel.setCzrq(new Date());
            }
            if (typeTwo.equals("1")) {
                healthLabel.setLabel("1");
                healthLabel.setLabelName("健康人群");
            } else {
                healthLabel.setLabel("2");
                healthLabel.setLabelName("患病人群");
            }
            healthMap.put(groupInfo.getPatient(), healthLabel);
            if (wjwGroup != null) {
                wjwGroup.setLabel(labelInfo.getLabel());
                wjwGroup.setLabelName(labelInfo.getLabelName());
                wjwGroup.setCzrq(new Date());
                normalLabel.put(groupInfo.getPatient(), wjwGroup);
            } else {
                normalLabel.put(groupInfo.getPatient(), labelInfo);
            }
        }
        if (normalLabel.size() > 0) {
            labelInfoDao.save(normalLabel.values());
        }
        if (healthMap.size() > 0) {
            labelInfoDao.save(healthMap.values());
        }
        groupInfoDao.save(groups);
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}

+ 151 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/PushMsgTask.java

@ -0,0 +1,151 @@
package com.yihu.wlyy.statistics.task;
import com.yihu.wlyy.statistics.util.HttpClientUtil;
import com.yihu.wlyy.statistics.util.ImUtill;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
public class PushMsgTask {
	public static String url="";
	private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
	private static PushMsgTask instance;
	private static Object lock = new Object();
	public static PushMsgTask getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new PushMsgTask();
				instance.run();
			}
		}
		return instance;
	}
	/**
	 * 添加一条推送消息
	 * @param receiver 接收人
	 * @param type 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public void put(String receiver, String type, String title, String msg, String data) {
		try {
			JSONObject json = new JSONObject();
			json.put("receiver", receiver);
			json.put("type", type);
			json.put("title", title);
			json.put("msg", msg);
			json.put("data", data);
			queue.put(json);
		} catch (Exception e) {
			logger.error("添加到消息队列失败!", e);
			e.printStackTrace();
		}
	}
	public void put(JSONArray array) {
		if (array == null || array.size() == 0) {
			return;
		}
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			if (json == null) {
				continue;
			}
			try {
				queue.put(json);
			} catch (Exception e) {
				logger.error("批量添加到消息队列失败!", e);
			}
		}
	}
	private void run() {
		new Thread(new ConsumerTask()).start();
	}
	// 消费者
	class ConsumerTask implements Runnable {
		@Override
		public void run() {
			try {
				while (true) {
					// 如果queue为空,则当前线程会堵塞,直到有新数据加入
					JSONObject json = queue.take();
					logger.info("发送前:"+json);
					// 推送平台消息
					String receiver = json.containsKey("receiver") ? json.getString("receiver") : "";
					String type = json.containsKey("type") ? json.getString("type") : "";
					String title = json.containsKey("title") ? json.getString("title") : "";
					String msg = json.containsKey("msg") ? json.getString("msg") : "";
					String data = json.containsKey("data") ? json.getString("data") : "";
					boolean res = pushMessage(receiver, type, title, msg, data);
					if (res) {
						logger.info("消息推送成功!");
					} else {
						logger.error("消息推送失败!");
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	/**
	 * 消息推送
	 *
	 * @param receiver 消息接收人
	 * @param msgType 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public static boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
		try {
			//List<NameValuePair> params = new ArrayList<NameValuePair>();
			//params.add(new BasicNameValuePair("to", receiver));
			//params.add(new BasicNameValuePair("content", msg));
			//params.add(new BasicNameValuePair("contentType", msgType));
			//params.add(new BasicNameValuePair("title", title));
			//params.add(new BasicNameValuePair("summary", data));
			//String response = HttpClientUtil.post(url, params, "UTF-8");
			org.json.JSONObject participants = new org.json.JSONObject();
			participants.put("system",0);
			participants.put(receiver,0);
			org.json.JSONObject sessionObj  = ImUtill.createSession(url,participants,"0","系统消息","");
			if(sessionObj.getInt("status")==-1){
				throw  new RuntimeException(sessionObj.getString("message"));
			}
			org.json.JSONObject session = sessionObj.getJSONObject("data");
			ImUtill.sendImMsg(url,"system","系统",session.getString("id"),"1", msg,msgType);
			return true;
		} catch (Exception e) {
			logger.error("push message error:", e);
		}
		return false;
	}
}

+ 200 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/task/SignTeamAndGroupRunnable.java

@ -0,0 +1,200 @@
package com.yihu.wlyy.statistics.task;
import com.yihu.wlyy.statistics.Application;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.team.DoctorTeam;
import com.yihu.wlyy.statistics.model.team.DoctorTeamMember;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by lyr-pc on 2016/10/11.
 */
public class SignTeamAndGroupRunnable implements Runnable {
    long start = 0;
    long end = 0;
    SignFamilyDao signFamilyDao;
    DoctorTeamDao teamDao;
    DoctorTeamMemberDao teamMemberDao;
    JpaTransactionManager transactionManager;
    SignPatientLabelInfoDao labelInfoDao;
    public SignTeamAndGroupRunnable(Long start, Long end){
        this.start = start;
        this.end = end;
        this.signFamilyDao = SpringUtil.getApplicationContext().getBean(SignFamilyDao.class);
        this.teamDao = SpringUtil.getApplicationContext().getBean(DoctorTeamDao.class);
        this.teamMemberDao = SpringUtil.getApplicationContext().getBean(DoctorTeamMemberDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    @Override
    public void run() {
        boolean flag = true;
        while (flag) {
            PageRequest pageRequest = new PageRequest(0, 100);
            Page<SignFamily> signs = signFamilyDao.findByTypeAndSignSourceAndId(2, "1",start, end,pageRequest);
            if (signs != null && signs.getContent().size() < 100) {
                flag = false;
            }
            start = signs.getContent().get(signs.getContent().size() - 1).getId() + 1;
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务
            TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
            try {
                transform(signs);
                //事物提交
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
            }
        }
    }
    public void transform(Page<SignFamily> signs){
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<DoctorTeam> teams = new ArrayList<>();
        List<DoctorTeamMember> teamMembers = new ArrayList<>();
        List<DoctorPatientGroupInfo> groupList = new ArrayList<>();
        Map<String,SignPatientLabelInfo> labels =  new HashMap<>();
        List<SignFamily> signList = signs.getContent();
        for (SignFamily sign : signList) {
            try {
                if (StringUtils.isNotEmpty(sign.getTeamCode())) {
                    continue;
                }
                //建立团队
                DoctorTeam doctorTeam = new DoctorTeam();
                String doctorTeamCode = getCode();
                doctorTeam.setCode(doctorTeamCode);
                doctorTeam.setCzrq(new Date());
                doctorTeam.setName("团队名称:" + sign.getName());
                doctorTeam.setSignType("2");//家庭签约
                doctorTeam.setDel("1");
                teams.add(doctorTeam);
                //添加团队成员
                if (StringUtils.isNotEmpty(sign.getDoctor())) {
                    //添加全科
                    DoctorTeamMember wlyyDoctorTeamDoctor = new DoctorTeamMember();
                    wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
                    wlyyDoctorTeamDoctor.setMemberCode(sign.getDoctor());
                    wlyyDoctorTeamDoctor.setName(sign.getDoctorName());
                    wlyyDoctorTeamDoctor.setDel("1");
                    wlyyDoctorTeamDoctor.setType(2);
                    wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
                    wlyyDoctorTeamDoctor.setCode(getCode());
                    wlyyDoctorTeamDoctor.setCzrq(new Date());
                    teamMembers.add(wlyyDoctorTeamDoctor);
                }
                if (StringUtils.isNotEmpty(sign.getDoctorHealth())) {
                    //添加健康管理师
                    DoctorTeamMember wlyyDoctorTeamDoctor = new DoctorTeamMember();
                    wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
                    wlyyDoctorTeamDoctor.setMemberCode(sign.getDoctorHealth());
                    wlyyDoctorTeamDoctor.setName(sign.getDoctorHealthName());
                    wlyyDoctorTeamDoctor.setDel("1");
                    wlyyDoctorTeamDoctor.setType(3);
                    wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
                    wlyyDoctorTeamDoctor.setCode(getCode());
                    wlyyDoctorTeamDoctor.setCzrq(new Date());
                    teamMembers.add(wlyyDoctorTeamDoctor);
                }
                //添加患者和团队的关系
                DoctorTeamMember wlyyDoctorTeamPatient = new DoctorTeamMember();
                wlyyDoctorTeamPatient.setTeam(doctorTeamCode);
                wlyyDoctorTeamPatient.setMemberCode(sign.getPatient());
                wlyyDoctorTeamPatient.setName(sign.getName());
                wlyyDoctorTeamPatient.setDel("1");
                wlyyDoctorTeamPatient.setSignType("2");//家庭签约
                wlyyDoctorTeamPatient.setType(5);
                wlyyDoctorTeamPatient.setCode(getCode());
                wlyyDoctorTeamPatient.setCzrq(new Date());
                teamMembers.add(wlyyDoctorTeamPatient);
                if (StringUtils.isEmpty(sign.getIdcard())) {
                    System.out.println("error:sign-family-set-group:no-idcard:" + sign.getId());
                    continue;
                }
                int age = IdCardUtil.getAgeForIdcard(sign.getIdcard());
                String groupCode = "1";
                String groupName = "普通人群";
                if (age >= 65) {
                    groupCode = "3";
                    groupName = "65岁以上人群";
                }
                SignPatientLabelInfo label =  new SignPatientLabelInfo();
                SignPatientLabelInfo exLabelInfo = labelInfoDao.findByPatientAndLabelAndLabelTypeAndStatus(
                        sign.getPatient(), groupCode, "1", 1);
                if (exLabelInfo != null) {
                    continue;
                }
                label.setPatient(sign.getPatient());
                label.setPatient(sign.getName());
                label.setLabel(groupCode);
                label.setLabelName(groupName);
                label.setLabelType("1");
                label.setStatus(1);
                label.setCzrq(new Date());
                labels.put(sign.getPatient(),label);
                sign.setTeamCode(doctorTeamCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        teamDao.save(teams);
        teamMemberDao.save(teamMembers);
        labelInfoDao.save(labels.values());
        signFamilyDao.save(signList);
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}

+ 142 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/Contant.java

@ -0,0 +1,142 @@
package com.yihu.wlyy.statistics.util;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/6/1.
 */
public class Contant {
    //抽取数据的开始时间
    public static String startTime = "${start_time}";
    //抽取数据的结束时间
    public static String endTime = "${end_time}";
    //数据库类型
    public static class db_type {
        public static String oracle = "oracle";
        public static String mysql = "mysql";
    }
    /**
     * DateModel的map的key常量
     */
    public static class extract {
        public static final String computeKey1 = "oneKey";
        public static final String computeKey2 = "senondKey";
    }
    /**
     * 运算常量
     */
    public static class compute {
        public static final String add = "1"; //累加
        public static final String division = "2"; //相除
    }
    /**
     * 主维度常量
     */
    public static class main_dimension {
        public static final String time_day = "1";//时间维度 日
        public static final String time_week = "2";//时间维度  月
        public static final String time_month = "3";//时间维度 周
        public static final String time_year = "4";//时间维度 年
        public static final String area_province = "5";//行政区划 省
        public static final String area_city = "6";//行政区划 市
        public static final String area_town = "7";//行政区划 区县
        public static final String area_org = "8";//行政区划 机构
        public static final String area_team = "9";//行政区划  团队
    }
    /**
     * areaLevel 具体的值
     */
    public static class main_dimension_areaLevel {
        public static final String area_province = "1";//行政区划 省
        public static final String area_city = "2";//行政区划 市
        public static final String area_town = "3";//行政区划 区县
        public static final String area_org = "4";//行政区划 机构
        public static final String area_team = "5";//行政区划  团队
        public static String getAreaLevelByMainDimension(String key) {
            switch (key) {
                case main_dimension.area_province: {
                    return area_province;
                }
                case main_dimension.area_city: {
                    return area_city;
                }
                case main_dimension.area_town: {
                    return area_town;
                }
                case main_dimension.area_org: {
                    return area_org;
                }
                case main_dimension.area_team: {
                    return area_team;
                }
            }
            return "";
        }
    }
    /**
     * 主维度 时间维度
     */
    public static class main_dimension_timeLevel {
        public static final String year = "1";
        public static final String month = "2";
        public static final String week = "3";
        public static final String day = "4";
    }
    /**
     * 从维度常量
     */
    public static class slave_dimension {
        public static final String sex = "1";//性别
        public static final String age = "2";//年龄段
    }
    public static class slave_dimension_key {
        public static final String one = "one";
        public static final String two = "two";
    }
    public static class save_status {
        public static final String success = "1";
        public static final String fail = "0";
    }
    /**
     * 数据过滤用到的参量
     */
    public static class role {
        public static final String not_null = "1";//非空
    }
    public static class save {
        public static final String mysql = "1";
        public static final String redis = "2";
        public static final String es = "3";
    }
    public static class convert{
        public static String level_age_1="1";
        public static String level_age_2="2";
        public static String level_age_3="3";
        public static String level_age_4="4";
        public static String level_age_5="5";
        public static String level_age_6="6";
        public static String level_age_1_name="0~6";
        public static String level_age_2_name="7~18";
        public static String level_age_3_name="19~30";
        public static String level_age_4_name="31~50";
        public static String level_age_5_name="51~65";
        public static String level_age_6_name=">65";
    }
}

+ 720 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/DateUtil.java

@ -0,0 +1,720 @@
package com.yihu.wlyy.statistics.util;
import org.apache.commons.lang3.StringUtils;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateUtil {
	public static final String HH_MM = "HH:mm";
	public static final String HH_MM_SS = "HH:mm:ss";
	public static final String YY = "yy";
	public static final String YYYYMM = "yyyyMM";
	public static final String YYYYMMDD = "yyyyMMdd";
	public static final String YYYY_MM_DD = "yyyy-MM-dd";
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
	public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	/**
	 * 字符串转时间格式
	 */
	public static Date strToDate(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		else{
			int length = strDate.length();
			if(strDate.contains("-"))
			{
				if(length == 10)
				{
					 return strToDate(strDate,YYYY_MM_DD);
				}
				else if(length == 19)
				{
					return strToDate(strDate,YYYY_MM_DD_HH_MM_SS);
				}
			}
			else{
				if(length == 8)
				{
					return strToDate(strDate,YYYYMMDD);
				}
				else if(length == 14)
				{
					return strToDate(strDate,YYYYMMDDHHMMSS);
				}
			}
		}
		return null;
	}
	/**
	  * 获取现在时间
	  * 
	  * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	  */
	public static Date getNowDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(dateString, pos);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回短时间格式 yyyy-MM-dd
	 */
	public static Date getNowDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		String dateString = formatter.format(currentTime);
		return strToDate(dateString, YYYY_MM_DD);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate(String format) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return 返回短时间字符串格式yyyy-MM-dd
	 */
	public static String getStringDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(currentTime);
	}
	/**
	 * 获取时间 小时:分;秒 HH:mm:ss
	 * 
	 * @return
	 */
	public static String getTimeShort() {
		SimpleDateFormat formatter = new SimpleDateFormat(HH_MM_SS);
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}
	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDateLong(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateShort(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrLong(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(dateDate);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd
	 *
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrShort(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式时间转换为字符串 yyyy-MM-dd
	 *
	 * @param dateDate
	 * @param k
	 * @return
	 */
	public static String dateToStr(Date dateDate, String format) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式字符串转换为时间
	 *
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateAppendNowTime(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		strDate += " " + getTimeShort();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 得到现在时间
	 *
	 * @return
	 */
	public static Date getNow() {
		Date currentTime = new Date();
		return currentTime;
	}
	/**
	 * 提取一个月中的最后一天
	 *
	 * @param day
	 * @return
	 */
	public static Date getLastDate(long day) {
		Date date = new Date();
		long date_3_hm = date.getTime() - 3600000 * 34 * day;
		Date date_3_hm_date = new Date(date_3_hm);
		return date_3_hm_date;
	}
	/**
	 * 得到现在时间
	 *
	 * @return 字符串 yyyyMMdd HHmmss
	 */
	public static String getStringToday() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 得到现在小时
	 */
	public static String getHour() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String hour;
		hour = dateString.substring(11, 13);
		return hour;
	}
	/**
	 * 得到现在分钟
	 *
	 * @return
	 */
	public static String getTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String min;
		min = dateString.substring(14, 16);
		return min;
	}
	/**
	 * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
	 *
	 * @param sformat
	 *            yyyyMMddhhmmss
	 * @return
	 */
	public static String getUserDate(String sformat) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(sformat);
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
	 */
	public static String getTwoHour(String st1, String st2) {
		String[] kk = null;
		String[] jj = null;
		kk = st1.split(":");
		jj = st2.split(":");
		if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
			return "0";
		else {
			double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
			double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
			if ((y - u) > 0)
				return y - u + "";
			else
				return "0";
		}
	}
	/**
	 * 得到二个日期间的间隔天数
	 */
	public static String getTwoDay(String sj1, String sj2) {
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		long day = 0;
		try {
			Date date = myFormatter.parse(sj1);
			Date mydate = myFormatter.parse(sj2);
			day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		} catch (Exception e) {
			return "";
		}
		return day + "";
	}
	/**
	 * 时间前推或后推分钟,其中JJ表示分钟.
	 */
	public static String getPreTime(String sj1, String jj) {
		SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String mydate1 = "";
		try {
			Date date1 = format.parse(sj1);
			long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
			date1.setTime(Time * 1000);
			mydate1 = format.format(date1);
		} catch (Exception e) {
		}
		return mydate1;
	}
	/**
	 * 得到一个时间延后或前移几分钟的时间,nowdate为时间,delay为前移或后延的分钟数
	 */
	public static Date getNextMin(Date date, int delay) {
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MINUTE, delay);
			return cal.getTime();
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
	 */
	public static String getNextDay(String nowdate, int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
			String mdate = "";
			Date d = strToDate(nowdate, YYYY_MM_DD);
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			return "";
		}
	}
	// public static String getNextDay(Date d, int delay) {
	// try {
	// SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
	// String mdate = "";
	// long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
	// d.setTime(myTime * 1000);
	// mdate = format.format(d);
	// return mdate;
	// } catch (Exception e) {
	// return "";
	// }
	// }
	public static String getNextDay(Date d, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DATE, days);
		return dateToStrShort(c.getTime());
	}
	public static String getNextMonth(Date d, int months) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, months);
		return dateToStrShort(c.getTime());
	}
	public static String getNextYear(Date d, int year) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.YEAR, year);
		return dateToStrShort(c.getTime());
	}
	/**
	 * 判断是否润年
	 *
	 * @param ddate
	 * @return
	 */
	public static boolean isLeapYear(String ddate) {
		/**
		 * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
		 * 3.能被4整除同时能被100整除则不是闰年
		 */
		Date d = strToDate(ddate, YYYY_MM_DD);
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(d);
		int year = gc.get(Calendar.YEAR);
		if ((year % 400) == 0)
			return true;
		else if ((year % 4) == 0) {
			if ((year % 100) == 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	/**
	 * 返回美国时间格式 26 Apr 2006
	 *
	 * @param str
	 * @return
	 */
	public static String getEDate(String str) {
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(str, pos);
		String j = strtodate.toString();
		String[] k = j.split(" ");
		return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
	}
	/**
	 * 获取一个月的最后一天
	 *
	 * @param dat
	 * @return
	 */
	public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
		String str = dat.substring(0, 8);
		String month = dat.substring(5, 7);
		int mon = Integer.parseInt(month);
		if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
			str += "31";
		} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
			str += "30";
		} else {
			if (isLeapYear(dat)) {
				str += "29";
			} else {
				str += "28";
			}
		}
		return str;
	}
	/**
	 * 判断二个时间是否在同一个周
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isSameWeekDates(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
		if (0 == subYear) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
			// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}
		return false;
	}
	/**
	 * 产生周序列,即得到当前时间所在的年度是第几周
	 *
	 * @return
	 */
	public static String getSeqWeek() {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
		if (week.length() == 1)
			week = "0" + week;
		String year = Integer.toString(c.get(Calendar.YEAR));
		return year + week;
	}
	/**
	 * 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
	 *
	 * @param sdate
	 * @param num
	 * @return
	 */
	public static String getWeek(String sdate, String num) {
		// 再转换为时间
		Date dd = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(dd);
		if (num.equals("1")) // 返回星期一所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		else if (num.equals("2")) // 返回星期二所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
		else if (num.equals("3")) // 返回星期三所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
		else if (num.equals("4")) // 返回星期四所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
		else if (num.equals("5")) // 返回星期五所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		else if (num.equals("6")) // 返回星期六所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
		else if (num.equals("0")) // 返回星期日所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}
	/**
	 * 根据一个日期,返回是星期几的字符串
	 *
	 * @param sdate
	 * @return
	 */
	public static String getWeek(String sdate) {
		// 再转换为时间
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了,其范围 1~7
		// 1=星期日 7=星期六,其他类推
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}
	public static String getWeekStr(String sdate) {
		String str = "";
		str = DateUtil.getWeek(sdate);
		if ("1".equals(str)) {
			str = "星期日";
		} else if ("2".equals(str)) {
			str = "星期一";
		} else if ("3".equals(str)) {
			str = "星期二";
		} else if ("4".equals(str)) {
			str = "星期三";
		} else if ("5".equals(str)) {
			str = "星期四";
		} else if ("6".equals(str)) {
			str = "星期五";
		} else if ("7".equals(str)) {
			str = "星期六";
		}
		return str;
	}
	/**
	 * 两个时间之间的天数
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(String date1, String date2) {
		if (date1 == null || date1.equals(""))
			return 0;
		if (date2 == null || date2.equals(""))
			return 0;
		// 转换为标准时间
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		Date date = null;
		Date mydate = null;
		try {
			date = myFormatter.parse(date1);
			mydate = myFormatter.parse(date2);
		} catch (Exception e) {
		}
		long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 返回两个日期相差的天数
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(Date date1, Date date2) {
		if (date1 == null || date2 == null)
			return 0;
		long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
	 * 此函数返回该日历第一行星期日所在的日期
	 * 
	 * @param sdate
	 * @return
	 */
	public static String getNowMonth(String sdate) {
		// 取该时间所在月的一号
		sdate = sdate.substring(0, 8) + "01";
		// 得到这个月的1号是星期几
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int u = c.get(Calendar.DAY_OF_WEEK);
		String newday = DateUtil.getNextDay(sdate, 1 - u);
		return newday;
	}
	/**
	 * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
	 * 
	 * @param k 表示是取几位随机数,可以自己定
	 */
	public static String getNo(int k) {
		return getUserDate("yyyyMMddhhmmss") + getRandom(k);
	}
	/**
	 * 返回一个随机数
	 * 
	 * @param i
	 * @return
	 */
	public static String getRandom(int i) {
		Random jjj = new Random();
		if (i == 0)
			return "";
		String jj = "";
		for (int k = 0; k < i; k++) {
			jj = jj + jjj.nextInt(9);
		}
		return jj;
	}
	/**
	 * 根据用户生日计算年龄
	 */
	public static int getAgeByBirthday(Date birthday) {
		try {
			Calendar cal = Calendar.getInstance();
			if (cal.before(birthday)) {
				return 0;
			}
			int yearNow = cal.get(Calendar.YEAR);
			int monthNow = cal.get(Calendar.MONTH) + 1;
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
			cal.setTime(birthday);
			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH) + 1;
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
			int age = yearNow - yearBirth;
			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					if (dayOfMonthNow < dayOfMonthBirth) {
						age--;
					}
				} else {
					age--;
				}
			}
			return age;
		} catch (Exception e) {
			return 0;
		}
	}
	public static void main(String[] args) {
//		String hour = "12:22:12";
//		System.out.println(Time.valueOf(hour));
//		System.out.println(getNowDate());
//
		System.out.println(getNextYear(new Date(), -65));
	}
	public static int getNowMonth(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MONTH)+1;
	}
	public static int getNowYear(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR);
	}
}

+ 0 - 0
patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/HttpClientUtil.java


Some files were not shown because too many files changed in this diff